標籤:python監控主機是否存活 smtplib pexpect
利用python寫了簡單測試主機是否存活指令碼,此指令碼不適於線上使用,因為網路延遲、丟包現象會造成誤判郵件,那麼後續會更新判斷三次ping不通後再發警示郵件,並啟用多執行緒。
#!/usr/bin/env python# coding:UTF-8import timeimport pexpectimport smtplibfrom email.mime.text import MIMETextmail_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...
本文出自 ““企鵝”那點事兒” 部落格,請務必保留此出處http://lizhenliang.blog.51cto.com/7876557/1649664
Python監控主機是否存活並發警示郵件