我正在开发一个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)
我面临的问题是:当我使用变量 tcpOpenPorts
和 udpOpenPorts
上面的函数执行脚本时,即使 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/