python寫個進程監控的指令碼

來源:互聯網
上載者:User

標籤:psutil   python   郵件   指令碼   smtp   

廢話不多說了,直接貼代碼,大家設定檔都是喜歡用xml我不太喜歡,下面這個是自訂設定檔:

class_config.py#!/usr/bin/env python#coding:utf-8'''此處定義郵件的相關參數'''class Mail_conf():    sender = '[email protected]'    receiver = '[email protected]'    host = 'smtp.126.com'    port = '25'    user = '[email protected]'    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-8import string,timeimport smtplibfrom email.mime.text import MIMETextfrom email.header import Headerfrom 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-8import psutil,timeimport subprocessfrom 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-8import psutilimport timeimport sysfrom optparse import OptionParserparser = 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-8import psutilimport timeimport sysdef 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了寫的不好大家見諒

都是一個功能一個檔案,直接運行也可以組織起來調用

python寫個進程監控的指令碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.