• python监控端口脚本[jkport1.0.py]


    此脚本根据端口判断进程是否存活, 如果有指定的端口就证明进程是没问题的, 如果检测不到端口就是说业务进程已经挂掉了, 此时自动重启程序, 不多说下面请看脚本

    创建脚本

    我这里模拟的是nginx, 监控端口是9999, 如果您的是8080或者80, 可以自行更改,记得启动程序命令也需要修改喔,

    这个脚本是linux中的, 如果是windows中的请看这里Windows server利用批处理脚本判断端口, 启动tomcat原理都是一样的, 换汤不换药.

    里面也支持邮件提醒功能, 需要的自行配置.

    #!/usr/bin/env python
    #!coding=utf-8
    import os
    import time
    import sys
    import smtplib
    from email.mime.text import MIMEText
    from email.MIMEMultipart import MIMEMultipart
    
    def sendsimplemail (warning):
        msg = MIMEText(warning)
        msg['Subject'] = 'python first mail'
        msg['From'] = 'root@localhost'
        try:
            smtp = smtplib.SMTP()
            smtp.connect(r'pop.qq.com')
            smtp.login('mail@qq.com', 'mail_passwd')
            smtp.sendmail('mail@qq.com', ['mail@qq.com'], msg.as_string())
            smtp.close()
        except Exception, e:
            print e
    
    while True:
        Pro_status = os.popen('netstat -tulnp | grep nginx','r').readlines()
        now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        try:
            if Pro_status == []:
                os.system('service nginx start')
                new_Pro_status = os.popen('netstat -tulnp | grep nginx','r').readlines()
                str1 = ''.join(new_Pro_status)
                port = str1.split()[3].split(':')[-1]
                if port != '9999':
                    print 'nginx start fail ...'
                else:
                    print 'nginx start success ...'
                    sendsimplemail(warning = "This is a warning!!!")
            else:
                print now_time , 'nginx 进程正常运行中 ... '
            time.sleep(10)
        except KeyboardInterrupt:
            sys.exit('
    ') 

    脚本可以放在任意位置,启动方式: 守护进程

    我的启动方式是, 守护进程nohup, 然后把打印的结果输入到日志文件中, 我再py脚本中并没有配置输出日志, 我这个加上的是标准输出, 下面是启动方式

    nohup python -u jkport.py >>time.log 2>&1 &
    

    看上面已经看出来, 我的脚本名字是jkport.py, 日志名字是time.log, 没5秒把监控到的信息输入进来, 一旦发现程序挂掉, 会自动启动, 如果检测到程序存在, 信息提示正常运行中

    如有问题,请自行检测或反馈, 谢谢.

  • 相关阅读:
    HttpCookie类
    WebClient类
    最大流算法 ISAP 模板 和 Dinic模板
    拓扑序+dp Codeforces Round #374 (Div. 2) C
    二分 Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) D
    线段树 或者 并查集 Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) C
    无源无汇有上下界的最大流
    并查集+bfs+暴力滑窗 Codeforces Round #356 (Div. 2) E
    dfs Codeforces Round #356 (Div. 2) D
    cookie+session
  • 原文地址:https://www.cnblogs.com/chenglee/p/7808785.html
Copyright © 2020-2023  润新知