linux tcpdump命令行执行后回显是一行一行输出的,但是如果用python的subprocess执行tcpdump命令就会成为一段一段的回显,实时性不高。这个怎么解决?有人说是tcpdump本身的原因,和linux缓存有关系,但是python有没有办法实现和命令行一行一行输出的效果。
代码如下
#coding=utf-8
import subprocess
p = subprocess.Popen("tcpdump udp -i eth0",shell=True,stdout=subprocess.PIPE)
while p.stdout.readline()!=' ':
line = p.stdout.readline()
line = line.strip()
print line
怪我咯2017-04-18 10:19:45
The code you gave has a bug in this line, while p.stdout.readline()!=' '
Correction as follows!
#coding=utf-8
import subprocess
p = subprocess.Popen("tcpdump udp -i eth0",shell=True,stdout=subprocess.PIPE)
while True:
line = p.stdout.readline()
line = line.strip()
if line == '':
break
print line
PHP中文网2017-04-18 10:19:45
#!/usr/bin/env python
import subprocess
subprocess.call("echo your_password | sudo -S tcpdump", shell=True)
伊谢尔伦2017-04-18 10:19:45
I also made this, used to passively start a certain port service!
import subprocess as sub
# 注意参数-l很重要(行显)
# 在Mac上测试, 所以加了sudo
pipe = sub.Popen(['sudo', 'tcpdump', '-l', '-nn', '-i', 'lo0', 'dst portrange 200000-30000'], stdout=sub.PIPE)
while True:
for row in iter(p.stdout.readline, b''):
print(row)