python 用ping循环监测服务器心跳

        循环用ping命令监测服务器是否在运行。本脚本为循环监测,每次监测间隔3秒钟。当错误达到一定数量时,发邮件告知。为了防止脚本错误退出,建议写一个启停的脚本放在crontab中调用,具体做法参见:http://www.simonzhang.net/?p=697

#!/usr/local/bin/python
# -------------------------------------------------------------------------------
# Filename:    check_ip.py
# Revision:    1.0
# Date:        2012-03-20
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
# -------------------------------------------------------------------------------
import pexpect
import time
import smtplib
from email.mime.text import MIMEText

#### base set
#### 配置要监测的IP地址
check_ip ={"192.168.1.100":0
           ,"192.168.1.101":0
           ,"192.168.1.102":0}
#### 定义几次ping不通发邮件
send_mail_limit = [3,4]
#### 发邮件的邮件服务器配置
mail_host = 'smtp.exmail.qq.com'
mail_user = 'simon-zzm@qq.net'
mail_pwd = 'XXXXXXX'
mail_to = "simon-zzm@139.com"
mail_cc = "simon-zzm@163.com"
####

def mail_warn(error_ip):
    content = 'Ping IP %s is error!'%error_ip
    msg = MIMEText(content)
    msg['From'] = mail_user
    msg['Subject'] = 'warnning %s'%error_ip
    msg['To'] = mail_to
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pwd)
        s.sendmail(mail_user,[mail_to,mail_cc],msg.as_string())
        s.close()
    except Exception ,e:
        print e

def check(get_ip):
    try :
        ping=pexpect.spawn("ping -c1 %s" % (get_ip))
        check_result =ping.expect([pexpect.TIMEOUT,"1 packets transmitted, 1 received, 0% packet loss"],2)
    except :
        check_result = 0
    return check_result

def main():
    while True :
        for i in check_ip:
            check_status = check("%s"%i)
            if check_status == 1:
                check_ip["%s"%i] = 0
            else :
                check_ip["%s"%i] +=1
            if check_ip["%s"%i] in send_mail_limit :
                mail_warn("%s"%i)
        time.sleep(3)

if __name__ == "__main__":
    main()

发表评论

电子邮件地址不会被公开。 必填项已用*标注