MYSQL教程mysql巡检脚本(必看篇)

MYSQL教程mysql巡检脚本(必看篇),第1张

概述介绍《MYSQL教程mysql巡检脚本(必看篇)》开发教程,希望对您有用。

《MysqL教程MysqL巡检脚本(必看篇)》要点:
本文介绍了MysqL教程MysqL巡检脚本(必看篇),希望对您有用。如果有疑问,可以联系我们。

MysqL学习如下所示:

MysqL学习#!/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,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,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='''        <div >          <div ><span>{0}</span></div>          <div >            <p >              <span >区分格式</span>              <span >{1}</span>            </p>            <p >              <span >总空间大小</span>              <span >{2:8.2f}G</span>            </p>            <p >              <span >空闲空间(%)</span>              <span >{3:8.2f}</span>            </p>            <p >                          </p>          </div>        </div>\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='''    <div >      <div >        <span>磁盘</span>      </div>      <div >\n'''    for index in range(len(self.disks)):      result=result+self.disks[index].__str__()    result=result+'''      </div>    </div>\n'''    return resultclass cpuResources(object):  def __init__(self,status):    self.status=status  def __str__(self):    result='''    <div >      <div >        <span>cpu</span>      </div>      <div >        <div >          <div ><span>global</span></div>          <div >            <p >              <span >用户空间使用(%)</span>              <span >{0}</span>            </p>            <p >              <span >内核空间使用(%)</span>              <span >{1}</span>            </p>            <p >              <span >空闲(%)</span>              <span >{2}</span>            </p>            <p >              <span >硬中断(%)</span>              <span >{3}</span>            </p>            <p >              <span >软中断(%)</span>              <span >{4}</span>            </p>            <p >              <span >io等待(%)</span>              <span >{5}</span>            </p>            <p >            </p>          </div>        </div>      </div>    </div>\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='''    <div >      <div >        <span>MEM</span>      </div>      <div >        <div >          <div ><span>global</span></div>          <div >            <p >              <span >总大小</span>              <span >{0:8.2f}G</span>            </p>            <p >              <span >空闲大小</span>              <span >{1:8.2f}G</span>            </p>                        <p >                          </p>          </div>        </div>      </div>    </div>'''.format(self.status['total'],self.status['avariable'])    return resultclass MysqLResources(object):  def __init__(self,status):    self.status=status  def __str__(self):    result='''    <div >      <div >        <span>MysqL</span>      </div>      <div >        <div >          <div ><span>{0}</span></div>          <div >            <p >              <span >innodb_log_wait</span>              <span >{1}</span>            </p>            <p >              <span >binlog_cache_use</span>              <span >{2}</span>            </p>            <p >              <span >create_temp_disk_table</span>              <span >{3}</span>            </p>                        <p >                            <span >Slow_querys</span>                            <span >{4}</span>                        </p>            <p >                          </p>          </div>        </div>      </div>    </div>'''.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='''<!DOCTYPE HTML><HTML lang="en"><head>  <Meta charset="UTF-8">  <Title>巡检报告</Title><style>*{  margin: 0;  padding: 0;}  .content{    wIDth:1000px;    height: auto;    margin: 30px auto;    border-bottom:1px solID #b2b2b2;  }  .List-item{    border:1px solID #b2b2b2;    border-bottom: none;    Transition: all .35s;    overflow: hIDden;    display: flex;  }  .List-item:empty{    display: none;  }  .top-Title{    line-height: 32px;    Font-size: 16px;    color: #333;    text-indent: 10px;    Font-weight: 600;  }  .category{    wIDth:97px;    height: auto;    border-right: 1px solID #b2b2b2;    float: left;    text-align: center;    position: relative;  }  .stage-Title>span,.category>span{    display: block;    height: 20px;    wIDth:100%;    text-align: center;    line-height: 20px;    position: absolute;    top: 50%;    margin-top: -10px;left: 0;  }  .second-stage{    wIDth:900px;    float: left;  }  .stage-List{    border-bottom: 1px solID #b2b2b2;    display: flex;  }  .stage-List:last-child{    border-bottom: 0;  }  .stage-Title{    wIDth:99px;    border-right: 1px solID #b2b2b2;    position: relative;  }  .detail{    flex: 1;  }  .detail-List{    border-bottom: 1px solID #b2b2b2;    height: 40px;    display: flex;    Transition: all .35s;  }  .detail-Title{    padding: 10px;    height: 20px;    line-height: 20px;    border-right: 1px solID #b2b2b2;    wIDth:200px;  }  .detail-describe{    flex: 1;    padding: 10px;line-height: 20px;  }  .detail-List:last-child{    border-bottom: 0;  }  .List-item:hover{    background-color: #eee;  }  .detail-List:hover{    background-color: #d1d1d1;  }</style></head><body>  <div >        <div >            <p >report_Title</p>        </div>\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+'''  </div></body></HTML>'''    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,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,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))

MysqL学习以上这篇MysqL巡检脚本(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持内存溢出PHP.

总结

以上是内存溢出为你收集整理的MYSQL教程mysql巡检脚本(必看篇)全部内容,希望文章能够帮你解决MYSQL教程mysql巡检脚本(必看篇)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/1161449.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存