【摘要】
實(shí)時(shí)掌握服務(wù)器運行狀態(tài)對系統管理員來(lái)說(shuō)非常重要,服務(wù)器出現問(wèn)題是第一時(shí)間知道可以保證及時(shí)處理,將意外損失降到最小。利用powershell可簡(jiǎn)單實(shí)現監控功能,并在服務(wù)器掉線(xiàn)或關(guān)鍵服務(wù)停止時(shí)發(fā)出郵件通知管理員,使管理員可以及時(shí)處理故障。
【正文】

如圖,除powershell腳本文件外,需要創(chuàng )建3個(gè)txt文件,分別為Servers.txt、Services.txt、Urls.txt。三個(gè)文件都是以csv格式導入,第一行內容需要保留,添加內容由第二行開(kāi)始
Servers.txt添加服務(wù)器名用于監控服務(wù)器在線(xiàn)情況

Services.txt添加服務(wù)器名及服務(wù)名用于監控關(guān)鍵服務(wù)運行情況

Urls.txt添加網(wǎng)站用于監控網(wǎng)頁(yè)是否能正常打開(kāi)

$Urls = import-csv Urls.txt
$Servers = import-csv Servers.txt
$Services = import-csv Services.txt
$mailcontent = $null
$mailFrom = "XXX@canway.net"
$mailTo = "XXX@canway.net"
$Credential = Get-Credential -Credential $mailFrom
While($true)
{
Foreach ($server in $Servers)
{
$hostname = $server.server
if (!(test-connection $hostname -count 2 -quiet))
{$date = Get-Date
$mailcontent = $mailcontent + "$hostname is offline $date `n"
Write-Host "$hostname is offline $date" -ForegroundColor Red}
}
Foreach ($service in $Services)
{
$Server = $Service.server
$ServiceName = $Service.service
If (!(test-connection $Server -count 2 -quiet))
{$date = Get-Date
$mailcontent = $mailcontent + "$Server is offline $date `n"
Write-Host "$Server is offline $date" -ForegroundColor Red}
Else
{$Servicestate = (Get-WmiObject -Class win32_service -ComputerName $Server|Where-Object{$_.Name -eq $ServiceName}).State
If($Servicestate -ne "Running")
{$date = Get-Date
$mailcontent = $mailcontent + "$ServiceName in $Server is not running! $date `n"
Write-Host "$ServiceName in $Server is not running! $date" -ForegroundColor Red}
}
}
Foreach($url in $Urls)
{
$Website = $url.website
Invoke-WebRequest $Website
If(!$?)
{$date = Get-Date
$mailcontent = $mailcontent + "$Website 無(wú)法連接 $date `n"
Write-Host "$Website 無(wú)法連接 $date" -ForegroundColor Red}
}
If($mailcontent -ne $null)
{
Send-MailMessage -Body $mailcontent -SmtpServer smtp.partner.outlook.cn -From $mailFrom -To $mailTo -Subject "Warning" -UseSsl -Credential $Credential -Port 587
}
$mailcontent = $null
sleep 3600
}
用1.2所列出的腳本內容創(chuàng )建powershell腳本,與Servers.txt、Services.txt、Urls.txt放在同一路徑下,用有權限的賬戶(hù)運行
當有任意一項檢查不通過(guò)時(shí),會(huì )發(fā)郵件通知管理員。如圖,修改以下位置可以自定義收件人和發(fā)件人。

運行腳本后會(huì )讓你填入郵箱密碼,之后腳本就會(huì )每個(gè)小時(shí)檢查一次,檢查不通過(guò)時(shí)發(fā)郵件到設定的收件人,腳本檢查間隔可自定義,如圖,初始設置為3600s


收到郵件如圖

選擇發(fā)件人郵箱后需要在下面的命令里修改Smtp服務(wù)器和端口號
Send-MailMessage -Body $mailcontent -SmtpServer smtp.partner.outlook.cn -From $mailFrom -To $mailTo -Subject"Warning" -UseSsl -Credential $Credential -Port 587
聯(lián)系客服