Python writes a Process Monitoring script

Source: Internet
Author: User

Python writes a Process Monitoring script

If you don't talk much about it, You can paste code directly. I don't like xml in your configuration files. The following is a custom configuration file:

Class_config.py #! /Usr/bin/env python # coding: UTF-8 ''' the parameter '''class Mail_conf () of the email is defined here (): sender = 'fyxichen @ 126.com 'guest ER = 'fyxichen @ 126.com' host = 'smtp .126.com 'port = '25' user = 'fyxichen @ 126.com' passwd = '100' log_dir =' sendmail _ err_log ''' defines the monitoring program and startup path, the startup path cannot contain Chinese ''' # usage {program name: Startup Password} # configure the restart log name, which cannot be blank. Class ProgramPath (): Path = require '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: The utf-8import string, timeimport smtplibfrom email. mime. text import MIMETextfrom email. header import Headerfrom class_config import Mail_conf ''' send mail class ''' def send_mail (Title, context): msg = MIMEText (context, 'plain ', 'utf-8 ') msg ['subobject'] = 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 () failed t 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 email, change the mailbox configuration in class_config.py to configure ")

 

 

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 = "this parameter allows you to view the bandwidth occupied by the current download.-t indicates the test time ", 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; average speed of 32 m % 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; 32 m boot time: % s \ 033 [1; m "% Boot_Start print" \ 033 [1; 32 m current CPU usage: % s \ 033 [1; m "% (Cpu_usage, BFH) print "\ 033 [1; 32 m physical memory: % dM \ t usage: % s \ 033 [1; m" % (RAM, RAM_percent, BFH) print "\ 033 [1; 32mSwap memory: % dM \ t usage: % s \ 033 [1; m" % (Swap, Swap_percent, BFH) print "\ 033 [1; 32 m send: % d Byte \ t Number of sent packets: % d \ 033 [1; m" % (Net_sent, Net_spkg) print "\ 033 [1; 32 m Received: % d Byte \ t received packets: % d \ 033 [1; m" % (Net_recv, Net_rpkg) for I in psutil. disk_partitions (): print "\ 033 [1; 32 m drive letter: % s mount point: % s usage: % 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 ()

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.