Python 操作 Linux 命令行

二、基础用法示例

1. 执行简单命令(无输出捕获)

python 复制代码
# 执行 ls -l 命令
subprocess.run(["ls", "-l"])

# 使用 shell=True(注意安全风险)
subprocess.run("ls -l | grep .txt", shell=True)

2. 捕获命令输出

python 复制代码
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print("输出内容:", result.stdout)
print("错误信息:", result.stderr)
print("返回码:", result.returncode)

3. 执行命令并检查错误

python 复制代码
try:
    subprocess.run(["invalid_command"], check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
    print(f"命令执行失败: {e}")

三、进阶操作示例

1. 管道操作(|

python 复制代码
# 实现 ls -l | grep .py
p1 = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["grep", ".py"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
output = p2.communicate()[0]
print(output.decode())

2. 输入重定向(<

python 复制代码
# 等价于 grep "hello" < input.txt
with open("input.txt", "r") as f:
    result = subprocess.run(["grep", "hello"], stdin=f, text=True, capture_output=True)
print(result.stdout)

3. 输出重定向(>

python 复制代码
# 等价于 ls -l > output.txt
with open("output.txt", "w") as f:
    subprocess.run(["ls", "-l"], stdout=f)

四、实用场景示例

1. 系统信息获取

python 复制代码
# 获取内核版本
uname_result = subprocess.run(["uname", "-r"], capture_output=True, text=True)
print("内核版本:", uname_result.stdout.strip())

# 获取磁盘使用情况
df_result = subprocess.run(["df", "-h"], capture_output=True, text=True)
print(df_result.stdout)

2. 文件操作

python 复制代码
# 创建目录
subprocess.run(["mkdir", "-p", "test_dir"])

# 递归复制目录
subprocess.run(["cp", "-r", "src_dir", "dest_dir"])

# 压缩文件
subprocess.run(["tar", "-czvf", "archive.tar.gz", "target_dir"])

3. 软件包管理

python 复制代码
# 更新软件包列表(Ubuntu)
subprocess.run(["sudo", "apt", "update"])

# 安装软件
subprocess.run(["sudo", "apt", "install", "nginx", "-y"])

4. 后台进程

python 复制代码
# 启动后台进程(不会阻塞Python脚本)
subprocess.Popen(["python3", "long_running_script.py"])

五、高级技巧

1. 环境变量控制

python 复制代码
# 添加自定义环境变量
env = {"CUSTOM_ENV": "123"}
subprocess.run(["env"], env=env, capture_output=True, text=True)

2. 超时控制

python 复制代码
try:
    subprocess.run(["sleep", "10"], timeout=5)
except subprocess.TimeoutExpired:
    print("命令执行超时!")

3. 交互式命令(如 sudo)

python 复制代码
# 通过 stdin 输入密码(需要配置免密 sudo 更安全)
password = "your_password\n"
result = subprocess.run(
    ["sudo", "-S", "apt", "update"],
    input=password, 
    text=True, 
    capture_output=True
)
print(result.stdout)

六、安全注意事项

  1. 避免 shell=True :除非必要,否则不要使用 shell=True,可能引发命令注入漏洞
  2. 输入校验:所有外部输入需经过严格过滤
  3. 错误处理 :始终检查 returncodestderr

七、完整实战示例

python 复制代码
import subprocess

def system_info():
    # 获取系统信息
    print("=== 系统信息 ===")
    subprocess.run(["uptime"])
    subprocess.run(["free", "-h"])

def backup_directory(src, dest):
    # 目录备份
    print(f"正在备份 {src} 到 {dest}")
    subprocess.run(["rsync", "-avz", src, dest])

if __name__ == "__main__":
    system_info()
    backup_directory("/home/user/docs", "/backup/")
相关推荐
qq_14182697322 分钟前
python通过curl访问deepseek的API调用案例
java·数据库·python
红衣小蛇妖2 小时前
Python基础学习-Day23
开发语言·python·学习
Hello world.Joey2 小时前
数据挖掘入门-二手车交易价格预测
人工智能·python·数据挖掘·数据分析·conda·pandas
刘延林.2 小时前
树莓5安装 PyCharm 进行python脚本开发
ide·python·pycharm
小洛~·~3 小时前
多模态RAG与LlamaIndex——1.deepresearch调研
人工智能·python·深度学习·神经网络·chatgpt
q_q王3 小时前
‌FunASR‌阿里开源的语音识别工具
python·大模型·llm·语音识别
不学无术の码农4 小时前
《Effective Python》第1章 Pythonic 思维总结——编写优雅、高效的 Python 代码
开发语言·python
zhou1854 小时前
MySQL保姆级安装教程(附资源包+5分钟极速配置+环境变量调试技巧)
java·python·mysql·php
lczdyx4 小时前
PNG转ico图标(支持圆角矩形/方形+透明背景)Python脚本 - 随笔
图像处理·python
lgily-12255 小时前
常用的设计模式详解
java·后端·python·设计模式