Python 自动化运维与爬虫 · 篇4 · 中级
← 上篇:进阶爬虫:Scrapy框架与动态页面   |   下篇:办公自动化:Excel、Word与PDF处理 →

运维自动化:脚本与定时任务

让Python成为你的运维利器,从重复劳动中解放出来
运维工程师的日常工作中,有大量重复性任务:检查服务器状态、分析日志文件、定时备份数据、批量更新配置……这些任务如果手动操作,不仅耗时费力,还容易出错。Python 凭借其丰富的标准库和第三方工具,已经成为运维自动化的首选语言。本篇将带你系统学习用 Python 编写运维脚本,从系统命令执行到远程 SSH 操作,从日志处理到定时任务调度,最后实战一个完整的服务器健康检查与告警系统。
目录
01Python在运维中的角色
02os/subprocess:执行系统命令
03文件与目录操作
04日志处理:logging模块
05SSH远程操作:paramiko
06定时任务:schedule与APScheduler
07系统监控脚本
08Ansible简介
09Ansible Playbook基础
10实战:服务器健康检查 + 邮件告警

01 · Python在运维中的角色

在 DevOps 和 SRE(站点可靠性工程)实践中,Python 占据着核心地位。它既不像 Bash 那样受限于简单的命令组合,也不像 Java 那样过于繁重,恰好处于"够用且高效"的甜蜜点。Python 在运维中主要承担这些角色:

自动化批量服务器配置、部署、监控
脚本化替代复杂的Shell脚本,提升可读性
工具链Ansible、SaltStack、Fabric等工具都基于Python
API集成与云平台、监控系统、告警系统对接

02 · os/subprocess:执行系统命令

os 模块提供了操作系统级别的功能,而 subprocess 模块则用于执行外部命令并获取输出:

Python 系统命令执行
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
import os
import subprocess

# === os模块常用操作 ===
print(os.getcwd()) # 当前工作目录
print(os.listdir("/tmp")) # 列出目录内容
print(os.getenv("HOME")) # 获取环境变量

# === subprocess执行系统命令(推荐方式) ===
# 方式一:简单执行并获取输出
result = subprocess.run(
["df", "-h"], # 命令以列表形式传入
capture_output=True, # 捕获输出
text=True # 返回字符串而非bytes
)
print(f"磁盘使用:\n{result.stdout}")
print(f"退出码: {result.returncode}")

# 方式二:执行带管道的命令
result = subprocess.run(
"ps aux | grep python | wc -l",
shell=True, # 使用shell解析(支持管道)
capture_output=True, text=True
)
print(f"Python进程数: {result.stdout.strip()}")

# 方式三:检查命令是否成功
result = subprocess.run(
["ping", "-c", "3", "8.8.8.8"],
capture_output=True, text=True
)
if result.returncode == 0:
print("网络连通 ✓")
else:
print(f"网络异常: {result.stderr}")
⚠️ 常见错误:shell=True 的安全风险
当命令参数来自用户输入时,使用 shell=True 有命令注入风险。例如用户输入 "; rm -rf /" 会导致灾难性后果。在可能的情况下,始终使用列表形式传参并设置 shell=False。

03 · 文件与目录操作

运维脚本经常需要操作文件系统:查找日志、清理临时文件、备份数据等。Python 提供了多个模块来处理这些任务:

Python 文件与目录操作
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
import shutil
import glob
from pathlib import Path
from datetime import datetime, timedelta

# === pathlib:现代路径操作(推荐) ===
log_dir = Path("/var/log/myapp")

# 遍历目录下的所有日志文件
for log_file in log_dir.glob("*.log"):
size_mb = log_file.stat().st_size / (1024 * 1024)
print(f"{log_file.name}: {size_mb:.1f} MB")

# === 清理超过7天的旧日志 ===
cutoff = datetime.now() - timedelta(days=7)

for log_file in log_dir.glob("*.log"):
mtime = datetime.fromtimestamp(log_file.stat().st_mtime)
if mtime < cutoff:
log_file.unlink() # 删除文件
print(f"已删除: {log_file.name}")

# === shutil:高级文件操作 ===
# 复制文件
shutil.copy2("config.yaml", "config.yaml.bak")

# 压缩整个目录
shutil.make_archive(
"backup_2024", "zip",
root_dir="/data/myapp"
)

# === glob:通配符匹配 ===
access_logs = glob.glob("/var/log/nginx/access*.log")
print(f"找到 {len(access_logs)} 个访问日志")
💡 小贴士:pathlib vs os.path
pathlib 是 Python 3.4+ 引入的现代路径操作库,语法比 os.path 更直观。推荐使用 Path 对象代替字符串拼接路径,它会自动处理不同操作系统的路径分隔符。

04 · 日志处理:logging模块

