DB系统预警联系人API

Author:Skate

Time:2014/12/16

DB系统预警联系人API

在我们维护系统时,需要把系统的报警信息即时传递给相应同学,如果把联系方式直接写到脚本里,对以后的维护变更将埋下祸根,尤其是成百上千的系统。

为此这里写了个获取联系人信息的API

数据库配置中心表:

CREATE TABLE `db_alertcontact` (

`id` INT(11) NULL DEFAULT NULL,

`levelid` INT(11) NULL DEFAULT NULL COMMENT ‘contact level‘,

`contact` VARCHAR(50) NULL DEFAULT NULL COMMENT ‘email or phone information‘,

`type` VARCHAR(50) NULL DEFAULT NULL COMMENT ‘phone/email‘,

`username` VARCHAR(100) NULL DEFAULT NULL,

`group` VARCHAR(80) NULL DEFAULT NULL COMMENT ‘contact group‘

)

COLLATE=‘utf8_general_ci‘

ENGINE=InnoDB;

CREATE TABLE `db_alertlevel` (

`id` INT(11) NULL DEFAULT NULL,

`levelname` VARCHAR(50) NULL DEFAULT NULL COMMENT ‘info/warn/err‘

)

COLLATE=‘utf8_general_ci‘

ENGINE=InnoDB;

用法帮助:

[[email protected] 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 message 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

--load LOAD          = The configure center database,eg:

load=user/[email protected]:port:dbname

[[email protected] pytest]#

例子:

INSERT INTO `db_alertcontact` (`id`, `levelid`, `contact`, `type`, `username`, `group`) VALUES

(1, 1, ‘[email protected]‘, ‘email‘, ‘skate1‘, ‘p1‘),

(2, 2, ‘[email protected]‘, ‘email‘, ‘skate2‘, ‘p2‘),

(3, 1, ‘1300000000‘, ‘phone‘, ‘skate3‘, ‘p2‘),

(4, 1, ‘1311111111‘, ‘phone‘, ‘skate4‘, ‘p2‘),

(5, 1, ‘1322222222‘, ‘phone‘, ‘skate5‘, ‘p2‘),

(6, 2, ‘[email protected]‘, ‘email‘, ‘skate6‘, ‘p2‘);

INSERT INTO `db_alertlevel` (`id`, `levelname`) VALUES

(1, ‘info‘),

(2, ‘warn‘),

(3, ‘error‘);

[[email protected] pytest]# python contactlist.py --group=p2 --type=phone --level=info --interval=10--load=root/[email protected]:3306:test6

1300000000,1311111111,1322222222,

[[email protected] pytest]#

[[email protected] pytest]# python contactlist.py --group=p2 --type=email --level=warn --interval=10--load=root/[email protected]:3306:test6

[email protected],[email protected],

[[email protected] pytest]#

优点:

1.在变更联系人或联系方式不需要修改代码

2.联系人的相关信息存储在配置中心数据库,为了减少对数据库的查询,每天查一次数据库,把联系信息放在本地,既提高了速度,也减少了对配置中心的依赖

3.如果想在变更联系信息及时生效,只需把本地的临时文件"/tmp/contact_dbinfo"删除即可

contactlist.py:

# -*- coding: utf-8 -*-
#!/usr/bin/python
# Author:Skate
# Time:2014/12/10
 
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/[email protected]: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

大家有好的意见,欢迎提出

------end-------

时间: 2024-08-05 23:18:21

DB系统预警联系人API的相关文章

Android 获取系统的联系人

本文主要介绍android中怎样获取系统的联系人数据 首先打开模拟器 点击联系人图标按钮 说明系统联系人数据库是空的,打开File explorer,找到data/data下面的文件夹: 将contacts2.db文件导出,添加到sqlite中的时候报错: 点击“ok”忽略之 表结构相当的复杂,首先搞清楚其中的三张表 * data表 保存联系人的数据 * raw_contacts表 保存联系人的id contact_id * mimetypes表 保存联系人数据的类型 接下来通过模拟器添加联系人

[转]Oracle DB 查看预警日志

"Database(数据库)"主页>"Related Links相关链接)"区域> "Alert Log Content (预警日志内容)" 查看预警日志 每个数据库都有一个alert_<sid >.log文件.此文件位于数据库所在的服务器中,如果设置了$ORACLE_BASE,则此文件默认存储在$ORACLE_BASE/diag/rdbms/<db_name>/<SID>/trace中. 数据库预

无废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4)

