1. 程式人生 > >Windows下PowerShell監控Keepalived

Windows下PowerShell監控Keepalived

一、背景

  某資料庫伺服器為CentOS,想要監控Keepalived的VIP是否有問題,通過郵件進行報警,但這臺機器不能上外網,現在只能在Windows下通過PowerShell來完成發郵件預警。

二、指令碼詳情

1.建立名為:ping-ip.ps1的PS指令碼,程式碼如下所示:

# ping 192.168.1.51
Test-Connection 192.168.1.51 -Count 2

If ($? -ne "True"){
    Write-Host $address"連線失敗"
    # send mail
    powershell.exe D:\ps\send-mail.ps1
}
Else { Write-Host $address"連線成功" $tcp.Close() }

2.建立名為:send-mail.ps1的PS指令碼,程式碼如下所示:

#mail server configuration
$smtpServer = "smtp.126.com"
$smtpUser = "[email protected]"
$smtpPassword = "mypsw"
#create the mail message
$mail = New-Object System.Net.Mail.MailMessage
#set the addresses
$MailAddress="[email protected]" $MailtoAddress="[email protected]" $mail.From = New-Object System.Net.Mail.MailAddress($MailAddress) $mail.To.Add($MailtoAddress) #set the content $mail.Subject = "XX預警"; $mail.Priority = "High" $mail.Body = "VIP 失效了 $(Get-Date -Format 'M-d H:m:s')"
#$filename="file" #$attachment = new-Object System.Net.Mail.Attachment($filename) #$mail.Attachments.Add($attachment) #send the message $smtp = New-Object System.Net.Mail.SmtpClient -argumentList $smtpServer $smtp.Credentials = New-Object System.Net.NetworkCredential -argumentList $smtpUser,$smtpPassword $smtp.Send($mail)

3. 設定任務計劃

wps24A4.tmp

(Figure1:任務計劃-常規)

wps24B4.tmp

(Figure2:任務計劃-操作)

4. 效果示意圖:

wps24B5.tmp

(Figure3:郵件和簡訊通知)

三、注意事項

  1. 採用的ISE編輯器:PowerShell ISE
  2. 檢視PowerShell版本資訊:Get-Host
  3. 剛開始使用Powershell,匯入管理模組或者其他操作的時候會出現因為在此係統中禁止執行指令碼的報錯,報錯內容如下:

wps9E58.tmp

(Figure4:注意)

PS C:\Windows\system32> set-ExecutionPolicy RemoteSigned

四、參考文獻