自动化服务部署脚本02
脚本如下
import os
import sys
import threading
import subprocess
from datetime import datetime
# 远程服务器信息列表
servers = [
{"host": "103.152.133.13"},
{"host": "107.172.209.161"}, # 假设有多个服务器
]
# 要发布的程序目录路径
package_dir = "/root/deploy/package_dir/web/"
config_dir = "/root/deploy/config/"
supervisor_dir = os.path.join(package_dir, "supervisor")
# 远程服务器上的部署路径
deploy_path = "/opt/myapp"
supervisor_deploy_path = "/opt/"
# 备份目录路径
backup_base_dir = "/root/deploy/package_dir/back/"
def backup(server):
"""
备份远程服务器上的部署目录到本地
"""
now = datetime.now().strftime("%Y%m%d%H%M%S")
backup_dir = os.path.join(backup_base_dir, now)
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
print(f"开始备份{server['host']}:{deploy_path}到本地{backup_dir}")
try:
# 部署package_dir
if os.path.exists(package_dir):
rsync_cmd = f"rsync -e 'ssh -o StrictHostKeyChecking=no' -avz {package_dir}/ {server['host']}:{deploy_path}"
result = subprocess.run(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
print(f"Deploy package_dir Error: {result.stderr.decode()}")
else:
print(f"{server['host']}部署package_dir成功")
# 部署supervisor_dir
if os.path.exists(supervisor_dir):
rsync_cmd = f"rsync -e 'ssh -o StrictHostKeyChecking=no' -avz {supervisor_dir}/ {server['host']}:{supervisor_deploy_path}"
result = subprocess.run(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
print(f"Deploy supervisor_dir Error: {result.stderr.decode()}")
else:
print(f"{server['host']}部署supervisor_dir成功")
# 部署config_dir
if os.path.exists(config_dir):
rsync_cmd = f"rsync -e 'ssh -o StrictHostKeyChecking=no' -avz {config_dir}/ {server['host']}:{deploy_path}/config"
result = subprocess.run(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
print(f"Deploy config_dir Error: {result.stderr.decode()}")
else:
print(f"{server['host']}部署config_dir成功")
except Exception as e:
print(f"Backup Error: {e}")
def deploy(server, backup_first=False):
"""
发布程序目录到指定远程服务器
"""
if backup_first:
# 先备份
backup(server)
print(f"开始部署到{server['host']}")
try:
# rsync命令,使用ssh并跳过host key检查
rsync_cmd = f"rsync -e 'ssh -o StrictHostKeyChecking=no' -avz {package_dir}/ {server['host']}:{deploy_path}"
result = subprocess.run(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
print(f"Deploy Error: {result.stderr.decode()}")
else:
print(f"{server['host']}部署成功")
except Exception as e:
print(f"Deploy Error: {e}")
def deploy_all():
"""
并发部署到所有远程服务器
"""
threads = []
for index, server in enumerate(servers):
# 只有第一个服务器进行备份
backup_first = (index == 0)
t = threading.Thread(target=deploy, args=(server, backup_first))
threads.append(t)
t.start()
for t in threads:
t.join()
def restart_web_server(server, service_name):
"""
重启远程服务器上的指定web服务
"""
print(f"重启{server['host']}上的web服务: {service_name}")
try:
# 使用ssh远程执行重启命令
ssh_cmd = f"ssh -o StrictHostKeyChecking=no {server['host']} 'supervisorctl restart {service_name}'"
result = subprocess.run(ssh_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
print(f"Restart Error: {result.stderr.decode()}")
else:
print(f"{server['host']}上的web服务{service_name}重启成功")
except Exception as e:
print(f"Restart Error: {e}")
def deploy_menu():
"""
部署web服务菜单
"""
deploy_all()
while True:
print("请选择操作:")
print("a. 重启web1服务")
print("b. 重启web2服务")
print("c. 退出")
choice = input("输入选项字母: ")
if choice == "a":
for server in servers:
restart_web_server(server, "web1")
elif choice == "b":
for server in servers:
restart_web_server(server, "web2")
elif choice == "c":
break
else:
print("无效选项,请重试")
def restart_menu():
"""
重启服务菜单
"""
while True:
print("请选择操作:")
print("a. 重启web1服务")
print("b. 重启web2服务")
print("c. 退出")
choice = input("输入选项字母: ")
if choice == "a":
for server in servers:
restart_web_server(server, "web1")
elif choice == "b":
for server in servers:
restart_web_server(server, "web2")
elif choice == "c":
break
else:
print("无效选项,请重试")
if __name__ == "__main__":
while True:
print("请选择操作:")
print("1. 发布服务")
print("2. 重启服务")
print("3. 退出")
choice = input("输入选项数字: ")
if choice == "1":
print("1. 部署web服务")
deploy_menu()
elif choice == "2":
restart_menu()
elif choice == "3":
print("退出程序")
sys.exit(0)
else:
print("无效选项,请重试")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
上次更新: 2024/06/11, 23:05:26