Python脚本对linux 服务器超时进程进行查杀

本博客对于不会写sh脚本的同学们希望有帮助。

import os
import logging
logging.basicConfig(filename="test.log",filemode="w",format="%(asctime)s %(name)s:%(levelname)s:%(message)s",datefmt="%d-%M-%Y %H:%M:%S", level=logging.INFO)
log = logging.getLogger()
job="business_info"
#popen可以实现一个“管道”,从这个命令获取的值可以在python中继续被使用
os.popen("ps aux|grep %s" % job).read()
for line in os.popen("ps aux|grep %s" % job):
        #取消获取数据的空格
        pid=line[8:15].strip()
        time=line[58:65].strip()
        title=line[66:].strip()
        #在线时间
        aline_time = int(line[58:61].strip())
        print("pid:%s         time:%s         title:%s" %(pid,time,title))
        #print("aline_time:%s" % aline_time)
        #设置超时时间
        if aline_time>=5:
            #结束时间超过5分钟的进程
            os.popen("kill %s" % pid)
            # 写入日志
            log.info("pid:%s         time:%s         title:%s" % (pid, time, title))
log.info("本轮巡检结束")




 

你可能感兴趣的:(Python脚本对linux 服务器超时进程进行查杀)