当前位置:首页>python>脚本开发与运维工具(第2篇)之Python 运维常用库(os, subprocess, requests)

脚本开发与运维工具(第2篇)之Python 运维常用库(os, subprocess, requests)

  • 2026-09-10 11:50:30
脚本开发与运维工具(第2篇)之Python 运维常用库(os, subprocess, requests)

上一期我们讲了基础,这一期咱们直接上硬菜,聊聊Python运维里最常用的三个库:os、subprocess和requests。这三个家伙,用好了是神器,用不好就是给自己挖坑。今天我就把我在生产环境里亲手填过的几个坑,连同填坑的土方量,一并分享给大家。

一、os模块:别让它“静默”地坑你

os模块是Python和操作系统交互的门面,但很多人只把它当“文件搬运工”。我见过最经典的坑,就是用os.system()去执行命令。

坑位1:os.system的“黑盒”输出

有一次,一个自动化搭建脚本用os.system('cp /data/app/config.yaml /data/app/config.yaml.bak')做备份。看起来没问题对吧?但某天磁盘满了,cp命令失败了,os.system却默默返回了一个非零的退出码,而脚本完全没检查这个返回值,继续往下执行了。结果新版本的设置没备份,回滚时直接炸了。

填坑方案: 永远不要用os.system()。用os.popen()或者更现代的subprocess。如果非要用os模块,请务必使用os.popen()并读取返回值。

import os

# 错误示范
# os.system('cp a.txt b.txt')

# 正确姿势:检查返回值
ret = os.system('cp a.txt b.txt')
if ret != 0:
    raise RuntimeError(f"备份失败,退出码: {ret}")

# 更推荐的:用os.popen获取输出
with os.popen('ls -la /data/app/') as f:
    output = f.read()
    if 'config.yaml' not in output:
        print("警告: 设置文件不存在")

坑位2:路径拼接的“跨平台”陷阱

os.path.join是好人,但很多人用字符串加法。Windows和Linux的路径分隔符不一样,用+拼接的路径,在Windows上直接报错。

import os

# 错误示范
# path = '/data/app/' + 'config.yaml'  # 硬编码分隔符

# 正确姿势
base_dir = '/data/app'
config_file = os.path.join(base_dir, 'config.yaml')
print(config_file)  # 输出: /data/app/config.yaml

# 检查文件是否存在
if os.path.exists(config_file):
    print("文件存在")

二、subprocess:管理子进程的“瑞士军刀”

subprocess是os.system和os.popen的终极进化版,但坑也不少。

坑位3:shell=True的“引号地狱”

