Python 抓包程序(pypcap)
#/usr/bin/env python
#-*-coding:utf8-*- #抓包脚本
"""
This script is used to Capture and Analysis packets Required dependencies:
libpcap-devel
Installation:
rpm -ivh ../libpcap-devel-0.9.-.el5.i386.rpm
pypcap
Installation:
tar zxvf pypcap-1.1.tar.gz
cd pypcap-1.1
CFLAGS=-m32 python setup.py config
CFLAGS=-m32 python setup.py build
CFLAGS=-m32 python setup.py install iplist Format
iplist= 'ip/mask','ip/mask' OR iplist= 'ip/mask', #本脚本主要根据ip段分析内外网流量数据,我自定义一个函数用来解析子网掩码方式的ip段,这里支持多个ip段,也支持一个段,但是要加‘,’ Writer:Dongweiming """ import pcap
import socket
import struct
import ctypes
import datetime
import threading
import inspect
import traceback
from optparse import OptionParser
from subprocess import *
import sys,os
import time iplist = '115.12.1.0/24','219.213.232.192/26' #设置解析这2个段的ip列表 def _async_raise(tid, exctype):
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == :
raise ValueError("invalid thread id")
elif res != :
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, )
raise SystemError("PyThreadState_SetAsyncExc failed")
def ipto(ip,ti):
d = ti/
c = /(**(ti%))
ip_items = ip.split('.')
if len(ip_items[d:]) == :
if ti% == :
cmin = '%s.%s' % ('.'.join(ip_items[:d]),'')
cmax = '%s.%s' % ('.'.join(ip_items[:d]),'')
else:
for i in range(**(ti%)):
mymax = (i+)*c-
mymin= i*c
data = int(''.join(ip_items[d:]))
if data < mymax and data >= mymin:
cmin = '%s.%s' % ('.'.join(ip_items[:d]),mymin)
cmax = '%s.%s' % ('.'.join(ip_items[:d]),mymax)
else:
if ti% == :
cmin = '%s.%s.%s' % ('.'.join(ip_items[:d]),'',('0.'*(len(ip_items)-d-))[:-])
cmax = '%s.%s.%s' % ('.'.join(ip_items[:d]),'',('255.'*(len(ip_items)-d-))[:-])
else:
for i in range(**(ti%)):
mymax = (i+)*c-
mymin= i*c
data = int(''.join(ip_items[d]))
if data < mymax and data >= mymin:
cmin = '%s.%s.%s' % ('.'.join(ip_items[:d]),mymin,('0.'*(len(ip_items)-d-))[:-])
cmax = '%s.%s.%s' % ('.'.join(ip_items[:d]),mymax,('255.'*(len(ip_items)-d-))[:-])
return cmin,cmax #返回ip段中可用的最小ip和最大ip class MYthread(threading.Thread): #自定义theading.Thread类,能够产生线程并且杀掉线程
def _get_my_tid(self):
if not self.isAlive():
raise threading.ThreadError("the thread is not active")
if hasattr(self, "_thread_id"):
return self._thread_id for tid, tobj in threading._active.items():
if tobj is self:
self._thread_id = tid
return tid
raise AssertionError("could not determine the thread's id")
def raise_exc(self, exctype):
_async_raise(self._get_my_tid(), exctype) def terminate(self):
self.raise_exc(SystemExit)
class Crawl(): #解析主函数
def __init__(self,eth,mytime,flag):
self.bytes =
self.bytes_out =
self.packets =
self.packets_out =
self.eth = eth
self.mytime = mytime
self.flag = flag
def myntohl(self,ip):
return socket.ntohl(struct.unpack("I",socket.inet_aton(ip))[]) #inet_aton 将ip地址的4段地址分别进行2进制转化,输出用16进制表示,
#unpack的处理是按16进制(4bit)将2进制字符,从后向前读入的,低位入
#ntohl, htonl 表示的是网络地址和主机地址之间的转换(network byte <==> host byte)
#由于unpack/pack的解/打包的颠倒顺序,必须通过htonl 或者 ntohl 进行处理
#比如从’192.168.1.235’ 可以转换为数字’’,此数字为网络字节序
def check(self,dict,uip):
flag =
for i in dict.keys():
if uip > self.myntohl(i) and uip < self.myntohl(dict[i]): #如果抓取的uip属于ip段,flag=,否则为0
# if (uip > self.myntohl('') and uip < self.myntohl('')) or (self.myntohl('') and uip < self.myntohl('')):
flag =
return flag
def run(self): #设置的抓取时间里pcap一直抓包,各个队列累加数值,最后除以时间,即平均
dict = {}
for i in iplist:
d = i.split('/')
cmin,cmax = ipto(d[],int(d[]))
dict[cmin]=cmax #这里记录一个字典,key是ip段最小的的ip,value是最大的ip if self.eth == 'all':
pc = pcap.pcap()
else:
pc = pcap.pcap(self.eth)
for ptime,pdata in pc:
#try:
# ip_type = socket.ntohs(struct.unpack("H",pdata[:])[]) #
#except:
# pass
#if ip_type != 2048:
# continue
s_uip = socket.ntohl(struct.unpack("I",pdata[+:+])[]) #源ip的网络字节序
#d_uip = socket.ntohl(struct.unpack("I",pdata[+:+])[]) #目的ip的网络字节序
bytes = socket.ntohs(struct.unpack("H",pdata[+:+])[])+ #数据的字节数
if self.check(dict,s_uip):
self.bytes_out += bytes
self.packets_out +=
else:
self.bytes += bytes
self.packets +=
def withtime(self):
pid = os.getpid()
name = sys.argv[]
Popen("kill -9 `ps -ef |grep %s|grep -v grep |awk '{print $2}'|grep -v %d`" % (name,pid),stdout=PIPE, stderr=PIPE,shell=True) #这里是
#在启动时候主动杀掉系统中存在的残留程序,使用中发现有时候(极少)执行时间到没有杀掉程序,为了定时任务安全
self.t = MYthread(target = self.run)
self.t.setDaemon()
self.t.start()
curtime = time.ctime(time.time())
t =
while t<int(self.mytime):
t +=
time.sleep()
nowtime = time.ctime(time.time())
data = "From[%s]To[%s]%s\n%s%s%s%s\n%s%s%s%s\n" \
% (curtime,nowtime,u'数据统计'.encode('utf8'),u'出网总流量/s'.encode('utf8').ljust(,' '),\
u'出网总数据包/s'.encode('utf8').ljust(,' '),u'进网总流量/s'.encode('utf8').ljust(,' '),\
u'进网总数据包/s'.encode('utf8').ljust(,' '),str(int(self.bytes_out)/int(self.mytime)).ljust(,' '),\
str(int(self.packets_out)/int(self.mytime)).ljust(,' '),str(int(self.bytes)/int(self.mytime)).ljust(,' '),\
str(int(self.packets)/int(self.mytime)).ljust(,' '))
if self.flag:
print data
self.log(data)
self.t.terminate()
self.t.join() def log(self,log): #记录日志,使用-p选项只在记录,不在终端打印,用于定时任务等需求时(定时任务执行没必要输出)
path = os.path.split(os.path.realpath(__file__))[]
log_file = "%s/common.log" % path
if not os.path.exists(log_file):
f=open(log_file,'w')
f.close()
try:
fr = open(log_file, "a+")
fr.write(log+"\r\n")
fr.close()
except Exception, e:
pass if __name__ == '__main__':
argc = len(sys.argv)
parser = OptionParser(description="Use For Capture and Analysis packets",add_help_option=False,prog="sniffer.py",usage="%prog [ -e <ethname>][ -t <time>]")
parser.add_option("-e", "--eth",action = "store",default = "all",help = "Select the card, the default is 'all'") #选择网卡,默认是all
parser.add_option("-t", "--time",action = "store",default = ,help = "Select the capture time,the default is 5s") #设置要抓包的时间,单位秒,时间越长越精确
parser.add_option("-p", "--myprint",action = "store_false",default = True,help = "Print data, the default is true")
parser.add_option("-h", "--help",action = "help",help="print help")
options, arguments=parser.parse_args()
a = Crawl(options.eth,options.time,options.myprint)
a.withtime()
参考链接:https://old.dongwm.com/old/archives/pythonzhuabaochengxupypcap/
Python 抓包程序(pypcap)的更多相关文章
- NetAnalyzer笔记 之 三. 用C++做一个抓包程序
[创建时间:2015-08-27 22:15:17] NetAnalyzer下载地址 经过前两篇的瞎扯,你是不是已经厌倦了呢,那么这篇让我们来点有意思的吧,什么,用C#.不,这篇我们先来C++的 Wi ...
- python抓包截取http记录日志
#!/usr/bin/python import pcap import dpkt import re def main(): pc=pcap.pcap(name="eth1" ...
- 基于Linux C的socket抓包程序和Package分析 (一)
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/guankle/article/details/27538031 測试执行平台:CentOS 6 ...
- (转载)基于Linux C的socket抓包程序和Package分析
转载自 https://blog.csdn.net/kleguan/article/details/27538031 1. Linux抓包源程序 在OSI七层模型中,网卡工作在物理层和数据链路层的MA ...
- linux-pcap 抓包程序框架
转:http://blog.chinaunix.net/uid-21556133-id-120228.html libpcap详解 2010-12-01 22:07 libpcap(Packet Ca ...
- 抓包程序可抓一切数据(破微信oauth2限制) 完整教程
1.下载fiddler 官网下载或者 https://www.cr173.com/soft/57378.html 2.按图设置 3.重启软件 4.看下自己的网络IP cmd->ipconfig ...
- paper 78:sniff抓包程序片段
#define INTERFACE "eth0"#define MAX_SIZE 65535 int init_raw_socket();int open_promisc(char ...
- python抓包模块
pcapy模块 安装 yum install -y epel-release yum install -y pip gcc gcc-c++ libpcap-devel python-deve ...
- python 进行抓包嗅探
一.绪论 最近一直想弄一个代理,并且对数据包进行解读,从而完成来往流量的嗅探.于是今天学习了一下如何使用Python抓包并进行解包. 首先要用到两个模块 dpkt(我这边ubuntu16.04 LTS ...
随机推荐
- 论文阅读 ORBSLAM3
这周末ORB-SLAM3出现了.先看了看论文.IMU部分没细看,后面补上. Abstract 视觉,视觉惯导,多地图SLAM系统 支持单目/立体/RGBD相机 支持pinhole/鱼眼相机 基于特征/ ...
- 数据结构C语言实现----顺序查找
建立上图的一个txt文件: 1004 TOM 1001002 lily 951001 ann 931003 lucy 98 用一个c程序读入这个表一个结构体数组中: 结构体如下: //学生数据结构体 ...
- 设在起始地址为STRING的存储空间存放了一个字符串(该串已存放在内存中,无需输入,且串长不超过99),统计字符串中字符“A”的个数,并将结果显示在屏幕上。
问题 设在起始地址为STRING的存储空间存放了一个字符串(该串已存放在内存中,无需输入,且串长不超过99),统计字符串中字符"A"的个数,并将结果显示在屏幕上. 代码 data ...
- P1429 平面最近点对[加强版] 随机化
LINK:平面最近点对 加强版 有一种分治的做法 因为按照x排序分治再按y排序 可以证明每次一个只会和周边的六个点进行更新. 好像不算很难 这里给出一种随机化的做法. 前置知识是旋转坐标系 即以某个点 ...
- php操作mysql关于文件上传、存储
php+前端+mysql实现文件上传并储存 我们都知道很多网站都需要上传文件,最普遍的就是图片上传,即是用户头像等等: 关于mysql+php实现文件查询,存储大致两个方式, 1.直接把文件写入mys ...
- FreeSql增加新特性Context
源 FreeSql 作者做了很完善的组件 我看了一下,感觉很实用,使用上有很大的可自定义操作的地方,跟传统Orm固定格式不同,也异于Dapper的设计,支持表达式树 原地址 https://www.c ...
- 【BZOJ1426】收集邮票 题解 (期望)
题目:有n种不同的邮票,皮皮想收集所有种类的邮票.唯一的收集方法是到同学凡凡那里购买,每次只能买一张,并且买到的邮票究竟是n种邮票中的哪一种是等概率的,概率均为1/n.但是由于凡凡也很喜欢邮票,所以皮 ...
- kubernetes 中安装 heapster 问题
step1: 在官网下载部署文件 https://github.com/kubernetes-retired/heapster/tree/master/deploy/kube-config/influ ...
- 团队项目-记账App
一.团队成员介绍 队长: 向瑜 博客园地址: https://www.cnblogs.com/xiangyu721/ 沟通能力较强,善于总结,能够正确分配团队任务.其次,有耐心学习新事物,发现新问题 ...
- Nginx - location常见配置指令,alias、root、proxy_pass
1.[alias]——别名配置,用于访问文件系统,在匹配到location配置的URL路径后,指向[alias]配置的路径.如: location /test/ { alias/first/secon ...