mysql巡检脚本(必看篇)
如下所示:
#!/usr/bin/envpython3.5 importpsutil importmysql.connector importargparse importjson importdatetime defget_cpu_info(verbose): cpu_info={} ifverbose>0: print("[cpu]startcollectcpuinfo...") 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() ifverbose>0: print("{0}".format(json.dumps(cpu_info,ensure_ascii=False,indent=4))) print("[cpu]collectioncompeleted...") returncpu_info defget_mem_info(verbose): mem_info={} ifverbose>0: print("[mem]startcollectmeminfo...") data=psutil.virtual_memory() mem_info['total']=data[0]/1024/1024/1024 mem_info['avariable']=data[1]/1024/1024/1024 ifverbose>0: print("{0}".format(json.dumps(mem_info,ensure_ascii=False,indent=4))) print("[mem]collectioncompeletd...") returnmem_info defget_disk_info(verbose): disk_info={} ifverbose>0: print("[disk]startcollectdiskinfo...") partitions=psutil.disk_partitions() partitions=[(partition[1],partition[2])forpartitioninpartitionsifpartition[2]!='iso9660'] disk_info={} forpartitioninpartitions: disk_info[partition[0]]={} disk_info[partition[0]]['fstype']=partition[1] formount_pointindisk_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] ifverbose>0: print("{0}".format(json.dumps(disk_info,ensure_ascii=False,indent=4))) print("[disk]collectioncompeleted....") returndisk_info defget_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) forindexinrange(len(status_list)): status_list[index].get_status(cursor) status=status_list[index] mysql_info[status.name]=status.value mysql_info['port']=config['port'] exceptmysql.connector.Erroraserr: print(err) finally: ifcursor!=None: cursor.close() ifcnx!=None: cnx.close() returnmysql_info classStatus(object): def__init__(self,name): self.name=name self._value=None defget_status(self,cursor): stmt="showglobalstatuslike'{0}';".format(self.name) cursor.execute(stmt) value=cursor.fetchone()[1].decode('utf8') self._value=int(value) @property defvalue(self): ifself._value==None: raiseException("cantgetvaluebeforexecutetheget_statusfunction") else: returnself._value IntStatus=Status classdiskResource(object): def__init__(self,mount_point,status): self.mount_point=mount_point self.status=status def__str__(self): result='''{0}