Python監控主機是否存活並以郵件警示

來源:互聯網
上載者:User
利用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 = "baojingtongzhi@163.com" #郵件收件者 mail_from = "monitor@163.com"   #郵件寄件者 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監控主機是否存活並以郵件警示有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.