运维脚本必须有良好的日志,否则出问题时根本不知道发生了什么。Python 的 logging 模块提供了分级日志系统:

级别 用途 场景示例
DEBUG 调试信息 变量值、函数调用
INFO 正常运行信息 任务开始/完成
WARNING 潜在问题 磁盘使用超过80%
ERROR 错误信息 连接失败、文件不存在
CRITICAL 严重故障 服务宕机、数据丢失
Python 日志配置与使用
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
import logging
from logging.handlers import RotatingFileHandler

# 配置日志器
logger = logging.getLogger("ops_monitor")
logger.setLevel(logging.DEBUG)

# 控制台输出
console = logging.StreamHandler()
console.setLevel(logging.INFO)
fmt = logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
console.setFormatter(fmt)
logger.addHandler(console)

# 文件输出(自动轮转,每个文件5MB,保留3个)
file_handler = RotatingFileHandler(
"ops.log",
maxBytes=5*1024*1024,
backupCount=3,
encoding="utf-8"
)
file_handler.setFormatter(fmt)
logger.addHandler(file_handler)

# 使用日志
logger.info("服务器健康检查开始")
logger.debug("检查目标: 192.168.1.100")
logger.warning("磁盘使用率已达85%%")
logger.error("SSH连接失败: Connection refused")

05 · SSH远程操作:paramiko

在运维中,经常需要在远程服务器上执行命令。paramiko 是 Python 中最流行的 SSH 客户端库:

Python SSH远程执行命令
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
import paramiko

def ssh_exec(host, username, command, key_file=None):
"""在远程服务器上执行命令"""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(
paramiko.AutoAddPolicy()
)
try:
# 使用密钥认证(推荐)
if key_file:
client.connect(
host, port=22,
username=username,
key_filename=key_file
)
else:
# 密码认证
client.connect(
host, port=22,
username=username,
password="your_password"
)
# 执行命令
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read().decode("utf-8")
error = stderr.read().decode("utf-8")
exit_code = stdout.channel.recv_exit_status()
return {
"output": output,
"error": error,
"exit_code": exit_code
}
finally:
client.close()

# 使用示例:批量检查多台服务器
servers = ["192.168.1.10", "192.168.1.11", "192.168.1.12"]

for server in servers:
result = ssh_exec(
server, "deploy",
"uptime && free -h",
key_file="~/.ssh/id_rsa"
)
print(f"[{server}] {result['output']}")

06 · 定时任务:schedule与APScheduler

运维脚本通常需要定时执行。schedule 库适合简单的定时任务,APScheduler 则适合更复杂的场景:

Python 定时任务调度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import schedule
import time

# === schedule库:简单易用的定时任务 ===
def check_disk():
print("检查磁盘使用情况...")
# ... 检查逻辑

def backup_db():
print("备份数据库...")
# ... 备份逻辑

# 设置定时任务
schedule.every(10).minutes.do(check_disk)
schedule.every().day.at("02:00").do(backup_db)
schedule.every().monday.at("09:00").do(check_disk)

# 主循环:持续运行并检查任务
while True:
schedule.run_pending()
time.sleep(1)

Cron表达式速查

表达式 含义
* * * * * 每分钟执行
*/5 * * * * 每5分钟执行
0 * * * * 每小时整点执行
0 2 * * * 每天凌晨2点执行
0 9 * * 1-5 工作日每天9点执行
0 0 1 * * 每月1号零点执行

07 · 系统监控脚本

psutil 是一个跨平台的系统监控库,可以获取 CPU、内存、磁盘、网络等信息:

Python 系统资源监控
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
import psutil

# CPU使用率
cpu_pct = psutil.cpu_percent(interval=1)
print(f"CPU使用率: {cpu_pct}%")

# 内存信息
mem = psutil.virtual_memory()
print(f"内存总量: {mem.total / 1024**3:.1f} GB")
print(f"内存使用: {mem.percent}%")

# 磁盘信息
for part in psutil.disk_partitions():
usage = psutil.disk_usage(part.mountpoint)
print(
f"{part.mountpoint}: "
f"{usage.percent}% used "
f"({usage.free / 1024**3:.1f} GB free)"
)

# 网络连接数
connections = psutil.net_connections(kind="inet")
print(f"当前TCP连接数: {len(connections)}")

# 进程列表(CPU占用最高的前5个)
processes = sorted(
psutil.process_iter(["name", "cpu_percent"]),
key=lambda p: p.info["cpu_percent"] or 0,
reverse=True
)[:5]
for p in processes:
print(f" {p.info['name']}: {p.info['cpu_percent']}%")

08 · Ansible简介与Playbook基础

Ansible 是一个无 Agent 的自动化运维工具,它通过 SSH 协议远程管理服务器,无需在被管理节点安装任何软件。Ansible 本身用 Python 编写,可以用 Python 扩展自定义模块。

