Python implementation DB system alert Contact API

Source: Internet
Author: User
Tags datetime mysql connect readline


When we maintain the system, we need to send the alarm information of the system to the corresponding students, if the contact method is written directly into the script, the future maintenance changes will bury the curse, especially hundreds of systems. To do this, you write an API for getting contact information.

Database Configuration Center table:

CREATE TABLE ' Db_alertcontact ' (
' ID ' INT (one) null DEFAULT null,
' Levelid ' INT (one) null DEFAULT null COMMENT ' contact level ',
' Contact ' VARCHAR null DEFAULT null COMMENT ' email or phone information ',
' type ' VARCHAR null DEFAULT null COMMENT ' Phone/email ',
' username ' VARCHAR null DEFAULT null,
' group ' VARCHAR null DEFAULT null COMMENT ' Contact Group '
)
Collate= ' Utf8_general_ci '
Engine=innodb;
CREATE TABLE ' Db_alertlevel ' (
' ID ' INT (one) null DEFAULT null,
' LevelName ' VARCHAR null DEFAULT null COMMENT ' Info/warn/err '
)
Collate= ' Utf8_general_ci '
Engine=innodb;
Usage Help:

[root@skatedb55 pytest]# python contactlist.py--help
Usage:contanct API v0.1, (C) Copyright Skate 2014 [-h]--group group--type
TYPE--level Level
[--interval interval]
[--load Load]
Optional arguments:
-H,--help show this Help and exit
--group Group = the Contact group
--type type = the mode of contact
--level level = Alarm Level,info/warn/err
--interval interval = Database query interval (s)
--load Load = The Configure Center Database,eg:
Load=user/pass@ip:port:dbname
[Root@skatedb55 pytest]#
Example:

INSERT into ' db_alertcontact ' (' IDs ', ' levelid ', ' contact ', ' type ', ' username ', ' group ') VALUES
  (1, 1, ' skate1 @163.com ', ' email ', ' skate1 ', ' P1 '),
  (2, 2, ' skate2@163.com ', ' email ', ' skate2 ', ' P2 '),
  (3, 1, ' 130000 0000 ', ' phone ', ' skate3 ', ' P2 '),
  (4, 1, ' 1311111111 ', ' phone ', ' skate4 ', ' P2 '),
  (5, 1, ' 1322222222 ', ' Phone ', ' skate5 ', ' P2 '),
  (6, 2, ' skate6@163.com ', ' email ', ' skate6 ', ' P2 ');
INSERT into ' db_alertlevel ' (' id ', ' levelname ') VALUES
  (1, ' info '),
  (2, ' warn '),
  (3, ' Error ');
[root@skatedb55 pytest]# python contactlist.py--group=p2--type=phone--level=info Root@10.20.0.55:3306:test6
1300000000,1311111111,www.111cn.net,
[root@skatedb55 pytest]#
[ root@skatedb55 pytest]# python contactlist.py--group=p2--type=email--level=warn--interval=10--load=root/ Root@10.20.0.55:3306:test6
skate2@163.com,skate6@163.com,
[root@skatedb55 pytest]#


Advantages:

1. Do not need to modify the code to change the contact or contact method

2. The relevant information of the contact is stored in the Configuration center database, in order to reduce the query to the database, the default to check the database every day (you can specify), put the contact information locally, both increase speed and reduce the dependency on the configuration center

3. If you want to change the contact information in a timely manner, simply delete the local temporary file "/tmp/contact_dbinfo" can be

