gpt4 book ai didi

python - 读取 os.popen() 输出不返回任何内容

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:54 25 4
gpt4 key购买 nike

我正在开发一个 python 脚本来收集有关 Linux 系统的几条信息,现在我正在尝试使用 os.popen() 收集监听 UDP 和 TCP 端口的列表,这里是函数的样子:

def ports(self):
# Gets a few lines of information about open TCP ports
tcpOpenPorts = os.popen("netstat -tulpn | grep -P 'tcp\b'").read()
print(tcpOpenPorts)
# Gets a few lines of information about open UDP ports
udpOpenPorts = os.popen("netstat -tulpn | grep -P 'tcp\b'").read()
print(udpOpenPorts)

我面临的问题是:当我使用上面的函数执行脚本时,变量 tcpOpenPortsudpOpenPorts 都返回空,即使 shell 命令:

netstat -tulpn | grep -P 'tcp\b'

正常工作。

这是命令的示例输出:

tcp        0      0 127.0.0.1:63342         0.0.0.0:*               OUÇA       3244/java
tcp 0 0 0.0.0.0:111 0.0.0.0:* OUÇA 539/rpcbind
tcp 0 0 0.0.0.0:22 0.0.0.0:* OUÇA 686/sshd
tcp 0 0 127.0.0.1:631 0.0.0.0:* OUÇA 4466/cupsd
tcp 0 0 127.0.0.1:6942 0.0.0.0:* OUÇA 3244/java

我使用 os 模块的方式有什么问题吗?

最佳答案

单引号会阻止 shell 处理反斜杠,但 shell 并不是唯一需要阻止处理反斜杠的东西。 Python 字符串文字语法还为反斜杠赋予特殊含义,因此 shell 接收退格字符而不是反斜杠和 b。

使用原始字符串文字来避免 Python 的反斜杠处理:

os.popen(r"netstat ...")

(顺便说一下,我可能通常会推荐使用 subprocess 模块,但是如果不使用 shell=True,将命令与 subprocess 一起使用会很尴尬,并使用 shell=True 破坏了 subprocess 的大部分好处。不过,如果您发现自己在运行时构建命令字符串,一定要切换到 subprocess 而不是尝试使用字符串格式来处理事情。)

关于python - 读取 os.popen() 输出不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54246369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com