python调用tcpdump抓包过滤的方法

yipeiwu_com6年前Python基础

本文实例为大家分享了python调用tcpdump抓包过滤的具体代码,供大家参考,具体内容如下

之前在linux用python脚本写一个抓包分析小工具,实在不想用什么libpcap、pypcap所以,简单来了个tcpdump加grep搞定。基本思路是分别起tcpdump和grep两个进程,进程直接通过pipe交换数据,简单代码如下:

#! /usr/bin/python
 
def 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 p2
 
 
def poll_tcpdump(proc):
 #print 'poll_tcpdump....'
 import select
 txt = None
 while True:
 # wait 1/10 second 
 readReady, _, _ = select.select([proc.stdout.fileno()], [], [], 0.1)
 if not len(readReady):
  break
 try:
  for line in iter(proc.stdout.readline, ""):
  if txt is None:
   txt = ''
  txt += line
 except IOError:
  print 'data empty...'
  pass
 break
 return txt
 
 
proc = tcpdump()
while True:
 text = poll_tcpdump(proc)
 if text:
 print '>>>> ' + text

运行效果:


其中值得注意tcpdump中'-B', '4096'这个参数,官方文档貌似没有明确提及,但是它是你解决丢包的关键地方之一,当然还有-s这个参数也得好好利用!其他的大家可以自由发挥!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pandas 选择某几列的方法

如下所示: col_n = ['名称','收盘价','日期'] a = pd.DataFrame(df,columns = col_n) 以上这篇pandas 选择某几列的方法就...

Python同步遍历多个列表的示例

Python同步遍历多个列表的示例

Python的for循环十分灵活,使用for循环我们可以很轻松地遍历一个列表,例如: a_list = ['z', 'c', 1, 5, 'm'] for each in a_lis...

Python ljust rjust center输出

看下面的例子就会明白了: 复制代码 代码如下:print '|','*'.ljust(10),'|' print '|','*'.ljust(10,'-'),'|' print '|',...

Win7上搭建Cocos2d-x 3.1.1开发环境

Win7上搭建Cocos2d-x 3.1.1开发环境

开发工具的准备 搭建开发环境需要安装工具包括 Visual Studio python ———(本教程以python2.7.3版本为例),下载地址:http://www.python.o...

使用pycharm生成代码模板的实例

通过在File->setting->File and Code Templates设置模板代码,这样就可以在新建python文件的时候自动带上抬头。 # -*- codi...