【问题标题】:Reading os.popen() output returns nothing读取 os.popen() 输出不返回任何内容
【发布时间】: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)

我面临的问题是:当我使用上面的函数执行脚本时,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 模块的方式有什么问题吗?

【问题讨论】:

    标签: python python-3.x python-2.7 shell


    【解决方案1】:

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

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

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

    (顺便说一下,我通常会推荐使用subprocess 模块,但是不使用shell=Truesubprocess 一起使用管道命令会很尴尬,并且使用shell=True 会破坏subprocess 的大部分好处。如果你但是,如果您发现自己在运行时构建命令字符串,请务必切换到 subprocess,而不是尝试使用字符串格式处理。)

    【讨论】:

    • 不知道原始字符串...非常感谢!并感谢子流程提示!去看看吧!
    猜你喜欢
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多