博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mysql巡检脚本
阅读量:6788 次
发布时间:2019-06-26

本文共 10543 字,大约阅读时间需要 35 分钟。

#!/usr/bin/env python3.5import psutilimport mysql.connectorimport argparseimport jsonimport datetimedef get_cpu_info(verbose):    cpu_info={}    if verbose >0:        print("[cpu]    start collect cpu info ...")    data=psutil.cpu_times_percent(3)    cpu_info['user']=data[0]    cpu_info['system']=data[2]    cpu_info['idle']=data[3]    cpu_info['iowait']=data[4]    cpu_info['hardirq']=data[5]    cpu_info['softirq']=data[6]    cpu_info['cpu_cores']=psutil.cpu_count()    if verbose >0:        print("{0}".format(json.dumps(cpu_info,ensure_ascii=False,indent=4)))        print("[cpu]    collection compeleted ...")    return cpu_infodef get_mem_info(verbose):    mem_info={}    if verbose >0:        print("[mem]    start collect mem info ...")    data=psutil.virtual_memory()    mem_info['total']=data[0]/1024/1024/1024    mem_info['avariable']=data[1]/1024/1024/1024    if verbose>0:        print("{0}".format(json.dumps(mem_info,ensure_ascii=False,indent=4)))        print("[mem]    collection compeletd ...")    return mem_infodef get_disk_info(verbose):    disk_info={}    if verbose >0:        print("[disk]    start collect disk info ...")    partitions=psutil.disk_partitions()    partitions=[(partition[1],partition[2])for partition in partitions if partition[2]!='iso9660']    disk_info={}    for partition in partitions:        disk_info[partition[0]]={}        disk_info[partition[0]]['fstype']=partition[1]    for mount_point in disk_info.keys():        data=psutil.disk_usage(mount_point)        disk_info[mount_point]['total']=data[0]/1024/1024/1024        disk_info[mount_point]['used_percent']=data[3]    if verbose >0:        print("{0}".format(json.dumps(disk_info,ensure_ascii=False,indent=4)))        print("[disk]    collection compeleted ....")    return disk_infodef get_mysql_info(cnx_args,status_list):    config={        'user':cnx_args.user,        'password':cnx_args.password,        'host':cnx_args.host,        'port':cnx_args.port}    cnx=None    cursor=None    mysql_info={}    try:        cnx=mysql.connector.connect(**config)        cursor=cnx.cursor(prepared=True)        for index in range(len(status_list)):            status_list[index].get_status(cursor)            status=status_list[index]            mysql_info[status.name]=status.value        mysql_info['port']=config['port']    except mysql.connector.Error as err:        print(err)    finally:        if cursor != None:            cursor.close()        if cnx != None:            cnx.close()    return mysql_infoclass Status(object):    def __init__(self,name):        self.name=name        self._value=None    def get_status(self,cursor):        stmt="show global status like '{0}';".format(self.name)        cursor.execute(stmt)        value=cursor.fetchone()[1].decode('utf8')        self._value=int(value)    @property    def value(self):        if self._value==None:            raise Exception("cant get value befor execute the get_status function")        else:            return self._valueIntStatus=Statusclass diskResource(object):    def __init__(self,mount_point,status):        self.mount_point=mount_point        self.status=status    def __str__(self):        result='''                
{0}

区分格式 {1}

总空间大小 {2:8.2f}G

空闲空间(%) {3:8.2f}

\n'''.format(self.mount_point,self.status['fstype'],self.status['total'],self.status['used_percent']) return resultclass diskResources(object): def __init__(self,status): self.disks=[] for mount_point in status.keys(): self.disks.append(diskResource(mount_point,status[mount_point])) def __str__(self): result='''
磁盘
\n''' for index in range(len(self.disks)): result=result+self.disks[index].__str__() result=result+'''
\n''' return resultclass cpuResources(object): def __init__(self,status): self.status=status def __str__(self): result='''
CPU
global

用户空间使用(%) {0}

内核空间使用(%) {1}

空闲(%) {2}

硬中断(%) {3}

软中断(%) {4}

io等待(%) {5}

