Python calls tcpdump for packet capture filtering and pythontcpdump
Previously, I used a python script in linux to write a small package capture analysis tool. I really didn't want to use libpcap or pypcap. So I just came up with a tcpdump and grep. The basic idea is to start two processes: tcpdump and grep. The process directly exchanges data through pipe. The simple code is as follows:
#! /usr/bin/pythondef tcpdump():import subprocess, fcntl, os# sudo tcpdump -i eth0 -n -s 0 -w - | grep -a -o -E "Host: .*|GET /.*"cmd1 = ['tcpdump', '-i', 'eth0', '-n','-B', '4096','-s', '0', '-w', '-']cmd2 = ['grep', '--line-buffered', '-a', '-o', '-E', 'Host: .*|GET /.*']p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)p2 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stdin=p1.stdout)flags = fcntl.fcntl(p2.stdout.fileno(), fcntl.F_GETFL)fcntl.fcntl(p2.stdout.fileno(), fcntl.F_SETFL, (flags | os.O_NDELAY | os.O_NONBLOCK))return p2def poll_tcpdump(proc):#print 'poll_tcpdump....'import selecttxt = Nonewhile True:# wait 1/10 second readReady, _, _ = select.select([proc.stdout.fileno()], [], [], 0.1)if not len(readReady):breaktry:for line in iter(proc.stdout.readline, ""):if txt is None:txt = ''txt += lineexcept IOError:print 'data empty...'passbreakreturn txtproc = tcpdump()while True:text = poll_tcpdump(proc)if text:print '>>>> ' + text
Running effect:
It is worth noting that the '-B' and '123' parameters in tcpdump are not explicitly mentioned in the official documentation, but they are one of the key points for solving packet loss, of course, the-s parameter must be well used! Everyone else can play it freely!
Reprinted Please note: http://blog.csdn.net/wangqiuyun/article/details/46966839
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.