章工运维 章工运维
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)

章工运维

业精于勤,荒于嬉
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)
  • python

    • python基础

      • python基础知识
      • python基础较难的15个知识点
    • FastAPI

    • python每日练习脚本

    • python3给防火墙添加放行
    • python生成部署脚本
    • python将多个文件内容输出到一个文件中
    • 使用 Aligo 定时备份服务器文件
    • python监控日志文件并发送钉钉告警
    • python监控数据库脚本并发送钉钉告警
    • 使用python编写自动化发布脚本
    • 查询redis列表某个元素
    • centos7安装python3
    • python环境管理工具介绍
    • conda安装和镜像源配置
    • pip更换国内源
    • python爬虫
    • python环境启动服务报错缺少glibc库版本
    • 监控目录或文件变化
    • 批量更改文件
    • python引用数据库
  • shell

  • go

  • 编程
  • python
章工运维
2024-06-05

使用python编写自动化发布脚本

脚本内容如下

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
182
微信 支付宝
上次更新: 2024/06/05, 16:23:38

← python监控数据库脚本并发送钉钉告警 查询redis列表某个元素→

最近更新
01
shell脚本模块集合
05-13
02
生活小技巧(认知版)
04-29
03
生活小技巧(防骗版)
04-29
更多文章>
Theme by Vdoing | Copyright © 2019-2025 | 点击查看十年之约 | 鄂ICP备2024072800号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式