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('\n') 

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

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

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

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

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

转载于:https://www.cnblogs.com/chenglee/p/7808785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值