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

 

四、參考文獻

如何查看PowerShell版本號

Powershell中禁止執行腳本解決辦法

pstips

使用PowerShell通過Smtp發送郵件

powershell 發送郵件