Python calls Tcpdump packet filter

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.