\n'''.format(self.status['user'],self.status['system'],self.status['idle'],self.status['hardirq'],self.status['softirq'],self.status['iowait']) return resultclass memResources(object): def __init__(self,status): self.status=status def __str__(self): result='''
MEM
global

总大小 {0:8.2f}G

空闲大小 {1:8.2f}G

'''.format(self.status['total'],self.status['avariable']) return resultclass mysqlResources(object): def __init__(self,status): self.status=status def __str__(self): result='''
MYSQL
{0}

innodb_log_wait {1}

binlog_cache_use {2}

create_temp_disk_table {3}

Slow_querys {4}

'''.format(self.status['port'],self.status['Innodb_log_waits'],self.status['Binlog_cache_use'], self.status['Created_tmp_disk_tables'],self.status['Slow_queries']) return resultclass hostResources(object): def __init__(self,cpu_info,mem_info,disk_info,mysql_info,report_title='MySQL巡检报告'): self.cpu=cpuResources(cpu_info) self.mem=memResources(mem_info) self.disk=diskResources(disk_info) self.mysql=mysqlResources(mysql_info) self.report_title=report_title def __str__(self): result='''
巡检报告

report_title

\n''' result=result.replace('report_title',self.report_title) result=result+self.cpu.__str__() result=result+self.mem.__str__() result=result+self.disk.__str__() result=result+self.mysql.__str__() result=result+'''
''' return resultif __name__=="__main__": parser=argparse.ArgumentParser() parser.add_argument('--verbose',type=int,default=1,help='verbose for output') parser.add_argument('--user',default='chkuser',help='user name for connect to mysql') parser.add_argument('--password',default='123456',help='user password for connect to mysql') parser.add_argument('--host',default='127.0.0.1',help='mysql host ip') parser.add_argument('--port',default=3306,type=int,help='mysql port') parser.add_argument('--int-status',default=('Com_select,Com_insert,Com_update,Com_delete,Innodb_log_waits,' 'Binlog_cache_disk_use,Binlog_cache_use,Created_tmp_disk_tables,' 'Slow_queries') ,help='mysql status its value like int') parser.add_argument('--report-title',default='MySQL巡检报告',help='report title') parser.add_argument('--output-dir',default='/tmp/',help='default report file output path') args=parser.parse_args() cpu_info=get_cpu_info(args.verbose) mem_info=get_mem_info(args.verbose) disk_info=get_disk_info(args.verbose) status_list=[ IntStatus(name=item) for item in args.int_status.split(',')] mysql_info=get_mysql_info(args,status_list) #dr=diskResources(disk_info) #cr=cpuResources(cpu_info) #mr=memResources(mem_info) #msr=mysqlResources(mysql_info) hr=hostResources(cpu_info,mem_info,disk_info,mysql_info,args.report_title) now=str(datetime.datetime.now()).replace(' ','^') if args.output_dir.endswith('/') != True: args.output_dir=args.output_dir+'/' filename=args.output_dir+'mysql_inspection_{0}.html'.format(now) with open(filename,'w') as output: output.write(hr.__str__()) print('[report] the report been saved to {0} ok.... ....'.format(filename))

 

转载地址:http://mnbgo.baihongyu.com/

你可能感兴趣的文章
机器指令处理的数据所在位置
查看>>
第三次作业
查看>>
北大acm1004
查看>>
Difference Search Path
查看>>
webpack再看一遍
查看>>
利用d3.js对大数据资料进行可视化分析
查看>>
用vue实现博客列表的级联效果
查看>>
Java并发编程序列之线程状态
查看>>
数据结构与算法-链表(上)
查看>>
JavaSE基础:"头疼"的正则表达式
查看>>
Web开发者成长路线总结
查看>>
iOS开发 AutoreleasePool是什么时候销毁的?
查看>>
RxSwift 之 Subject
查看>>
直播项目---弹幕问题
查看>>
课程 4: 使用 CursorLoader 加载数据
查看>>
IDEA 插件开发入门教程
查看>>
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。...
查看>>
痛入爽出 HTTP/2:入门简述
查看>>
Flux模式简析
查看>>
超级小白系列之一坨x的原始数据类型转换
查看>>