Python calls tcpdump for packet capture filtering and pythontcpdump

Source: Internet
Author: User

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.

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.