本文共 2665 字,大约阅读时间需要 8 分钟。
#!/usr/bin/python
import sys
import subprocessimport MySQLdbclass MySQL(object):
def init(self):passdef sql_init(self): conn = MySQLdb.connect("localhost", "root", "", "test", charset='utf8' ) cur = conn.cursor() return conn, cur@classmethoddef query_sql(cls, sql): res = cls().sql_init() conn = res[0] cur = res[1] try: cur.execute(sql) data = cur.fetchall() except Exception: data = None print 'SQL ERROR!!' conn.close() return data@classmethoddef insert_sql(cls, sql): res = cls().sql_init() conn = res[0] cur = res[1] try: cur.execute(sql) conn.commit() result = True except: conn.rollback() result = False conn.close() return result@classmethoddef delete_sql(cls, sql): res = cls().sql_init() conn = res[0] cur = res[1] try: cur.execute(sql) conn.commit() result = True except: conn.rollback() result = False conn.close() return result@classmethoddef update_sql(cls, sql): res = cls().sql_init() conn = res[0] cur = res[1] try: cur.execute(sql) conn.commit() result = True except: conn.rollback() result = False conn.close() return result@classmethoddef do_mysql(cls, sql): """ 其他任意的SQL语句,如创建表 """ res = cls().sql_init() conn = res[0] cur = res[1] try: cur.execute(sql) result = True except: result = False conn.close() return result
def getUnknownPods():
s=subprocess.Popen('kubectl get pods --all-namespaces|grep Unknown', shell=True, stdout=subprocess.PIPE)out = s.communicate()[0]if s != '': #print out result = out.split('\n') #print result lines = result[0:-1] print lines for line in lines: rows = line.split() #print rows sql = 'insert into alerts (type,name,number,error,time) values("pod","%s",1,"Unknown Pod",now()) '%(rows[1]) #print sql MySQL.insert_sql(sql)
def getRestartPods():
s=subprocess.Popen('kubectl get pods --all-namespaces', shell=True, stdout=subprocess.PIPE)out = s.communicate()[0]if s != '': #print out result = out.split('\n') #print result lines = result[1:-1] print lines for line in lines: rows = line.split() #print rows if rows[4] > 3: sql = 'insert into alerts (type,name,number,error,time) values("pod","%s",%s,"Unknown Pod",now()) '%(rows[1],rows[4]) #print sql MySQL.insert_sql(sql)
def main():
#getUnknownPods()getRestartPods()if name == 'main':
main()转载于:https://blog.51cto.com/11346335/2150146