You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中获取Bash命令的布尔返回值 实现sshd检测逻辑

问题原因
  • 你使用shlex.split拆分带管道符|的Shell命令时,|、grep、-q等内容会全部被当做pstree的启动参数传递,pstree本身没有-q选项,因此触发参数错误。
  • 原Bash脚本中的$$指代当前Shell进程的PID,直接写到传给subprocess的命令中不会被自动解析,需要替换为Python侧获取的当前进程PID。
  • 你预设的os.system逻辑存在判断倒置问题:Shell中if后命令退出码为0代表条件成立,而Python中0对应布尔值False,直接按你写的判断会走反分支。
正确实现方案

方案1:启用Shell解析(适合自用场景)

直接设置shell=True让subprocess调用系统Shell解析管道语法,无需手动拆分参数:

import os
import subprocess

# 替换$$为当前Python进程PID
cmd = f"pstree -s {os.getpid()} | grep -q 'sshd'"
ret = subprocess.run(cmd, shell=True, capture_output=True).returncode

if ret == 0:
    os.environ['SOME_VAR'] = 'foo'
else:
    os.environ['SOME_VAR'] = 'boo'

方案2:手动拼接管道(无Shell注入风险,适合生产环境)

如果需要避免Shell注入风险,可以手动串联两个进程的输入输出:

import os
import subprocess
import shlex

# 分别定义两个命令的参数
pstree_args = shlex.split(f"pstree -s {os.getpid()}")
grep_args = shlex.split("grep -q 'sshd'")

# 先执行pstree,捕获输出
pstree_proc = subprocess.run(pstree_args, capture_output=True)
# 将pstree的输出作为grep的输入执行
grep_proc = subprocess.run(grep_args, input=pstree_proc.stdout, capture_output=True)

if grep_proc.returncode == 0:
    os.environ['SOME_VAR'] = 'foo'
else:
    os.environ['SOME_VAR'] = 'boo'

内容的提问来源于stack exchange,提问作者dsmoly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:27:03