subprocess - python实时获取tcpdump输出
天蓬老师
天蓬老师 2017-04-18 10:17:45
0
4
858

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
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(4)
刘奇

tcpdump -l options

刘奇

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
洪涛
#!/usr/bin/env python

import subprocess

subprocess.call("echo your_password | sudo -S tcpdump", shell=True)
伊谢尔伦

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template