search
HomeDatabaseMysql TutorialMYSQL 数据库状态检查脚本(Python版)_MySQL

python

bitsCN.com #原shell版View Code
  1 #!/bin/bash   2   3 # Script Name: mysql_status_check.sh   4 # Description: check mysql servers status   5 # Author: Xinggang Wang - OpsEye.com   6 # Create Date: 2012/3/30   7   8 #获取MySQL所在服务器IP/端口/用户名/密码   9 read -p "Host=" HOST  10 read -p "Port=" PORT  11 read -p "User=" USER  12 read -sp "Password=" PASSWORD  13 echo  14  15 #默认为127.0.0.1/3306/root  16 if [ "${HOST}" = "" ]  17 then  18 HOST='127.0.0.1'  19 fi  20  21 if [ "${PORT}" = "" ]  22 then  23 PORT='3306'  24 fi  25  26 if [ "${USER}" = "" ]  27 then  28 USER='root'  29 fi  30  31 #注意密码为空的时候的格式  32 mysql_list="  33 $HOST:$PORT:$USER:$PASSWORD  34 "  35 #计算函数,提高脚本效率  36 compute(){  37 formula="$1"  38 awk 'BEGIN{printf("%.2f",'$formula')}' 2>/dev/null &&  39 echo $value || echo NULL  40 }  41  42 for mysql in $mysql_list  43 {  44 host=${mysql%%:*}  45 port=$(echo $mysql|awk -F: '{print $2}')  46 user=$(echo $mysql|awk -F: '{print $3}')  47 passwd=${mysql##*:}  48  49 [ -z "$passwd" ] && mysql="mysql -h$host -P$port -u$user" ||  50 mysql="mysql -h$host -P$port -u$user -p$passwd"  51  52 unset Uptime  53 # 把show global status的值赋给相应的参数名称(这里相当于大量的变量赋值操作)  54 eval $( $mysql -e "show global status" | awk '{print $1"=/x27"$2"/047"}')  55 [ X = X"$Uptime" ] && continue  56  57 # Mysql VER  58 VER=`$mysql -e"status;"|grep 'Server version'|awk '{print $3}'`  59  60 # Uptime  61 UPTIME=`compute "$Uptime/3600/24"`  62  63 # Threads_connected  64 threads_connected=`compute "$Threads_connected"`  65  66 # QPS Questions/Uptime  67 qps=`compute "$Questions/$Uptime"`  68  69 # TPS (Com_commit + Com_rollback)/Uptime  70 tps=`compute "($Com_commit+$Com_rollback)/$Uptime"`  71  72 # Reads Com_select + Qcache_hits  73 reads=`compute "$Com_select+$Qcache_hits"`  74  75 # Writes Com_insert + Com_update + Com_delete + Com_replace  76 writes=`compute "$Com_insert+$Com_update+$Com_delete+$Com_replace"`  77  78 # Read/Writes Ratio reads/writes*100%  79 rwratio=`compute "$reads/$writes*100"`%  80  81 # MyISAM Key_buffer_read_hits (1 - Key_reads/Key_read_requests) * 100  82 key_buffer_read_hits=`compute "(1-$Key_reads/$Key_read_requests)*100"`%  83  84 # MyISAM Key_buffer_write_hits (1 - Key_writes/Key_write_requests) * 100  85 key_buffer_write_hits=`compute "(1-$Key_writes/$Key_write_requests)*100"`%  86  87 # Query_cache_hits (Qcache_hits / (Qcache_hits + Qcache_inserts)) * 100%  88 query_cache_hits=`compute "$Qcache_hits/($Qcache_hits+$Qcache_inserts)*100"`%  89  90 # Innodb_buffer_read_hits (1 - Innodb_buffer_pool_reads/Innodb_buffer_pool_read_requests) * 100  91 innodb_buffer_read_hits=`compute "(1-$Innodb_buffer_pool_reads/$Innodb_buffer_pool_read_requests)*100"`%  92  93 # Thread_cache_hits (1 - Threads_created / Connections) * 100%  94 thread_cache_hits=`compute "(1-$Threads_created/$Connections)*100"`%  95  96 # Slow_queries_per_second Slow_queries / Uptime * 60  97 slow_queries_per_second=`compute "$Slow_queries/$Uptime"`  98  99 # Select_full_join_per_second Select_full_join / Uptime * 60 100 select_full_join_per_second=`compute "$Select_full_join/$Uptime*60"` 101 102 # select_full_join_in_all_select (Select_full_join / Com_select) * 100 103 select_full_join_in_all_select=`compute "($Select_full_join/$Com_select)*100"`% 104 105 # MyISAM Lock Contention (Table_locks_waited / Table_locks_immediate) * 100 106 myisam_lock_contention=`compute "($Table_locks_waited/$Table_locks_immediate)*100"`% 107 108 # Temp_tables_to_disk (Created_tmp_disk_tables / Created_tmp_tables) * 100 109 temp_tables_to_disk_ratio=`compute "($Created_tmp_disk_tables/$Created_tmp_tables)*100"`% 110 111 # print formated MySQL status report 112 title="******************** MySQL--${HOST}--${PORT} ***********************" 113 width=$((`echo "$title"|wc -c`-1)) 114 115 echo "$title" 116 117 export IFS=':' 118 while read name value ;do 119 printf "%36s :/t%10s/n" $name $value 120 done 99%):$key_buffer_read_hits 130 MyISAM Key buffer write hits:$key_buffer_write_hits 131 Query cache hits:$query_cache_hits 132 InnoDB buffer read hits(>95%):$innodb_buffer_read_hits 133 Thread cache hits(>90%):$thread_cache_hits 134 Slow queries per second:$slow_queries_per_second 135 Select full join per second:$select_full_join_per_second 136 Select full join in all select:$select_full_join_in_all_select 137 MyiSAM lock contention(
