Powershell脚本,用于检测Apache服务器故障并启动重启

时间:2017-11-03 08:11:30

标签: powershell windows-server-2012 windows-server-2012-r2

我是一名Java程序员,我得到了一项任务,找出Apache服务器失败/超时的原因,因为它似乎每天至少发生5-10次。

我正在查看日志并找到了这些

File does not exist: C:/Apache2/htdocs/favicon.ico
File does not exist: C:/Apache2/htdocs/browserconfig.xml
File does not exist: C:/Apache2/htdocs/selfupdate
Invalid URI in request GET /../../../../../../../../../../../
Invalid method in request ABCD / HTTP/1.1
Invalid method in request QUALYS / HTTP/1.1

时不时地发生新事物,每天都会发生。我用谷歌搜索并尝试了一些修复,但新的东西似乎出现在日志中。

我确实在第一次失败,第二次失败以及随后的“重启服务”失败的属性中设置了恢复选项卡选项,然后选中了启用错误的停靠选项。

我决定编写一个PowerShell脚本来检查日志,并在失败时重启Apache服务器。

$services = Get-Service -Name Apache2.2

Get-Service | ? {
  $services -contains $_.Name -and $_.fFailureActionsOnNonCrashFailures
-eq ‘True’
} | Restart-Service

运行Get-Service -Name“Apache2.2”| Select-Object -Property *

给了我

    Name : Apache2.2 
    RequiredServices : {Afd, Tcpip} 
    CanPauseAndContinue : False 
    CanShutdown : False 
    CanStop : True 
    DisplayName : Apache2.2 
    DependentServices : {} 
    MachineName : . 
    ServiceName : Apache2.2 
    ServicesDependedOn : {Afd, Tcpip} 
    ServiceHandle : 
    Status : Running 
    ServiceType : Win32OwnProcess 
    Site : 
    Container :

请帮忙。

我现在正在编写一个java程序(JAR文件),它将以管理员身份启动PowerShell并运行脚本以重启Apache。然后通过任务计划程序将此JAR文件设置为每3分钟运行一次。

我想知道如何通过PowerShell检查故障,而不是盲目重启。任何更好的解决方案/建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

What I would do is find the correlating event in the event logs, for when the service stops.  Then right click and create a triggered script or email notification.  The triggered PowerShell script would look like this.

$serviceCheck = Get-Service -Name Apache 2.2 | select status

if ($serviceCheck -eq "Running")
{
    #donothing
}


else
{

  #send email here and restart service

}


Another option would be to run the script as a function and set a sleep timer so it only runs every 5 minutes.  That would look like this:

function Check-Service{

$serviceCheck = Get-Service -Name Apache 2.2 | select status

    if ($serviceCheck.Status -eq "Running")
            {
                          #donothing
            }


    else
            {

                  #send email here and restart service

                 #you can also send an email from here, just make sure you know the smtp server address

            }


        }