[VBScript] 監控服務 Windows Server 2005以下(含) 設定

之前在Win Server 2012 R2的機器上曾經發現一個功能

就是可以對服務的事件建立Trace 詳情可以參考

Administering Windows Server 2012 R2: Monitoring and Auditing

那如果是2012 R2以下的版本 但是又想要監控服務的狀態怎麼辦?

所以只好寫VBSript 其實也有很多寫法 我記得powershell 也可以 

但相對起來 powershell 我對VBScript比較熟悉 

所以這裡就會用VBScript來記錄

以下是vbscript的內容 請建立一個檔案 XXX.vbs (Or MonitorService.vbs)

請注意下8個參數(藍字) 請再自行調整囉 不然是不能用的!!!

1.strService = "ServiceName" => 請輸入你的Service Name 不是顯示名稱喔 是服務名稱如下圖 紅框的服務名稱

2.objMessage.Subject = "Email主旨"  => 這裡修改你要通知的Email 主旨內容

3.objMessage.From = "Sender"  => 寄件者

4.objMessage.To = "Receiver" => 收件者

5.objMessage.HTMLBody = "Hi Everyone <br/>" &_
"<br/>" &_
"&nbsp;XXX Service 未啟動 請確認相關程式 <br/>" &_
"<br/>" &_
"IMS_U <br/>"
=> Email的內容

6.objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2  =>(1) 使用 local SMTP, (2) 為外部 SMTP

7.objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "SMTP Server" =>smtp server ip or domain name

8.objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 => smtp server port 25 為default

Dim objWMIService, objProcess, colProcess, Status, strHost, strService

strHost = "."
strService = "ServiceName"
Status= false

If Len(strService) < 1 Then
    Wscript.echo "Please enter a service name"
    WScript.Quit
End If 

Set objWMIService =GetObject("winmgmts:"& "{impersonationLevel=impersonate}!\\" & strHost & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("SELECT DisplayName, Status, State FROM Win32_Service WHERE Name = '" & strService & "'")


For Each objProcess in colProcess
	If InStr(objProcess.Name,strService) > 0 And objProcess.State = "Running" Then
		 Status = true
	End If
Next
 
If Status = true Then
    Wscript.echo "Service: " & UCase(strHost) & " " & strService & " Running"
		
Else
    Wscript.echo "Service: " & UCase(strHost) & " " & strService & " Not Running"
	  SendMail
End If

Sub SendMail
Dim objMessage
Set objMessage = CreateObject("CDO.Message")

objMessage.Subject = "Email主旨"
objMessage.From = "Sender"
objMessage.To = "Receiver"
objMessage.HTMLBody = "Hi Everyone <br/>" &_
"<br/>" &_
"&nbsp;XXX Service 未啟動 請確認相關程式 <br/>" &_
"<br/>" &_
"IMS_U <br/>"

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "SMTP Server"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
objMessage.Send

Set objMessage = Nothing
End Sub

設定完成之後

就是要設定Scheduler

1.排程的時間:我是設定一小時會執行一次檢查該服務

2.  執行:選擇"啟動程式"
程式或指令碼(P): "C:\Windows\System32\cscript.exe"
新增引數(可省略)(A): 請填入該 *.vbs的路徑

這樣就完成囉!!

-----------------------------------------

有時在會走之前你就得跑

你不解決問題 就等問題解決你