Home Database Mysql Tutorial Detailed introduction to the case code of mysql inspection script

Detailed introduction to the case code of mysql inspection script

Mar 20, 2017 pm 01:49 PM

The editor below will bring you a mysql inspection script (a must-read). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

is as follows:

#!/usr/bin/env python3.5

import psutil
import mysql.connector
import argparse
import json
import datetime

def 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_info

def 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_info

def 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_info

def 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_info

class 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._value

IntStatus=Status


class diskResource(object):
  def init(self,mount_point,status):
    self.mount_point=mount_point
    self.status=status

  def str(self):
    result=&#39;&#39;&#39;        <p class="stage-list">
          <p class="stage-title"><span>{0}</span></p>
          <p class="detail">
            <p class="detail-list">
              <span class="detail-title">区分格式</span>
              <span class="detail-describe">{1}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">总空间大小</span>
              <span class="detail-describe">{2:8.2f}G</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">空闲空间(%)</span>
              <span class="detail-describe">{3:8.2f}</span>
            </p>
            <p class="detail-list">
              
            </p>
          </p>
        </p>\n&#39;&#39;&#39;.format(self.mount_point,self.status[&#39;fstype&#39;],self.status[&#39;total&#39;],self.status[&#39;used_percent&#39;])
    return result

class 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=&#39;&#39;&#39;    <p class="list-item">
      <p class="category">
        <span>磁盘</span>
      </p>
      <p class="second-stage">\n&#39;&#39;&#39;
    for index in range(len(self.disks)):
      result=result+self.disks[index].str()
    result=result+&#39;&#39;&#39;      </p>
    </p>\n&#39;&#39;&#39;
    return result

class cpuResources(object):
  def init(self,status):
    self.status=status
  def str(self):
    result=&#39;&#39;&#39;    <p class="list-item">
      <p class="category">
        <span>CPU</span>
      </p>
      <p class="second-stage">
        <p class="stage-list">
          <p class="stage-title"><span>global</span></p>
          <p class="detail">
            <p class="detail-list">
              <span class="detail-title">用户空间使用(%)</span>
              <span class="detail-describe">{0}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">内核空间使用(%)</span>
              <span class="detail-describe">{1}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">空闲(%)</span>
              <span class="detail-describe">{2}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">硬中断(%)</span>
              <span class="detail-describe">{3}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">软中断(%)</span>
              <span class="detail-describe">{4}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">io等待(%)</span>
              <span class="detail-describe">{5}</span>
            </p>
            <p class="detail-list">

            </p>
          </p>
        </p>
      </p>
    </p>\n&#39;&#39;&#39;.format(self.status[&#39;user&#39;],self.status[&#39;system&#39;],self.status[&#39;idle&#39;],self.status[&#39;hardirq&#39;],self.status[&#39;softirq&#39;],self.status[&#39;iowait&#39;])
    return result

class memResources(object):
  def init(self,status):
    self.status=status

  def str(self):
    result=&#39;&#39;&#39;    <p class="list-item">
      <p class="category">
        <span>MEM</span>
      </p>
      <p class="second-stage">
        <p class="stage-list">
          <p class="stage-title"><span>global</span></p>
          <p class="detail">
            <p class="detail-list">
              <span class="detail-title">总大小</span>
              <span class="detail-describe">{0:8.2f}G</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">空闲大小</span>
              <span class="detail-describe">{1:8.2f}G</span>
            </p>
            
            <p class="detail-list">
              
            </p>
          </p>
        </p>
      </p>
    </p>&#39;&#39;&#39;.format(self.status[&#39;total&#39;],self.status[&#39;avariable&#39;])
    return result


class mysqlResources(object):
  def init(self,status):
    self.status=status
  def str(self):
    result=&#39;&#39;&#39;    <p class="list-item">
      <p class="category">
        <span>MYSQL</span>
      </p>
      <p class="second-stage">
        <p class="stage-list">
          <p class="stage-title"><span>{0}</span></p>
          <p class="detail">
            <p class="detail-list">
              <span class="detail-title">innodb_log_wait</span>
              <span class="detail-describe">{1}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">binlog_cache_use</span>
              <span class="detail-describe">{2}</span>
            </p>
            <p class="detail-list">
              <span class="detail-title">create_temp_disk_table</span>
              <span class="detail-describe">{3}</span>
            </p>
                        <p class="detail-list">
                            <span class="detail-title">Slow_querys</span>
                            <span class="detail-describe">{4}</span>
                        </p>

            <p class="detail-list">
              
            </p>
          </p>
        </p>
      </p>
    </p>&#39;&#39;&#39;.format(self.status[&#39;port&#39;],self.status[&#39;Innodb_log_waits&#39;],self.status[&#39;Binlog_cache_use&#39;],
             self.status[&#39;Created_tmp_disk_tables&#39;],self.status[&#39;Slow_queries&#39;])

    return result

class hostResources(object):
  def init(self,cpu_info,mem_info,disk_info,mysql_info,report_title=&#39;MySQL巡检报告&#39;):
    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=&#39;&#39;&#39;<!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>
  <p class="content">
        <p class="list-item">
            <p class="top-title">report_title</p>
        </p>\n&#39;&#39;&#39;

    result=result.replace(&#39;report_title&#39;,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+&#39;&#39;&#39;  </p>
</body>
</html>&#39;&#39;&#39;
    return result


if name=="main":
  parser=argparse.ArgumentParser()
  parser.add_argument(&#39;--verbose&#39;,type=int,default=1,help=&#39;verbose for output&#39;)
  parser.add_argument(&#39;--user&#39;,default=&#39;chkuser&#39;,help=&#39;user name for connect to mysql&#39;)
  parser.add_argument(&#39;--password&#39;,default=&#39;123456&#39;,help=&#39;user password for connect to mysql&#39;)
  parser.add_argument(&#39;--host&#39;,default=&#39;127.0.0.1&#39;,help=&#39;mysql host ip&#39;)
  parser.add_argument(&#39;--port&#39;,default=3306,type=int,help=&#39;mysql port&#39;)
  parser.add_argument(&#39;--int-status&#39;,default=(&#39;Com_select,Com_insert,Com_update,Com_delete,Innodb_log_waits,&#39;
                        &#39;Binlog_cache_disk_use,Binlog_cache_use,Created_tmp_disk_tables,&#39;
                        &#39;Slow_queries&#39;)
            ,help=&#39;mysql status its value like int&#39;)
  parser.add_argument(&#39;--report-title&#39;,default=&#39;MySQL巡检报告&#39;,help=&#39;report title&#39;)
  parser.add_argument(&#39;--output-dir&#39;,default=&#39;/tmp/&#39;,help=&#39;default report file output path&#39;)
  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(&#39;,&#39;)]
  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(&#39; &#39;,&#39;^&#39;)
  if args.output_dir.endswith(&#39;/&#39;) != True:
    args.output_dir=args.output_dir+&#39;/&#39;
  filename=args.output_dir+&#39;mysql_inspection_{0}.html&#39;.format(now)
  with open(filename,&#39;w&#39;) as output:
    output.write(hr.str())
  print(&#39;[report]  the report been saved to {0}  ok.... ....&#39;.format(filename))
Copy after login

The above is the detailed content of Detailed introduction to the case code of mysql inspection script. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles