Windows下PowerShell監控Keepalived

1、背景php

  某數據庫服務器爲CentOS,想要監控Keepalived的VIP是否有問題,經過郵件進行報警,但這臺機器不能上外網,如今只能在Windows下經過PowerShell來完成發郵件預警。html

 

2、腳本詳情shell

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 = "bbs@126.com"
$smtpPassword = "mypsw"
#create the mail message
$mail = New-Object System.Net.Mail.MailMessage
#set the addresses
$MailAddress="bbs@126.com"
$MailtoAddress="1343xxx@139.com"
$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. 設置任務計劃 tcp

wps24A4.tmp

(Figure1:任務計劃-常規) 編輯器

wps24B4.tmp

(Figure2:任務計劃-操做) spa

 

4. 效果示意圖: .net

wps24B5.tmp

(Figure3:郵件和短信通知) code

 

3、注意事項

  1. 採用的ISE編輯器:PowerShell ISE
  2. 查看PowerShell版本信息:Get-Host
  3. 剛開始使用Powershell,導入管理模塊或者其餘操做的時候會出現由於在此係統中禁止執行腳本的報錯,報錯內容以下:

wps9E58.tmp

(Figure4:注意)

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

 

4、參考文獻

如何查看PowerShell版本號

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

pstips

使用PowerShell經過Smtp發送郵件

powershell 發送郵件

相關文章
相關標籤/搜索