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 发送邮件