Handling tcpdump output in python

前端 未结 2 1098
死守一世寂寞
死守一世寂寞 2020-12-28 08:36

Im trying to handle tcpdump output in python.

What I need is to run tcpdump (which captures the packets and gives me information) and read the output and process it.

相关标签:
2条回答
  • 2020-12-28 09:09

    You can make tcpdump line-buffered with "-l". Then you can use subprocess to capture the output as it comes out.

    import subprocess as sub
    
    p = sub.Popen(('sudo', 'tcpdump', '-l'), stdout=sub.PIPE)
    for row in iter(p.stdout.readline, b''):
        print row.rstrip()   # process here
    
    0 讨论(0)
  • 2020-12-28 09:24

    By default, pipes are block buffered and interactive output is line buffered. It sounds like you need a line buffered pipe - coming from tcpdump in a subprocess.

    In the old days, we'd recommend Dan Bernstein's "pty" program for this kind of thing. Today, it appears that pty hasn't been updated in a long time, but there's a new program called "emtpy" which is more or less the same idea: http://empty.sourceforge.net/

    You might try running tcpdump under empty in your subprocess to make tcpdump line buffered even though it's writing to a pipe.

    0 讨论(0)
提交回复
热议问题