程序员 Windows apache Python nginx HTML5 linux命令 linux shell wordpress centos java Firefox Android 开源 微软 google Ubuntu php mysql

Python MysqlDB 日常使用模板

这是一份添加zabbix自动发现的脚本:

#!/usr/bin/python 
#coding:utf-8 
 
import MySQLdb 
 class zabbix: 
    def __init__(self): 
        self.dbuser = 'root' 
        self.dbpass = 'wisp888' 
        self.dbport = 3306 
        self.dbhost = 'localhost' 
         
    def add(self, ip): 
        #连接数据库: 
        conn = MySQLdb.connect(user=self.dbuser, host=self.dbhost, passwd=self.dbpass, port=self.dbport, db='zabbix') 
        cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) 
         
        #判断drule表中是否已经存在此ip: 
        sql = '''''select * from drules where name = %s''' 
        ret = cursor.execute(sql,ip) 
        if ret: 
            print "%s is already exist!" % ip 
        else: 
            #获取drules表中最大的druleid,并+1,作为将要插入的记录的druleid 
            sql = '''''select max(druleid) as maxid from drules''' 
            ret = cursor.execute(sql) 
            druleid = cursor.fetchone()['maxid'] + 1 
            #print druleid 
             
            #插入drules: 
            sql = '''''insert into drules(druleid,name,iprange) value(%s,%s,%s) ''' 
            ret = cursor.execute(sql,(druleid,ip,ip)) 
            conn.commit() 

        
            #插入dchecks: 
            sql = '''''insert into dchecks(dcheckid,druleid,type,key_,ports) value(%s,%s,9,'system.uname',10050)''' 
            cursor.execute(sql,(druleid,druleid)) 
            conn.commit() 
            print "%s add to zabbix success!" % ip 
        conn.close() 
         
    def get_ip(self): 
        conn = MySQLdb.connect(host=self.dbhost, user=self.dbuser, passwd=self.dbpass, port=self.dbport, db='ips') 
        cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) 
        sql = '''''select ip from tb_system where id != -1 group by sys_name''' 
        sum = cursor.execute(sql) 
        list = cursor.fetchall() 
        return  list 
         
if __name__ == "__main__": 
    myzabbix = zabbix() 
    for i in myzabbix.get_ip(): 
        ip = i['ip'] 
        myzabbix.add(ip) 

延伸阅读

评论