#Python版<img class="code_img_closed lazy" src="/static/imghwm/default1.png" data-src="http://img.bitscn.com/upimg/allimg/c140719/1405L9330U940-33564.jpg" id="code_img_closed_547cb232-79f2-4f40-9763-d38b744e9424" alt=""><img class="code_img_opened lazy" src="/static/imghwm/default1.png" data-src="http://img.bitscn.com/upimg/allimg/c140719/1405L9331093P-423U.jpg" onclick="cnblogs_code_hide('547cb232-79f2-4f40-9763-d38b744e9424',event)" id="code_img_opened_547cb232-79f2-4f40-9763-d38b744e9424"   style="max-width:90%" alt="">View Code
<pre class="brush:php;toolbar:false">  1 #!/usr/bin/env python  2   3 #-*- coding: utf-8 -*-  4   5 # Script Name: mysql_status_check.py  6   7 # Description: check mysql servers status  8   9 # Author: Bruce.Zuo  10  11 # Create Date: 2012/06/05 12  13 import os,sys 14  15 import MySQLdb 16  17 import getpass 18  19  20  21 host=raw_input("host:") 22  23 user=raw_input("user:") 24  25 password=getpass.getpass() 26  27  28  29 try: 30  31    conn = MySQLdb.connect(host = host, user=user ,passwd = password, db = 'test') 32  33 except MySQLdb.ERROR,e: 34  35    print "Error %d:%s"%(e.args[0],e.args[1]) 36  37    exit(1) 38  39 cursor=conn.cursor() 40  41  42  43 cursor.execute('show global status;') 44  45 result_set=cursor.fetchall() 46  47 cursor.close() 48  49 conn.close() 50  51  52  53 def get_value(key_name): 54  55         for rows in result_set: 56  57                 if rows[0]==key_name: 58  59                         return float(rows[1]) 60  61  62  63 print ('MySQL-'+host+'-3306').center(60,'*') 64  65 print 'Uptime:'.rjust(40),get_value('Uptime') 66  67 print 'Threads_connected:'.rjust(40),get_value('Threads_connected') 68  69 print 'QPS:'.rjust(40),round(get_value('Questions') / get_value('Uptime'),2) 70  71 print 'TPS:'.rjust(40),round(get_value('Com_commit')+get_value('Com_rollback') / get_value('Uptime'),2) 72  73 reads=get_value('Com_select')+ get_value('Qcache_hits') 74  75 writes=get_value('Com_insert')+get_value('Com_update')+get_value('Com_delete')+get_value('Com_replace') 76  77 print 'Reads:'.rjust(40),get_value('Com_select')+ get_value('Qcache_hits') 78  79 print 'Writes:'.rjust(40),get_value('Com_insert')+get_value('Com_update')+get_value('Com_delete')+get_value('Com_replace') 80  81 print 'Read/Writes Ratio:'.rjust(40),round(reads / writes,2),'%' 82  83 print 'MyISAM Key buffer read hits(>99%):'.rjust(40),round(1-get_value('Key_reads') / (get_value('Key_read_requests')*100),2),'%' 84  85 print 'MyISAM Key buffer write hits:'.rjust(40),round(1-get_value('Key_writes') / (get_value('Key_write_requests')*100),2),'%' 86  87 print 'Query cache hits:'.rjust(40),round(get_value('Qcache_hits') / (get_value('Qcache_hits')+get_value('Qcache_inserts'))*100,2),'%' 88  89 print 'InnoDB buffer read hits(>95%):'.rjust(40),round(1-get_value('Innodb_buffer_pool_reads') / (get_value('Innodb_buffer_pool_read_requests')*100),2),'%' 90  91 print 'Thread cache hits(>90%):'.rjust(40),round(1-get_value('Threads_created') / (get_value('Connections')*100),2),'%' 92  93 print 'Slow queries per second:'.rjust(40),round(get_value('Slow_queries') / get_value('Uptime'),2) 94  95 print 'Select full join per second:'.rjust(40),round(get_value('Select_full_join') / get_value('Uptime'),2) 96  97 print 'Select full join in all select:'.rjust(40),round(get_value('Select_full_join') / (get_value('Com_select')*100),2),'%' 98  99 print 'MyiSAM lock contention(
<p>#根据这个方法,可以添加更多的状态项。</p>
<p>#效果图</p>
<p><img src="/static/imghwm/default1.png" data-src="http://img.bitscn.com/upimg/allimg/c140719/1405L933135940-593L.jpg" class="lazy" alt=""></p>
bitsCN.com
    
Statement
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
MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 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.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool