Before Linux with a Python script to write a grab packet analysis gadget, really do not want to use what libpcap, Pypcap so, simple to a tcpdump plus grep to fix. The basic idea is to start tcpdump and grep two processes, the process directly through the pipe Exchange data, simple code 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
Operating effect:
It is worth noting that the tcpdump '-B ', ' 4096 ', the official document does not seem to be explicitly mentioned, but it is one of the key points to solve the loss of the package, of course, and the-s parameter also have to make good use of! Everyone else is free to play!
Reprint Please specify: http://blog.csdn.net/wangqiuyun/article/details/46966839
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python calls Tcpdump packet filter