MYSQL 数据库状态检查脚本(Python版)_MySQL
python
bitsCN.com #原shell版

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/imghw/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/imghw/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/imghw/default1.png" data-src="http://img.bitscn.com/upimg/allimg/c140719/1405L933135940-593L.jpg" class="lazy" alt=""></p> bitsCN.com

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Go 언어는 효율적이고 간결하며 배우기 쉬운 프로그래밍 언어입니다. 동시 프로그래밍과 네트워크 프로그래밍의 장점 때문에 개발자들이 선호합니다. 실제 개발에서 데이터베이스 작업은 필수적인 부분입니다. 이 기사에서는 Go 언어를 사용하여 데이터베이스 추가, 삭제, 수정 및 쿼리 작업을 구현하는 방법을 소개합니다. Go 언어에서는 일반적으로 사용되는 SQL 패키지, Gorm 등과 같은 타사 라이브러리를 사용하여 데이터베이스를 운영합니다. 여기서는 sql 패키지를 예로 들어 데이터베이스의 추가, 삭제, 수정 및 쿼리 작업을 구현하는 방법을 소개합니다. MySQL 데이터베이스를 사용하고 있다고 가정합니다.

Apple의 최신 iOS18, iPadOS18 및 macOS Sequoia 시스템 릴리스에는 사진 애플리케이션에 중요한 기능이 추가되었습니다. 이 기능은 사용자가 다양한 이유로 손실되거나 손상된 사진과 비디오를 쉽게 복구할 수 있도록 설계되었습니다. 새로운 기능에는 사진 앱의 도구 섹션에 '복구됨'이라는 앨범이 도입되었습니다. 이 앨범은 사용자가 기기에 사진 라이브러리에 포함되지 않은 사진이나 비디오를 가지고 있을 때 자동으로 나타납니다. "복구된" 앨범의 출현은 데이터베이스 손상으로 인해 손실된 사진과 비디오, 사진 라이브러리에 올바르게 저장되지 않은 카메라 응용 프로그램 또는 사진 라이브러리를 관리하는 타사 응용 프로그램에 대한 솔루션을 제공합니다. 사용자는 몇 가지 간단한 단계만 거치면 됩니다.

Hibernate 다형성 매핑은 상속된 클래스를 데이터베이스에 매핑할 수 있으며 다음 매핑 유형을 제공합니다. Join-subclass: 상위 클래스의 모든 열을 포함하여 하위 클래스에 대한 별도의 테이블을 생성합니다. 클래스별 테이블: 하위 클래스별 열만 포함하는 하위 클래스에 대한 별도의 테이블을 만듭니다. Union-subclass: Joined-subclass와 유사하지만 상위 클래스 테이블이 모든 하위 클래스 열을 통합합니다.

HTML은 데이터베이스를 직접 읽을 수 없지만 JavaScript 및 AJAX를 통해 읽을 수 있습니다. 단계에는 데이터베이스 연결 설정, 쿼리 보내기, 응답 처리 및 페이지 업데이트가 포함됩니다. 이 기사에서는 JavaScript, AJAX 및 PHP를 사용하여 MySQL 데이터베이스에서 데이터를 읽는 실제 예제를 제공하고 쿼리 결과를 HTML 페이지에 동적으로 표시하는 방법을 보여줍니다. 이 예제에서는 XMLHttpRequest를 사용하여 데이터베이스 연결을 설정하고 쿼리를 보내고 응답을 처리함으로써 페이지 요소에 데이터를 채우고 데이터베이스를 읽는 HTML 기능을 실현합니다.

MySQLi를 사용하여 PHP에서 데이터베이스 연결을 설정하는 방법: MySQLi 확장 포함(require_once) 연결 함수 생성(functionconnect_to_db) 연결 함수 호출($conn=connect_to_db()) 쿼리 실행($result=$conn->query()) 닫기 연결( $conn->close())

PHP에서 데이터베이스 연결 오류를 처리하려면 다음 단계를 사용할 수 있습니다. mysqli_connect_errno()를 사용하여 오류 코드를 얻습니다. 오류 메시지를 얻으려면 mysqli_connect_error()를 사용하십시오. 이러한 오류 메시지를 캡처하고 기록하면 데이터베이스 연결 문제를 쉽게 식별하고 해결할 수 있어 애플리케이션이 원활하게 실행될 수 있습니다.

PHP는 웹사이트 개발에 널리 사용되는 백엔드 프로그래밍 언어로, 강력한 데이터베이스 운영 기능을 갖추고 있으며 MySQL과 같은 데이터베이스와 상호 작용하는 데 자주 사용됩니다. 그러나 한자 인코딩의 복잡성으로 인해 데이터베이스에서 잘못된 한자를 처리할 때 문제가 자주 발생합니다. 이 기사에서는 잘못된 문자의 일반적인 원인, 솔루션 및 특정 코드 예제를 포함하여 데이터베이스에서 중국어 잘못된 문자를 처리하기 위한 PHP의 기술과 사례를 소개합니다. 문자가 왜곡되는 일반적인 이유는 잘못된 데이터베이스 문자 집합 설정 때문입니다. 데이터베이스를 생성할 때 utf8 또는 u와 같은 올바른 문자 집합을 선택해야 합니다.

Go 표준 라이브러리 데이터베이스/sql 패키지를 통해 MySQL, PostgreSQL 또는 SQLite와 같은 원격 데이터베이스에 연결할 수 있습니다. 데이터베이스 연결 정보가 포함된 연결 문자열을 생성합니다. sql.Open() 함수를 사용하여 데이터베이스 연결을 엽니다. SQL 쿼리 및 삽입 작업과 같은 데이터베이스 작업을 수행합니다. 리소스를 해제하기 위해 defer를 사용하여 데이터베이스 연결을 닫습니다.