#-*-Coding:utf-8-*-
#!/usr/bin/python
#
# author:skate
# TIME:2014/12/10
# function:contact API
Import Mysqldb,sys
Import Argparse
Import OS
Import datetime
Class Database:
def __int__ (self,host,user,passwd,port,dbname):
Self.conn = None
Pass
Def Conn (self,host,user,passwd,port,dbname):
Self.host=host
Self.user=user
self.passwd=passwd
Self.port=port
Self.dbname=dbname
Try
Self.conn = MySQLdb.connect (Host=self.host, User=self.user, PASSWD=SELF.PASSWD, Db=self.dbname,port=self.port)
Except Mysqldb.error, E:
Print "MySQL Connect Error:%s"% (E.args[1])
Return Self.conn
def closeconn (self):
Self.conn.close ()
def execute (self,sql,param):
If Self.conn==none or Self.conn.open==false:
Return-1
Sys.exit
cur = self.conn.cursor ()
Cur.execute (Sql,param)
Self.closeconn ()
Return cur
def contactlist (group,type,level,host,user,passwd,port,dbname,interval=86400):
Tfile= '/tmp/contact_dbinfo '
List= '
If Os.path.isfile (tfile):
A1=datetime.datetime.fromtimestamp (Os.path.getctime (tfile))
A2=datetime.datetime.now ()
Diffsec = (a2-a1). seconds
If diffsec > Interval:
Os.remove (Tfile)
F=open (Tfile, ' a ')
Db=database ()
Db.conn (Host,user,passwd,port,dbname)
Sql= "select T.contact,t.username,t.group,t. ' Type ', l.levelname from Db_alertcontact T, Db_alertlevel l where t.levelid= L.id and l.levelname=%s and t.group=%s and T. ' Type ' =%s '
Param= (Level,group,type)
Cur=db.execute (Sql,param)
Results=cur.fetchall ()
For row in results:
If row[3] = = ' phone ':
#for R in row:
List = list + row[0] + ', '
Elif row[3] = = ' Email ':
#for R in row:
List = list + row[0] + ', '
if type = = ' phone ':
F.write (' phonelist= ' + group + ': ' + list + ' \ n ')
F.close ()
elif type = = ' Email ':
F.write (' emaillist= ' + group + ': ' +list + ' \ n ')
F.close ()
Else
Strsearch = type + ' list= ' + group
Istype = Os.popen (' cat ' + tfile + ' | grep ' + strsearch + ' | wc-l '). ReadLine (). Strip ()
if int (Istype) > 0:
line = Os.popen (' cat ' + tfile + ' | grep ' + strsearch). ReadLine (). Strip ()
B=line.split (' = ')
A=b[1].split (":")
If b[0]== ' phonelist ':
LIST=A[1]
Elif b[0]== ' emaillist ':
LIST=A[1]
elif Int (Istype) < 1:
F=open (Tfile, ' a ')
Db=database ()
Db.conn (Host,user,passwd,port,dbname)
Sql= "select T.contact,t.username,t.group,t. ' Type ', l.levelname from Db_alertcontact T, Db_alertlevel l where t.levelid= L.id and l.levelname=%s and t.group=%s and T. ' Type ' =%s '
Param= (Level,group,type)
Cur=db.execute (Sql,param)
Results=cur.fetchall ()
#list = '
For row in results:
If row[3] = = ' phone ':
List = list + row[0] + ', '
Elif row[3] = = ' Email ':
List = list + row[0] + ', '
if type = = ' phone ':
F.write (' phonelist= ' + group + ': ' + list + ' \ n ')
F.close ()
elif type = = ' Email ':
F.write (' emaillist= ' + group + ': ' + list + ' \ n ')
F.close ()
Else
F=open (Tfile, ' a ')
Db=database ()
Db.conn (Host,user,passwd,port,dbname)
Sql= "select T.contact,t.username,t.group,t. ' Type ', l.levelname from Db_alertcontact T, Db_alertlevel l where t.levelid= L.id and l.levelname=%s and t.group=%s and T. ' Type ' =%s '
Param= (Level,group,type)
Cur=db.execute (Sql,param)
Results=cur.fetchall ()
For row in results:
If row[3] = = ' phone ':
#for R in row:
List = list + row[0] + ', '
Elif row[3] = = ' Email ':
#for R in row:
List = list + row[0] + ', '
if type = = ' phone ':
F.write (' phonelist= ' + group + ': ' + list + ' \ n ')
F.close ()
elif type = = ' Email ':
F.write (' emaillist= ' + group + ': ' + list + ' \ n ')
F.close ()
Return list
if __name__ = = "__main__":
Parser = Argparse. Argumentparser ("Contanct API v0.1, (C) Copyright Skate 2014")
Parser.add_argument ('--group ', action= ' store ', dest= ' group ', Required=true,
help= "= the Contact Group")
Parser.add_argument ('--type ', action= ' store ', dest= ' type ', Required=true,
help= "= the mode of contact")
Parser.add_argument ('--level ', action= ' store ', dest= ' level ', required=true,
help= "= Alarm Level,info/warn/err")
Parser.add_argument ('--interval ', action= ' store ', dest= ' interval ', type=int,default=86400,
help= "= Database query Interval")
Parser.add_argument ('--load ', action= ' store ', dest= ' load ', default= ',
help= "= The Configure center Database,eg: \ n load=user/pass@ip:port:dbname")
Results = Parser.parse_args ()
Load = Results.load
Group = Results.group
Type = Results.type
Level = Results.level
Interval = Results.interval
if (Load!= '):
User_info,url = Load.split ("@")
Host,port,db = Url.split (":")
Port=int (Port)
USER,PASSWD = User_info.split ("/", 1)
str = contactlist (group,type,level,host,user,passwd,port,db,interval)
Print str

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.