Python as a monitoring

Source: Internet
Author: User


A. Python log module

Two. Python database connection

Three. Time Processing module

Four. Python passes parameters to the shell

Five. Send mail (py2.7)

Six. Python Scheduled Tasks

Seven. Supervisor

/etc/supervisor.conf[program:check]command = Python/data/remote_back/checkbackup.pydirectory =/data/remote_ Backuser = root[email protected]_tmn_data:[/data/remote_back]supervisorctl check RUNNING pid 5771, uptime 19:1 5:25

Eight. General examples

#coding:utf-8import threadingimport mysqldbfrom datetime import datetimeimport  time,osimport smtplibfrom email.mime.text import mimetext#from log import  Loggerimport loggingdef get_log ():     logging.basicconfig (level=logging. debug,    format= '% (asctime) s % (filename) s[line:% (Lineno) d] % (levelname) s  % (message) s ',     datefmt= '%a, %d %b %y %h:%m:%s ',     filename= ' Myapp.log ',     filemode= ' W ')     logger =  Logging.getlogger (' root ')     return loggerdef get_con ():     host =  "120.138.75.88"     port = 5849    logsdb  =  "ServerList"     user =  "xxxx"     password  =  "xxxxx"   &nbsP; con = mysqldb.connect (host=host, user=user, passwd=password, db=logsdb,  port=port, charset= "UTF8")     return condef calculate_time ():     now = time.mktime (DateTime.Now (). Timetuple ()) -60*2    result =  time.strftime ('%y-%m-%d %h:%m:%s ',  time.localtime (now))     return  Resultdef backup_time ():     now = time.mktime (DateTime.Now (). Timetuple ())- 60*2    result = time.strftime ('%y%m%d ',  time.localtime (now))      BACKUPRESULT = STR (Result)     return backupresultdef get_ Data (agent):     select_time = calculate_time ()     get_log (). Info ("Select time:" +select_time)     sql =  ' Select count (distinct  Gamedatadbname)   From gameserverinfo where agent= "%s"  and isdelete!=1  ORDER BY  Zone '  % (agent)     conn = get_con ()     cursor =  conn.cursor ()     cursor.execute (SQL)     results =  Cursor.fetchall ()     num1 = results[0]    num =  Num1[0]    cursor.close ()     conn.close ()      Return numdef get_backupdata (Agent): #    backupnum = os.popen (' ls  * ' date +%y%m%d04 ' * |wc -l '). Read (). strip (' \ n ')     shijian =   ' * '  + backup_time ()  +  '  + ' * '     guize =  '%s '  % (agent)  + shijian    os.environ[' guize '] = str (guize)      backupnum = os. Popen (' ls  $guize  |wc -l '). Read (). strip (' \ n ')     return backupnum     def check ():     numdata = int (Get_data (' ynvng '))     backupnum = int (Get_backupdata (' ynvng '))     if  numdata == backupnum:        result =  "Backup succeeded"      else:        result =  "Backup Failed"      return resultdef send_email (content):     sender =  "[ Email protected] "    receiver = [" [email protected] "," [email  Protected] "]    host =  ' smtp.163.com '     port =  465    msg = mimetext (content)     msg[' from '] =  ' [ Email protected] " &Nbsp;  msg[' to '] =  "[email protected]"     msg[' Subject '] =   "Vng backup check"      try:         smtp = smtplib. Smtp_ssl (Host, port)         smtp.login (sender,  ' xxxx ')          smtp.sendmail (Sender, receiver, msg.as_string ())          get_log (). info ("send email success")      except exception, e:        get_log (). Error (E) #print  edef task (): #    get_data = get_data () #    get_ Backupdata= get_backupdata ()     while true:    data =  get_data (' ynvng ')     backupdata= get_backupdata (' ynvng ') shijian =  Backup_time ()         get_log (). info ("monitor running")          results = check () Print resultsget_log (). info (Results)         if results ==  "Backup succeeded":             content =  "Vietnam Backup Success"          else:            content =   "Vietnam Backup Failed" Print content,data,backupdata        send_email ( content +  "  Backup time:"  + shijian +  "   :  should be backed up"  +  STR (data)  +      number of backups:  +  str (backupdata))          time.sleep (720*60) def run_monitor ():     monitor =  threading. Thread (Target=task)     monitor.start ()   if __name__ ==  "__main__":     run_monitor ()

Nine. Operation effect

650) this.width=650; "title=" program runs "alt=" program Run "src=" http://192.168.1.222/wiki/hdwiki/uploads/201501/ 1422435177aeumjzyr_s.png "/> program run



This article is from the "Automation Rolin" blog, so be sure to keep this source http://luoguoling.blog.51cto.com/1568501/1616617

Python as a 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.