Skip to content

Commit 7e911f7

Browse files
committed
2.19.08.01 增加一次性杀死所有客气端连接的功能
1 parent 376dfa3 commit 7e911f7

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

bin/mtls-kill-all-conections

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/env python3
2+
3+
import os
4+
import sys
5+
import logging
6+
import argparse
7+
import mysql.connector
8+
9+
"""
10+
kill 所有数据库上的连接
11+
"""
12+
13+
name = os.path.basename(__file__)
14+
logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s",level=logging.INFO)
15+
16+
def parser_cmd_args() -> argparse.ArgumentParser:
17+
"""
18+
处理命令行参数
19+
"""
20+
parser = argparse.ArgumentParser(name)
21+
parser.add_argument('--host',type=str,default='127.0.0.1',help='mysql host')
22+
parser.add_argument('--port',type=int,default=3306,help="mysql port")
23+
parser.add_argument('--user',type=str,default="opsuser",help="mysql user")
24+
parser.add_argument('--password',type=str,default="mtls0352",help="mysql user's password")
25+
args = parser.parse_args()
26+
return args
27+
28+
29+
def kill_all_connections(args):
30+
cnx = None
31+
try:
32+
cnx = mysql.connector.connect(host=args.host,port=args.port,user=args.user,password=args.password)
33+
cnx.autocommit=True
34+
cursor = cnx.cursor()
35+
# 查询出本身的连接 id
36+
cursor.execute("select connection_id();")
37+
self_connection_id,*_ = cursor.fetchone()
38+
#logging.info(f"self connection equal {self_connection_id}")
39+
40+
# 查询出当前主机上的所有连接
41+
processlist_ids = []
42+
cursor.execute("select id from information_schema.processlist where command not in ('Daemon','Binlog Dump') ;")
43+
44+
# 提取出 processlist id
45+
for ip,*_ in cursor.fetchall():
46+
if ip != self_connection_id:
47+
processlist_ids.append(ip)
48+
49+
# kill 掉每一个 processlist id
50+
for processlist in processlist_ids:
51+
try:
52+
# 不管 kill 是否正常返回,都认为是正常的
53+
cursor.execute(f"kill {processlist};")
54+
logging.info(f"kill {processlist};")
55+
except mysql.connector.Error as err:
56+
logging.error(f"kill {processlist} failed '{str(err)}' ")
57+
58+
except mysql.connector.Error as err:
59+
logging.error(str(err))
60+
finally:
61+
if cnx != None and hasattr(cnx,'close'):
62+
cnx.close()
63+
64+
65+
if __name__ == "__main__":
66+
args = parser_cmd_args()
67+
kill_all_connections(args)
39 Bytes
Binary file not shown.
27.1 KB
Binary file not shown.

0 commit comments

Comments
 (0)