自动化服务部署脚本01
脚本如下
import paramiko
import os
# 设置要部署的服务名称
SERVICE_NAME = 'my-service'
# 设置要部署到的目标主机信息
HOSTS = [
{'hostname': '10.0.0.1', 'username': 'root', 'password': 'your_password'},
{'hostname': '10.0.0.2', 'username': 'root', 'key_file': '/path/to/your/key_file'},
# 添加更多主机
]
# 设置服务文件的本地路径
LOCAL_SERVICE_PATH = '/path/to/your/service/files'
# 设置远程服务文件的目标路径
REMOTE_SERVICE_PATH = '/opt/my-service'
def deploy_service(client):
"""在目标主机上部署服务"""
# 创建远程服务目录
stdin, stdout, stderr = client.exec_command(f'mkdir -p {REMOTE_SERVICE_PATH}')
# 使用SFTP上传服务文件
sftp = client.open_sftp()
for root, dirs, files in os.walk(LOCAL_SERVICE_PATH):
for file in files:
local_path = os.path.join(root, file)
remote_path = os.path.join(REMOTE_SERVICE_PATH, os.path.relpath(local_path, LOCAL_SERVICE_PATH))
sftp.put(local_path, remote_path)
sftp.close()
# 在远程主机上执行部署命令
deploy_command = f'cd {REMOTE_SERVICE_PATH} && ./deploy.sh'
stdin, stdout, stderr = client.exec_command(deploy_command)
stdout_output = stdout.read().decode()
stderr_output = stderr.read().decode()
print(f'主机 {client.get_transport().getpeername()[0]} 部署输出:')
print(stdout_output)
print(stderr_output)
def main():
for host in HOSTS:
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if 'key_file' in host:
client.connect(hostname=host['hostname'], username=host['username'], key_filename=host['key_file'])
else:
client.connect(hostname=host['hostname'], username=host['username'], password=host['password'])
deploy_service(client)
except Exception as e:
print(f'无法部署服务到主机 {host["hostname"]}: {e}')
finally:
client.close()
if __name__ == '__main__':
main()
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
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
上次更新: 2024/06/11, 23:05:26