要求
要求本地有py环境和全局环境变量
先测试直接执行binlog命令执行命令
Windows 本地直接执行命令
# E:\output>E:\phpstudy_pro\Extensions\MySQL5.7.26\bin\mysqlbinlog binglog文件地址
# --no-defaults 不限制编码
# -h mysql链接地址
# -u mysql 链接名称
# -p mysql 密码
# -P3306 mysql 端口
# --read-from-remote-server --raw mysqlbinlog 命令的一个选项,它指示 mysqlbinlog 从远程 MySQL 服务器读取二进制日志文件进行解析。
# binlog.000003 文件地址
#命令如下
E:\output>E:\phpstudy_pro\Extensions\MySQL5.7.26\bin\mysqlbinlog --no-defaults -h 127.0.0.1 -u root -p -P3306 --read-from-remote-server --raw binlog.000003
代码
import subprocess
def download_binlogs(host, user, password, port, start_binlog, end_binlog, output_path):
try:
for binlog_number in range(start_binlog, end_binlog + 1):
binlog_filename = f"binlog.{str(binlog_number).zfill(6)}"
output_filename = f"{output_path}/binlog_{binlog_number}.sql"
# 构建命令
command = [
'E:/phpstudy_pro/Extensions/MySQL5.7.26/bin/mysqlbinlog.exe',
'--no-defaults',
'-h', host,
'-u', user,
'-p' + password,
'-P' + str(port),
'--read-from-remote-server',
'--raw',
binlog_filename
]
# 运行命令并将输出重定向到文件
with open(output_filename, 'w') as output_file:
subprocess.run(command, stdout=output_file)
output_file.flush() # 刷新缓冲区
print(f"Binlog日志文件 '{binlog_filename}' 下载成功!保存为 '{output_filename}'")
except Exception as e:
print(f"下载失败:{e}")
if __name__ == "__main__":
# 替换以下信息为实际的Polardb连接信息和binlog文件范围
polardb_host = "127.0.0.1"
polardb_user = "root"
polardb_password = "root"
polardb_port = 3306
start_binlog_number = 1
end_binlog_number = 3
output_directory = "E:/output" # 替换为你想要保存文件的目录
download_binlogs(polardb_host, polardb_user, polardb_password, polardb_port, start_binlog_number, end_binlog_number, output_directory)
python执行
python .\binlog.py