import tkinter as tk
import pymysql
import paramiko
import datetime
from tkinter import ttk
def execute_ssh_upload(jar_name, ssh_ip):
# 连接数据库
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='rootroot',
database='db_leadsend',
charset='utf8mb4'
)
# 创建一个游标对象 cursor
cursor = conn.cursor()
sql = "SELECT file_adress,ssh_ip, username, password FROM calo_ssh_table WHERE jar_name = '{}' AND ssh_ip = '{}'".format(jar_name, ssh_ip)
cursor.execute(sql)
# 获取单个查询结果
result = cursor.fetchone()
if result:
fileAdress = result[0]
sshIp = result[1]
userName = result[2]
passWord = result[3]
print(f"fileAdress: {fileAdress},sshIp: {sshIp}, userName: {userName}, passWord: {passWord}")
# SSH连接到服务器
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(sshIp.split(':')[0], port=int(sshIp.split(':')[1]), username=userName, password=passWord)
# 上传文件到服务器
local_file_path = fr"D:\calo-ssh\{jar_name}"
remote_dir_path = fileAdress # 远程目录路径,根据实际情况修改
sftp = ssh.open_sftp()
current_date = datetime.datetime.now().strftime("%Y%m%d")
remote_file_path = f"{remote_dir_path}/{jar_name}"
new_remote_file_path = f"{remote_dir_path}/{jar_name}.{current_date}"
new_fileName = f"{jar_name}.{current_date}"
# 获取远程目录的文件列表
file_list = sftp.listdir(remote_dir_path)
# 检查文件是否存在
if new_fileName in file_list:
print("备份文件已存在,跳过备份步骤")
else:
# 执行备份操作
sftp.rename(remote_file_path, new_remote_file_path)
print("文件已备份")
print("文件上传中")
sftp.put(local_file_path, remote_file_path)
print("文件已上传")
sftp.close()
ssh_shell = ssh.invoke_shell()
ssh_shell.send(f"cd {remote_dir_path}\n")
#ssh_shell.send(f"nohup java --add-opens java.base/java.io=ALL-UNNAMED -jar {jar_name} > log-file.log 2>&1 &\n")
# 执行启动命令
ssh_shell.send(f"systemctl restart {jar_name}.service\n")
print("部署成功")
output = ""
count = 0
while True:
output += ssh_shell.recv(1024).decode('utf-8')
if output.endswith("$ "): # 根据实际的命令行提示符进行调整
break
elif output.endswith("Connection closed by foreign host"): # 处理异常情况
break
else:
count += 1
if count > 4: # 如果连续未获取到结尾标记的次数超过 4 次,则退出循环
break
# 关闭 SSH 连接
ssh_shell.close()
ssh.close()
else:
print("没有找到匹配的结果")
# 关闭连接
cursor.close()
conn.close()
#版本回退
def execute_roll_back(jar_name, ssh_ip):
# 连接数据库
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='rootroot',
database='db_leadsend',
charset='utf8mb4'
)
jar_rollName = jar_name.rsplit(".", 1)[0]
# 创建一个游标对象 cursor
cursor = conn.cursor()
sql = "SELECT file_adress,ssh_ip, username, password FROM calo_ssh_table WHERE jar_name = '{}' AND ssh_ip = '{}'".format(
jar_rollName, ssh_ip)
cursor.execute(sql)
# 获取单个查询结果
result = cursor.fetchone()
if result:
fileAdress = result[0]
sshIp = result[1]
userName = result[2]
passWord = result[3]
print(f"fileAdress: {fileAdress},sshIp: {sshIp}, userName: {userName}, passWord: {passWord}")
# SSH连接到服务器
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(sshIp.split(':')[0], port=int(sshIp.split(':')[1]), username=userName, password=passWord)
remote_dir_path = fileAdress # 远程目录路径,根据实际情况修改
sftp = ssh.open_sftp()
remote_file_path = f"{remote_dir_path}/{jar_name}"
new_remote_file_path = f"{remote_dir_path}/{jar_rollName}"
print("remote_file_path"+remote_file_path)
print("new_remote_file_path"+new_remote_file_path)
# 判断远程文件是否存在
try:
file_stat = sftp.stat(remote_file_path)
if file_stat:
print("文件已存在")
# 删除同名文件
sftp.remove(new_remote_file_path)
# 执行重命名操作
sftp.rename(remote_file_path, new_remote_file_path)
except FileNotFoundError:
print("文件不存在")
sftp.close()
ssh_shell = ssh.invoke_shell()
ssh_shell.send(f"cd {remote_dir_path}\n")
#ssh_shell.send(f"nohup java --add-opens java.base/java.io=ALL-UNNAMED -jar {jar_rollName} > log-file.log 2>&1 &\n")
# 执行启动命令
ssh_shell.send(f"systemctl restart {jar_name}.service\n")
print("回退成功")
output = ""
count = 0
while True:
output += ssh_shell.recv(1024).decode('utf-8')
if output.endswith("$ "): # 根据实际的命令行提示符进行调整
break
elif output.endswith("Connection closed by foreign host"): # 处理异常情况
break
else:
count += 1
if count > 4: # 如果连续未获取到结尾标记的次数超过 4 次,则退出循环
break
# 关闭 SSH 连接
ssh_shell.close()
ssh.close()
else:
print("没有找到匹配的结果")
# 关闭连接
cursor.close()
conn.close()
def on_button_click():
jar_name = jar_name_entry.get()
ssh_ip_key = ssh_ip_combobox.get() # 获取选中的键
ssh_ip = options[ssh_ip_key] # 获取对应的值
execute_ssh_upload(jar_name, ssh_ip)
def on_roll_back():#版本回退
jar_name = jar_name_entry.get()
ssh_ip_key = ssh_ip_combobox.get() # 获取选中的键
ssh_ip = options[ssh_ip_key] # 获取对应的值
execute_roll_back(jar_name, ssh_ip)
window = tk.Tk()
window.geometry("400x200") # 设置窗口大小为宽400像素,高200像素
options = {
'服务器1': '127.0.0.1',
'服务器2': '127.0.0.1',
'服务器3': '127.0.0.1',
}
jar_name_label = tk.Label(window, text="Jar包名称:")
jar_name_label.pack()
jar_name_entry = tk.Entry(window)
jar_name_entry.pack()
ssh_ip_label = tk.Label(window, text="服务器IP:")
ssh_ip_label.pack()
# 创建一个Combobox,并设置显示值为选项的key,实际值为选项的value
ssh_ip_combobox = ttk.Combobox(window, values=list(options.keys()))
ssh_ip_combobox.pack()
button = tk.Button(window, text="自动部署", command=on_button_click)
button.pack(side=tk.LEFT)
# 添加空格
space = tk.Label(window, text="")
space.pack(side=tk.LEFT)
button2 = tk.Button(window, text="版本回退", command=on_roll_back)
button2.pack(side=tk.RIGHT)
window.mainloop()
window.destroy() # 关闭窗口
python写一个自动化部署脚本,包括文件备份,文件上传,启动
最新推荐文章于 2024-05-25 13:40:06 发布