进程监控的python脚本

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用


class_config.py

#!/usr/bin/env python
#coding:utf-8

'''此处定义邮件的相关参数'''
class Mail_conf():
    sender = 'fyxichen@126.com'
    receiver = 'fyxichen@126.com'
    host = 'smtp.126.com'
    port = '25'
    user = 'fyxichen@126.com'
    passwd = '123456'
    log_dir = 'sendmail_err_log'

'''此处定义监控程序以及启动路径,启动路径不能包含中文'''
#用法{程序名称:启动口令}
#配置重启日志名称,不能为空。
class ProgramPath():
    Path =  {'RTX.exe':'/home/admin',
             'Foxmail.exe':'D:\Program Files (x86)\jisupdf',
             'QQ.exe':'D:\Program Files (x86)\Tencent\QQ\Bin\qq.exe',}
    Restart_Log_path = 'Restart_log_path' 

SendMail.py

#!/usr/bin/env python
#coding:utf-8
import string,time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from class_config import Mail_conf
'''发送邮件类'''
def send_mail(Title,context):        

    msg = MIMEText(context,'plain','utf-8')
    msg['Subject'] = Header(Title,'utf-8')
    try:
        smtp = smtplib.SMTP()  
        smtp.connect(Mail_conf.host,Mail_conf.port)  
        smtp.login(Mail_conf.user, Mail_conf.passwd)  
        smtp.sendmail(Mail_conf.sender, Mail_conf.receiver, msg.as_string())  
        smtp.quit()
    except Exception,e:
        Writelog = open(Mail_conf.log_dir,'ab')
        log = '%s-->%s\n' % (time.strftime('%Y-%m-%d %H:%M:%S'),str(e))
        print log
        Writelog.write(log)
        Writelog.close()
if __name__ == "__main__":
    send_mail("Test Mail","这是一封测试邮件,更改邮箱配置在class_config.py中配置")
 



ProcessMoniter.py

#!/usr/bin/env python
#coding:utf-8
import psutil,time
import subprocess
from class_config import ProgramPath
     
def monitor():

     Time = time.time()
     log = open(ProgramPath.Restart_Log_path,'ab+')
     log.write('****************%s****************\n' % time.strftime('%Y-%m-%d %H:%M:%S'))
     log.close()
     while True:
         ProcessName = ProgramPath.Path.keys()
         Process = psutil.process_iter()
         for i in Process:
             try:
                 if i.name() in ProcessName:
                     ProcessName.remove(i.name())
             except Exception,e:
                 pass
         for i in ProcessName:
             try:
                 Restart = subprocess.Popen(ProgramPath.Path[i],shell=False)
             except Exception,e:
                 err_log = '%s-->%s\n' % (time.strftime('%Y-%m-%d %H:%M:%S'),str(e).strip())            
                 log = open(ProgramPath.Restart_Log_path,'ab+')
                 log.seek(-(len(str(e))),2)
                 if log.readline().strip() == str(e).strip():
                     if Time + 60 > time.time():
                         pass
                     else:
                         log.seek(0,2)
                         log.write(err_log)
                         log.close()
                         Time = time.time()
                 else:
                     log.seek(0,2)
                     log.write(err_log)
                     log.close()
                     Time = time.time()
         time.sleep(2)
if __name__ == "__main__":
    monitor() 



Net_io.py

#!/usr/bin/env python
#coding:utf-8
import psutil
import time
import sys
from optparse import OptionParser
parser = OptionParser()  
parser.add_option("-t", "--time", dest="time",
                  help="此参数可查看当前下载占的带宽,-t是测试时间", metavar="10")  

def Net_io(s):
    x = 0
    sum = 0
    while True:
        if x >= s:
            break
        r1 = psutil.net_io_counters().bytes_recv
        time.sleep(1)
        r2 = psutil.net_io_counters().bytes_recv
        y = r2 - r1
        print "%.2f Kb/s" % (y / 1024.0)
        sum += y
        x += 1
    result = sum / x
    print "\033[1;32m %s秒内平均速度:%.2f Kb/s \033[1;m"  % (x,result / 1024.0)
if __name__ == "__main__":
    (options, args) = parser.parse_args()  
    if options.time:
        Net_io(options.time)
    else:
        Net_io(10)

sysinfo.py

#!/usr/bin/env python
#coding:utf-8
import psutil
import time
import sys

def Sysinfo():
    Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(psutil.boot_time()))  
    time.sleep(0.5)
    Cpu_usage = psutil.cpu_percent()
    RAM = int(psutil.virtual_memory().total/(1027*1024))
    RAM_percent = psutil.virtual_memory().percent
    Swap = int(psutil.swap_memory().total/(1027*1024))
    Swap_percent = psutil.swap_memory().percent
    Net_sent = psutil.net_io_counters().bytes_sent
    Net_recv = psutil.net_io_counters().bytes_recv
    Net_spkg = psutil.net_io_counters().packets_sent
    Net_rpkg = psutil.net_io_counters().packets_recv
    if __name__ == "__main__":
        BFH = r'%'
        print " \033[1;32m开机时间:%s\033[1;m"  % Boot_Start
        print " \033[1;32m当前CPU使用率:%s%s\033[1;m" % (Cpu_usage,BFH)
        print " \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (RAM,RAM_percent,BFH)
        print "\033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (Swap,Swap_percent,BFH)
        print " \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (Net_sent,Net_spkg)
        print " \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (Net_recv,Net_rpkg)

        for i in psutil.disk_partitions():
            print " \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0],i[1],psutil.disk_usage(i[1])[3],BFH)
    else:
        File = open("sysinfo.log","ab+")
        File.write("CPU:%s   \tRAM:%s\tNet_recv:%d\tNet_sent:%d\r\n" % (Cpu_usage,RAM_percent,Net_recv,Net_sent))
        File.flush()
        File.close()
if __name__ == "__main__":
    Sysinfo()

主程序就不写了,大家自己看情况用就好了,好久没写过python了写的不好大家见谅


都是一个功能一个文件,直接运行也可以组织起来调用

标签: swap

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Android实现广播监听HOME键操作

下一篇: [iOS]图片压缩&保存View为内容Img