2009-03-19 10 views
11

He visto la pregunta "¿Puedes ejecutar Monit en Windows?" Y, a menos que quieras usar una VM, la respuesta parece ser no.Any Monit equivalentes similares para Windows OS?

Entonces ... ¿hay alguna aplicación pequeña similar a un monit en realidad para el sistema operativo Windows? Lo que busco no es solo la monitorización (de la que existen cientos de aplicaciones), sino también la posibilidad de ejecutar un script o reiniciar un servicio. Por ejemplo, monitoree una página web y reinicie Tomcat si esa página deja de responder (no puede simplemente mirar el servicio, porque el servicio aún se está ejecutando pero no responde adecuadamente).

Esto es para una aplicación pequeña, no una aplicación grande, por lo que no se desean soluciones costosas/costosas.

+0

Ja! - una pregunta y respuesta de 7 años puesta en espera. –

Respuesta

6

No encontré nada que se ajuste a mis necesidades, así que aprendí un poco de scripts de Powershell y obtuve una solución que también debería ser útil para otros. Asumiendo una plataforma de Windows (de lo contrario utiliza monit!), Powershell es realmente potente y fácil.

script de ejemplo-monitor.ps1:

$webClient = new-object System.Net.WebClient 

################################################### 
# BEGIN USER-EDITABLE VARIABLES 

# the URL to ping 
$HeartbeatUrl = "http://someplace.com/somepage/" 

# the response string to look for that indicates things are working ok 
$SuccessResponseString = "Some Text" 

# the name of the windows service to restart (the service name, not the display name) 
$ServiceName = "Tomcat6" 

# the log file used for monitoring output 
$LogFile = "c:\temp\heartbeat.log" 

# used to indicate that the service has failed since the last time we checked. 
$FailureLogFile = "c:\temp\failure.log" 

# END USER-EDITABLE VARIABLES 
################################################### 

# create the log file if it doesn't already exist. 
if (!(Test-Path $LogFile)) { 
    New-Item $LogFile -type file 
} 

$startTime = get-date 
$output = $webClient.DownloadString($HeartbeatUrl) 
$endTime = get-date 

if ($output -like "*" + $SuccessResponseString + "*") { 
    # uncomment the below line if you want positive confirmation 
    #"Success`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile 

    # remove the FailureLog if it exists to indicate we're in good shape. 
    if (Test-Path $FailureLogFile) { 
     Remove-Item $FailureLogFile 
    } 

} 
else { 
    "Fail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile 

    # restart the service if this is the first time it's failed since the last successful check. 
    if (!(Test-Path $FailureLogFile)) { 
     New-Item $FailureLogFile -type file 
     "Initial failure:" + $startTime.DateTime >> $FailureLogFile 
     Restart-Service $ServiceName 
    } 
} 

La única lógica en este guión es que sólo se tratará de reiniciar el servicio una vez después de un fallo inicial. Esto es para evitar una situación en la que un servicio tarda un rato en reiniciarse, y mientras se reinicia, el monitor sigue viendo la falla y se reinicia de nuevo (bucle infinito malo). De lo contrario, puede hacer casi cualquier cosa, como agregar notificaciones por correo electrónico, o hacer más que simplemente reiniciar un servicio.

Este script se ejecutará una vez, lo que significa que tendrá que controlar su repetición externamente. Podría ponerlo en un bucle infinito en el guión, pero eso parece un poco escamoso. Utilicé el Programador de tareas de Windows, ejecutándolo de esta forma: Programa: Powershell.exe argumentos: -comando "C: \ projects \ foo \ scripts \ monitor.ps1" -noprofile Inicio en: C: \ proyectos \ foo \ scripts

También podría utilizar un programador más robusto como VisualCron, conectarlo a un servicio de Windows o mediante un programador de servidor de aplicaciones como Quart.NET. En mi caso, el programador de tareas funciona bien.

0

Estoy usando ipsentry de RGE Inc (http://www.ipsentry.com/).

Lo he usado durante varios años, me ha ahorrado muchas veces.

Sin afiliación con ellos, esto no es un anuncio, solo información de un cliente satisfecho.

0

Esto se puede realizar al menos parcialmente con el Administrador de control de servicios que se envía con Windows. Supervisa las aplicaciones de servicio y puede iniciarlas automáticamente en el arranque, reiniciarlas cuando falla, etc. Escribir su aplicación como un servicio es una opción, pero si no puede escribir la aplicación como un servicio, entonces puede intentar envolver el proceso. usando srvany.exe en el Kit de recursos de Windows.

Más información acerca de cómo escribir un servicio: https://support.microsoft.com/en-us/kb/137890

En cuanto a las características reales de control, no estoy del todo seguro de lo que está disponible, o la extensión de las capacidades de SCM.

1

que ajustar un poco el guión Dan Tanner cuando no pudo conectar, mostraron un error y no se reiniciaron el servicio

$webClient = new-object System.Net.WebClient 

################################################### 
# BEGIN USER-EDITABLE VARIABLES 

# the URL to ping 
$HeartbeatUrl = "http://localhost:8080/" 

# the response string to look for that indicates things are working ok 
$SuccessResponseString = "Apache" 

# the name of the windows service to restart (the service name, not the display name) 
$ServiceName = "Tomcat6" 

# the log file used for monitoring output 
$LogFile = "c:\temp\log.log" 

# used to indicate that the service has failed since the last time we checked. 
$FailureLogFile = "c:\temp\log2.log" 

# END USER-EDITABLE VARIABLES 
################################################### 

# create the log file if it doesn't already exist. 
if (!(Test-Path $LogFile)) { 
    New-Item $LogFile -type file 
} 

$startTime = get-date 
try { 
    $output = $webClient.DownloadString($HeartbeatUrl) 
    $endTime = get-date 

    if ($output -like "*" + $SuccessResponseString + "*") { 
     # uncomment the below line if you want positive confirmation 
     #"Success`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile 

     # remove the FailureLog if it exists to indicate we're in good shape. 
     if (Test-Path $FailureLogFile) { 
      Remove-Item $FailureLogFile 
     } 

    } 
    else { 
     "Fail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> $LogFile 

     # restart the service if this is the first time it's failed since the last successful check. 
     if (!(Test-Path $FailureLogFile)) { 
      New-Item $FailureLogFile -type file 
      "Initial failure:" + $startTime.DateTime >> $FailureLogFile 
      Restart-Service $ServiceName 
     } 
    } 
    }catch [Net.WebException] { 
     New-Item $FailureLogFile -type file 
     "Initial failure:" + $startTime.DateTime + $_.Exception.ToString() >> $FailureLogFile 
     Restart-Service $ServiceName 
} 
Cuestiones relacionadas