💡 Ansible 核心优势
1. 无Agent:不需要在被管服务器安装任何软件
2. 幂等性:同一 Playbook 执行多次结果一致
3. 声明式:描述"期望状态"而非"执行步骤"
4. YAML配置:可读性强,易于版本管理
YAML Ansible Playbook示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# deploy.yml - 部署Web应用
---
- hosts: webservers
become: yes
vars:
app_name: my-web-app
app_version: "2.1.0"
tasks:
- name: 安装Nginx
apt:
name: nginx
state: present
- name: 部署应用代码
git:
repo: "https://github.com/user/{{ app_name }}"
dest: /opt/{{ app_name }}
version: "v{{ app_version }}"
- name: 重启Nginx服务
systemd:
name: nginx
state: restarted

10 · 实战:服务器健康检查 + 邮件告警

最后一个实战项目:编写一个服务器健康检查脚本,定期检查 CPU、内存、磁盘使用情况,当超过阈值时自动发送邮件告警。

Python 完整实战:健康检查+邮件告警
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
import psutil
import smtplib
import logging
import schedule
import time
from email.mime.text import MIMEText
from datetime import datetime

# === 配置 ===
THRESHOLDS = {
"cpu": 80, # CPU使用率阈值
"memory": 85, # 内存使用率阈值
"disk": 90 # 磁盘使用率阈值
}
EMAIL_CONFIG = {
"smtp_server": "smtp.example.com",
"smtp_port": 465,
"sender": "ops@example.com",
"password": "your_email_password",
"receivers": ["admin@example.com"]
}

# === 日志配置 ===
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
logger = logging.getLogger(__name__)

def check_system():
"""检查系统资源并返回告警列表"""
alerts = []
# 检查CPU
cpu = psutil.cpu_percent(interval=2)
logger.info(f"CPU: {cpu}%")
if cpu > THRESHOLDS["cpu"]:
alerts.append(f"CPU使用率过高: {cpu}%")
# 检查内存
mem = psutil.virtual_memory()
logger.info(f"内存: {mem.percent}%")
if mem.percent > THRESHOLDS["memory"]:
alerts.append(f"内存使用率过高: {mem.percent}%")
# 检查磁盘
disk = psutil.disk_usage("/")
logger.info(f"磁盘: {disk.percent}%")
if disk.percent > THRESHOLDS["disk"]:
alerts.append(f"磁盘使用率过高: {disk.percent}%")
return alerts

def send_alert_email(alerts):
"""发送告警邮件"""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
body = f"服务器告警通知\n时间: {now}\n\n"
body += "\n".join(f"- {a}" for a in alerts)
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = f"[告警] 服务器异常 - {now}"
msg["From"] = EMAIL_CONFIG["sender"]
msg["To"] = ", ".join(EMAIL_CONFIG["receivers"])
try:
server = smtplib.SMTP_SSL(
EMAIL_CONFIG["smtp_server"],
EMAIL_CONFIG["smtp_port"]
)
server.login(
EMAIL_CONFIG["sender"],
EMAIL_CONFIG["password"]
)
server.send_message(msg)
server.quit()
logger.info("告警邮件发送成功")
except Exception as e:
logger.error(f"邮件发送失败: {e}")

def health_check_job():
"""定时任务:执行健康检查"""
logger.info("=== 开始健康检查 ===")
alerts = check_system()
if alerts:
logger.warning(f"发现 {len(alerts)} 个告警")
send_alert_email(alerts)
else:
logger.info("所有指标正常 ✓")

# === 主程序 ===
if __name__ == "__main__":
# 每5分钟检查一次
schedule.every(5).minutes.do(health_check_job)
# 启动时先执行一次
health_check_job()
while True:
schedule.run_pending()
time.sleep(1)

这个脚本整合了 psutil 系统监控、logging 日志记录、schedule 定时调度和 smtplib 邮件发送。在生产环境中,你可以进一步扩展:添加多台服务器支持、接入企业微信/钉钉告警、将数据写入 InfluxDB 配合 Grafana 可视化展示。

💡 部署建议
1. 用 systemd 将脚本注册为系统服务,实现开机自启
2. 或使用 crontab 替代 schedule 库进行调度
3. 生产环境建议将告警发送到企业微信或钉钉群
4. 配合 supervisor 实现进程守护和自动重启
📋 本篇知识回顾
subprocess pathlib/glob/shutil logging日志 paramiko SSH schedule定时任务 psutil监控 Ansible 邮件告警
下一篇预告
05 · 办公自动化:Excel、Word与PDF处理
最后一篇,我们将从运维场景转向办公场景,学习用 Python 自动处理 Excel 表格、生成 Word 文档、操作 PDF 文件。你将学会从 Excel 数据自动生成月度销售报告,真正实现"让 Python 替你干活"。
相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书