1.内容观察者ContentObserver 如果ContentProvider的访问者需要知道ContentProvider中的数据发生了变化,可以在ContentProvider 发生数据变化时调用getContentResolver().notifyChange(uri, null)来通知注册在此URI上的访问者,例子如下: private static final Uri URI = Uri.parse("content://person.db"); public class

用ContentProvider向系统增加联系人

发现对系统的联系人进行操作的api很乱,感觉逻辑有点不清楚...... 主要用到这4个类: android.provider.ContactsContract.CommonDataKinds.Email;android.provider.ContactsContract.CommonDataKinds.Phone;android.provider.ContactsContract.CommonDataKinds.StructuredName;android.provider.ContactsCo

Oracle DB 查看预警日志

"Database(数据库)"主页>"Related Links相关链接)"区域> "Alert Log Content (预警日志内容)" 查看预警日志每个数据库都有一个alert_<sid>.log文件.此文件位于数据库所在的服务器中,如果设置了$ORACLE_BASE,则此文件默认存储在$ORACLE_BASE/diag/rdbms/<db_name>/<SID>/trace中.数据库预警文件

如何调用系统隐藏的API,或者使用系统未开放的类

一.反射 可以通过反射来调用系统隐藏的API, 但对于已经被系统隐藏的类似乎不太行得通. 二.使用系统源码编译后的classes.jar 路径:out/target/common/obj/JAVA_LIBRARIES/framework_intermediates 将此jar包添加到项目中后,在使用系统相关类或者隐藏的API时,就不会出现错误标识的小红点提示. 需要注意的是: 1,在manifest中标识:android:sharedUserId="android.uid.system"

[android] 获取系统的联系人信息

内容提供是实质上是个接口,后门,他给别人提供数据,系统联系人是个比较复杂的内容通过者. 找到/data/data/com.android.providers.contacts/contacts2.db 这个目录下还有个文件contacts2.db.-journal,这个文件和数据库的事务相关 联系人应用数据库的主要结构 raw_contacts 联系人表 contact_id 联系人id data数据表  raw_contact_id联系人id,mimetype_id数据类id,data1数据

IOS获取系统通讯录联系人信息

先导入AddressBook.framework先 然后引用  #import <AddressBook/AddressBook.h> 一.权限注册 随着apple对用户隐私的越来越重视,IOS系统的权限设置也更加严格,在获取系统通讯录之前,我们必须获得用户的授权.权限申请代码示例如下: #pragma mark - 注册权限 - (void)contacts { //这个变量用于记录授权是否成功,即用户是否允许我们访问通讯录 int __block tip = 0; //声明一个通讯簿的引用

Unix/Linux系统时间函数API

首先说明关于几个时间的概念: 世界时:起初,国际上的标准时间是格林尼治标准时间,以太阳横穿本初子午线的时刻为标准时间正午12点.它根据天文环境来定义,就像古代人们根据日晷来计时一样,如下图: 原子时:地球一年中自转的速度并不是恒定的,它有时候转的快,有时候转的慢,地震可能使得地球自转加快,而发射卫星则使得自转减缓,但地球的总体自转趋势是越来越慢.如果按照地球自转一圈固定为24小时来定义时间长度,会导致一秒钟的长度不稳定,或长或短.为解决这个问题,科研人员发现某元素的原子运动频率很稳定,可以以该元