gpt4 book ai didi

python - netstat 无法与 popen 一起正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:17 26 4
gpt4 key购买 nike

使用 Python 运行此命令时

p = Popen(['netstat', '-atunp'], shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
print stdout

我得到了不同的输出。也就是说,如果我从命令行运行相同的命令,我可以看到 IP 地址和应用程序名称,而使用 Python 则看不到。

我还需要做什么才能查看 IP 地址和应用名称吗?

最佳答案

我想我在没有 -p 标志的情况下运行了你的命令。该标志需要一个协议(protocol)。这可能就是你的标准输出字符串为空的原因;另一方面,stderr 会出现错误 -

In [86]: stderr
Out[86]: 'netstat: option requires an argument -- p\nUsage:\tnetstat [-AaLlnW] [-f address_family | -p protocol]\n\tnetstat [-gilns] [-f address_family]\n\tnetstat -i | -I interface [-w wait] [-abdgRt]\n\tnetstat -s [-s] [-f address_family | -p protocol] [-w wait]\n\tnetstat -i | -I interface -s [-f address_family | -p protocol]\n\tnetstat -m [-m]\n\tnetstat -r [-Aaln] [-f address_family]\n\tnetstat -rs [-s]\n\n'

因此,像这样更新您的命令(删除 shell=True 并添加协议(protocol)作为参数) -

In [87]: paste
p = Popen(['netstat', '-atunp', 'tcp'], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
print stdout

## -- End pasted text --
Active Internet connections (including servers)
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp4 0 0 192.168.1.100.53076 198.252.206.140.80 ESTABLISHED
tcp4 0 0 192.168.1.100.53075 198.252.206.140.80 ESTABLISHED
tcp4 0 0 192.168.1.100.53004 216.58.220.3.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52984 74.125.200.155.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52954 198.252.206.149.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52927 91.189.89.222.443 FIN_WAIT_1
tcp4 0 0 192.168.1.100.52925 173.194.120.144.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52869 74.125.130.155.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52863 74.125.68.139.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52858 74.125.130.102.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52851 74.125.68.93.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52847 74.125.200.132.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52814 216.58.216.163.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52812 74.125.68.189.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52794 74.125.130.17.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52793 198.252.206.149.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52761 74.125.68.138.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52737 74.125.68.132.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52577 17.172.232.205.443 ESTABLISHED
tcp4 0 0 192.168.1.100.52571 74.125.130.188.443 ESTABLISHED
tcp6 0 0 fd9a:f3a0:3346:7.4488 *.* LISTEN
tcp4 0 0 *.* *.* CLOSED
tcp4 0 0 127.0.0.1.631 *.* LISTEN
tcp6 0 0 ::1.631 *.* LISTEN

关于python - netstat 无法与 popen 一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30037671/

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