前文说如何对比文件中的差异并举例几个方法,读者朋友也留言提出其他的解决方法比如 :ide,beyond compare 。本文继续说另外一个需求多个配置文件如何对比。
有多个mysql实例,存在各个实例的my.cnf 和 数据库实时状态的 variables 值不一样的情况,所以需要对多个实例之间进行参数值的比较,一个个登陆到具体实例上查询又比较麻烦,直接无法通过文本对比。
1 编写配置文件记录多个db实例的连接信息
2 通过配置文件连接db 获取 show variables 命令,并存储多个结果集
3 将结果集 [{},{},{}] 转化为 dict[section]={k1:v1,k2:v2,k3:v3...kn:vn}
4 利用 pandas 的DataFrame.to_html 将处理过的集合输出为 html 文件
#!coding=utf-8
import pymysql
import configparser
import argparse
import pandas as pd
def get_conn(conf):
my_conf = {
"host": conf['host'],
"user": conf['user'],
"password": conf['pass'],
"port": int(conf['port'])
}
conn = pymysql.Connect(**my_conf)
return conn
def get_vars(db_conn):
var_dict = {}
sql = "show variables;"
with db_conn.cursor(cursor=pymysql.cursors.DictCursor) as cur:
cur.execute(sql)
var_list = cur.fetchall()
for item in var_list:
var_dict[item['Variable_name']] = item['Value']
return var_dict
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='comp_vars.py -f config_file ')
parser.add_argument('-f', dest='config_file', type=str, action='store', help='要对比的实例信息 ip port user pass')
args = parser.parse_args()
if not args.config_file:
parser.usage()
config_file = args.config_file
config = configparser.ConfigParser()
config.read(config_file)
sections = config.sections()
vars = {} ### 参数矩阵
for section in sections:
conn = get_conn(config[section])
vars[section] = get_vars(conn)
index = [key for key in vars[sections[0]]]
df = pd.DataFrame(index=index)
for section in sections:
df[section] = [value for value in vars[section].values()]
HEADER = '''
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<style type="text/css">
.table-style {
width: 100%;
table-layout:fixed;
}
.table-style tr td {
word-wrap:break-word;
white-space: normal;
padding:3px 5px;
width:30
}
</style>
'''
FOOTER = '''
</body>
</html>
'''
with open("/tmp/vars_comp.html", 'w') as f:
f.write(HEADER)
f.write(df.to_html(classes='table-style'))
f.write(FOOTER)
说明一下 css style 格式是为表格中的列能自动换行。
instances.cnf的内容如下,如果有多个实例 可以配置多个section [dbN]
[db1]
host = xxx
user = xx
pass = xxyz
port = 3306
[db2]
host = yyy
user = xy
pass = yyyz
port = 3306
生成html 文件在浏览器中打开。
python3 vars_comp.py -f instances.cnf
大家有什么更好的方式 可以留言交流。