【发布时间】:2019-01-18 00:53:08
【问题描述】:
我正在开发一个 python 脚本来收集有关 Linux 系统的几条信息,现在我正在尝试使用 os.popen() 收集侦听 UDP e 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 模块的方式有什么问题吗?
【问题讨论】:
标签: python python-3.x python-2.7 shell