Windows下PowerShell监控Keepalived

时间:2021-12-24 07:18:24

一、背景

  某数据库服务器为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 = "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. 设置任务计划

Windows下PowerShell监控Keepalived

(Figure1:任务计划-常规)

Windows下PowerShell监控Keepalived

(Figure2:任务计划-操作)

4. 效果示意图:

Windows下PowerShell监控Keepalived

(Figure3:邮件和短信通知)

三、注意事项

  1. 采用的ISE编辑器:PowerShell ISE
  2. 查看PowerShell版本信息:Get-Host
  3. 刚开始使用Powershell,导入管理模块或者其他操作的时候会出现因为在此系统中禁止执行脚本的报错,报错内容如下:

Windows下PowerShell监控Keepalived

(Figure4:注意)

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

四、参考文献

如何查看PowerShell版本号

Powershell中禁止执行脚本解决办法

pstips

使用PowerShell通过Smtp发送邮件

powershell 发送邮件