我见过最离谱的代码:subprocess.call('grep "error" /var/log/nginx/access.log | wc -l', shell=True)。这在本地跑没问题,但一旦参数里包含用户输入,比如grep "{}".format(user_input),用户输入一个"; rm -rf /"`,你就等着哭吧。这不是异常行为,这是脚本自爆。

填坑方案: 永远、永远、永远不要用shell=True,除非你100%确定参数是硬编码的常量。用列表传参。

import subprocess

# 错误示范(shell=True + 字符串拼接)
# cmd = f'grep "{user_input}" /var/log/nginx/access.log'
# subprocess.call(cmd, shell=True)

# 正确姿势(列表传参,无shell)
result = subprocess.run(
    ['grep', 'error', '/var/log/nginx/access.log'],
    capture_output=True,
    text=True,
    check=False  # 不自动抛异常,自己处理
)
if result.returncode == 0:
    print(f"找到 {len(result.stdout.splitlines())} 行错误")
elif result.returncode == 1:
    print("没有找到错误")
else:
    print(f"命令执行失败: {result.stderr}")

坑位4:超时处理的“僵尸进程”

有一次,一个脚本用subprocess.Popen调了一个长时间运行的备份命令,结果网络断了,脚本没等它结束就退出了。这个子进程变成了孤儿进程,一直在后台跑,占着CPU和文件句柄,最后把服务器搞卡了。

import subprocess
import time

# 错误示范(不设置超时)
# proc = subprocess.Popen(['sleep', '3600'])
# proc.wait()  # 如果命令卡住,这里永远不返回

# 正确姿势:设置超时并清理
try:
    proc = subprocess.Popen(['sleep', '10'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate(timeout=5)  # 最多等5秒
except subprocess.TimeoutExpired:
    print("命令超时,强制终止")
    proc.kill()  # 先发SIGKILL
    proc.wait()  # 等待进程真正结束,避免僵尸
    stdout, stderr = proc.communicate()  # 获取剩余输出
    print("已清理子进程")

三、requests:HTTP调用的“优雅陷阱”

requests库让HTTP调用变得像喝水一样简单,但运维场景下,细节是魔鬼。

坑位5:连接池耗尽与SSL验证

我们有一个监控脚本,每10秒调用一次内部API。刚开始用requests.get(url, verify=False)图省事。结果某天API服务器证书过期了,verify=False虽然能跳过验证,但连接池里的连接全被卡住了,最终导致urllib3的连接池耗尽,所有新请求都报Connection pool is full。

填坑方案: 永远不要在生产环境关掉SSL验证。如果证书有问题,去修证书,而不是关验证。同时,要管理好连接池。

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# 错误示范(关SSL + 无重试)
# resp = requests.get('https://internal-api.example.com/health', verify=False)

# 正确姿势:使用Session + 重试 + 超时
session = requests.Session()

# 设置重试策略
retry_strategy = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy, pool_connections=10, pool_maxsize=20)
session.mount('https://', adapter)
session.mount('http://', adapter)

try:
    # 必须设置超时,否则可能永远等待
    resp = session.get(
        'https://internal-api.example.com/health',
        timeout=(3.05, 10),  # (连接超时, 读取超时)
        verify='/etc/ssl/certs/ca-certificates.crt'  # 指定CA证书路径
    )
    resp.raise_for_status()  # 检查HTTP状态码
    print(f"API健康检查通过: {resp.json()}")
except requests.exceptions.RequestException as e:
    print(f"API调用失败: {e}")
finally:
    session.close()  # 显式关闭session,释放连接

坑位6:大文件下载的内存爆炸

用requests.get(url).content下载一个1GB的日志文件,脚本直接OOM被kill。这是新手最容易犯的错误。

import requests

# 错误示范(一次性加载到内存)
# content = requests.get('http://example.com/bigfile.log').content

# 正确姿势:流式下载
url = 'http://example.com/bigfile.log'
local_path = '/tmp/bigfile.log'

with requests.get(url, stream=True, timeout=(5, 60)) as r:
    r.raise_for_status()
    with open(local_path, 'wb') as f:
        for chunk in r.iter_content(chunk_size=8192):
            if chunk:  # 过滤掉keep-alive的空chunk
                f.write(chunk)
                f.flush()  # 确保数据写入磁盘
print(f"文件下载完成,大小: {os.path.getsize(local_path)} 字节")

总结

这三个库,每个都有自己的一亩三分地。os负责文件系统和环境,subprocess负责外部命令,requests负责网络通信。记住几个铁律:

  1. 永远检查返回值:不管是os.system的退出码,还是subprocess.run的returncode,还是requests的status_code。
  2. 永远设置超时:subprocess的timeout,requests的timeout,没有超时的脚本就是一颗定时炸弹。
  3. 永远不要用shell=True:除非你写的是玩具脚本。
  4. 永远管理好资源:文件句柄、连接池、子进程,用完要关,超时要杀。

这些坑,我都是拿线上事故换来的经验。希望各位看完之后,能少走一些弯路。下一期,我们聊聊日志处理和监控告警,敬请期待。

👨‍💻 运维老兵经验:根据实际生产环境,以上步骤建议先在测试环境验证,并做好备份。参数值需根据服务器设置调整,不要盲目照搬。

如果喜欢,点个「在看」分享给朋友吧。

最新文章

随机文章