利用Python寫了簡單測試主機是否存活腳本,此腳本不適於線上使用,因為網絡延遲、丟包現象會造成誤報郵件,那麼後續會更新判斷三次ping不通後再發報警郵件,並啟用多線程處理。
#!/usr/bin/env python
# coding:UTF-8
import time
import pexpect
import smtplib
from email.mime.text import MIMEText
mail_host = "smtp.163.com" #定義smtp服務器
mail_to = "[email protected]" #郵件收件人
mail_from = "[email protected]" #郵件發件人
mail_pass = "123456" #郵件發件人郵箱密碼
while True:
def Mail(error_ip):
date = time.strftime('%Y-%m-%d %H:%M:%S')
msg = MIMEText("%s Ping %s failed from 255.252." % (date, error_ip))
msg['Subject'] = "Ping %s failed." % error_ip #定義郵件主題
msg['From'] = mail_from
msg['To'] = mail_to
try:
s = smtplib.SMTP() #創建一個SMTP()對象
s.connect(mail_host, "25") #通過connect方法連接smtp主機
s.starttls() #啟動安全傳輸模式
s.login(mail_from,mail_pass) #郵箱賬戶登錄認證
s.sendmail(mail_from, mail_to, msg.as_string()) #郵件發送
s.quit() #斷開smtp連接
except Exception, e:
print str(e)
ip_list = ['192.168.18.10',
'192.168.18.11',
'192.168.18.12']
for ip in ip_list:
ping = pexpect.spawn('ping -c 1 %s' % ip)
check = ping.expect([pexpect.TIMEOUT,"1 packets transmitted, 1 received, 0% packet loss"],2) #2代表超時時間
if check == 0:
Mail(ip)
print "Ping %s failed,Have email." % ip
if check == 1:
print "Ping %s successful." % ip
print "Sleep 10s..."
time.sleep(10)
#直接運行
# python ping.py
Ping 192.168.18.10 successful.
Ping 192.168.18.11 successful.
Ping 192.168.18.12 successful.
Sleep 10s...
無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm
CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm
《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