Python writes a script for process monitoring

Source: Internet
Author: User

Nonsense not much to say, directly paste code, everyone profiles are like to use XML I do not like, the following is the custom configuration file:

Class_config.py#!/usr/bin/env Python#coding:utf-8 "" here defines the relevant parameters of the message ' Class mail_conf ():    sender = ' [email protected ] '    receiver = ' [email protected] '    host = ' smtp.126.com '    port = '    user = ' [email protected] '    passwd = ' 123456 '    log_dir = ' Sendmail_err_log ' here defines the monitor and boot path, the boot path cannot contain Chinese ' #用法 {program name: Startup Password} #配置重启日志名称, cannot be empty. 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 ',}    

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 ' Send Message class ' 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", " This is a test message, change the mailbox configuration in class_config.py Configuration ")

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:PROCESSN                 ame = 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.st                 Rftime ('%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 + > 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= "This parameter can see the bandwidth of the current download,-t is the test duration", 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 in%s seconds Average speed:%.2f kb/s \033[1;m"  % (x,res ult/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.strftim E ("%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.swa P_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 = P Sutil.net_io_counters (). packets_recv if __name__ = = "__main__": BFH = R '% ' print ' \033[1;32m boot time:%s\033[ 1;m "% boot_start print" \033[1;32m current CPU usage:%s%s\033[1;m "% (CPU_USAGE,BFH) print" \033[1;32m physical memory:%dm\t use        Rate:%s%s\033[1;m "% (RAM,RAM_PERCENT,BFH) print" \033[1;32mswap Memory:%dm\t usage:%s%s\033[1;m "% (SWAP,SWAP_PERCENT,BFH) Print "\033[1;32m send:%d byte\t send packets:%d \033[1;m "% (net_sent,net_spkg) print" \033[1;32m Received:%d Byte\t received packets:%d \033[1;m "% (net_recv,net_r PKG) for I in Psutil.disk_partitions (): print "\033[1;32m drive letter:%s mount point:%s usage:%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\tne t_recv:%d\tnet_sent:%d\r\n "% (cpu_usage,ram_percent,net_recv,net_sent)) File.flush () File.close () if __name_ _ = = "__main__": Sysinfo ()

The main program will not write, we look at the situation with a good, long time no write Python write bad everyone forgive

is a feature of a file that runs directly or can be organized to call

Python writes a script for process monitoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.