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/")
相关推荐
go&Python19 分钟前
检索模型与RAG
开发语言·python·llama
阿里云大数据AI技术1 小时前
ODPS 十五周年实录 | Data + AI,MaxCompute 下一个15年的新增长引擎
大数据·python·sql
RainbowJie11 小时前
Gemini CLI 与 MCP 服务器:释放本地工具的强大潜力
java·服务器·spring boot·后端·python·单元测试·maven
工作碎碎念1 小时前
NumPy------数值计算
python
工作碎碎念1 小时前
pandas
python
A7bert7772 小时前
【YOLOv5部署至RK3588】模型训练→转换RKNN→开发板部署
c++·人工智能·python·深度学习·yolo·目标检测·机器学习
冷月半明2 小时前
时间序列篇:Prophet负责优雅,LightGBM负责杀疯
python·算法
教练我想打篮球_基本功重塑版3 小时前
L angChain 加载大模型
python·langchain
跟橙姐学代码5 小时前
手把手教你玩转 multiprocessing,让程序跑得飞起
前端·python·ipython
LCS-3125 小时前
Python爬虫实战: 爬虫常用到的技术及方案详解
开发语言·爬虫·python