欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python調(diào)用tcpdump抓包過濾的方法

 更新時間:2018年07月18日 09:04:24   作者:wangqiuyun  
這篇文章主要為大家詳細(xì)介紹了python調(diào)用tcpdump抓包過濾的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了python調(diào)用tcpdump抓包過濾的具體代碼,供大家參考,具體內(nèi)容如下

之前在linux用python腳本寫一個抓包分析小工具,實在不想用什么libpcap、pypcap所以,簡單來了個tcpdump加grep搞定?;舅悸肥欠謩e起tcpdump和grep兩個進(jìn)程,進(jìn)程直接通過pipe交換數(shù)據(jù),簡單代碼如下:

#! /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'這個參數(shù),官方文檔貌似沒有明確提及,但是它是你解決丟包的關(guān)鍵地方之一,當(dāng)然還有-s這個參數(shù)也得好好利用!其他的大家可以自由發(fā)揮!

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論