iT邦幫忙

1

監測伺服器狀態-失聯時發MAIL通知

情境,每5分鐘檢查主機群,當某主機失去連線時,發送MAIL通知 admin@abc.com

1.建立 gogogo.cmd 內容如下:

powershell -file d:\PingTest.ps1

2.將 gogogo.cmd,加到工作排程器,每5分鐘(可自訂)執行一次.

3.建立 D:\PingTest.ps1 ,內容如下

# 定義欲監測之主機,Hostname或IP
$servers = "AP01","192.168.0.1","sql1","10.10.1.76"

#flush /register dns / test connect servers
Foreach($s in $servers)
{
  if(!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -ea 0 -quiet))
  {
   "Problem connecting to $s"
   "Flushing DNS"
   ipconfig /flushdns | out-null
   
   "Registering DNS"
   ipconfig /registerdns | out-null
   
  "doing a NSLookup for $s"
   nslookup $s
   #when re-ping fail, Send mail
   "Re-pinging $s"
     if(!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -ea 0 -quiet))
      {"Problem still exists in connecting to $s"
	  
	#Mail content 
	$Emailbody=
@" 
<span style="font-family: 微軟正黑體;">
<H1>您好,主機 <font color=red>$s</font> 已失聯,請查看情況,謝謝</H1>
</span>
"@

	#SMTP sender 
	$anonUser = "Alarm@abc.com" 
	$anonPass = ConvertTo-SecureString "89OP:./}+" -AsPlainText -Force 
	#Send mail 
	Send-MailMessage -To "admin@abc.com" -Subject "【警告】您的主機'$s'異常!" -Bodyashtml $Emailbody -From "Alarm@abc.com"  -SmtpServer "ssl.abc.com" -Encoding ([System.Text.Encoding]::UTF8) 
	  	  }
       ELSE {"Resolved problem connecting to $s"} #end if
   } # end if
} # end foreach

注意事項:
請確認執行工作排程的帳戶及電腦,有權限發送EMAIL(有的SMTP有驗證及轉發限制)
請自行修改 寄件/收件人/SMTP主機/$servers值

參考:
https://blogs.technet.microsoft.com/heyscriptingguy/2012/02/24/use-powershell-to-test-connectivity-on-remote-servers/


1 則留言

2
尼克
iT邦高手 1 級 ‧ 2017-11-22 09:42:45

可以將預監測得伺服器列表,放置到外面檔案嗎?
以便維護

喬可 iT邦新手 3 級 ‧ 2017-11-22 10:49:19 檢舉

準備一個txt檔
servers.txt 內容如下

"AP01","192.168.0.1","sql1","10.10.1.76"

把下面這串

$servers = "AP01","192.168.0.1","sql1","10.10.1.76"

換成下面這串

$servers = gc servers.txt

即可.

尼克 iT邦高手 1 級 ‧ 2017-11-22 11:27:32 檢舉

感恩!

我要留言

立即登入留言