使用python和wincap抓包

环境安装

  1. easy_install winpcapy
  2. easy_install pcapy

在这第2步安装pcapy时报错了:

Searching for pcapy
Reading https://pypi.python.org/simple/pcapy/
Best match: pcapy 0.11.1
Downloading https://pypi.python.org/packages/7f/12/626c6c1ee949b6d447f887a65388aa83faec6feb247e1bdf2478139a6078/pcapy-0.11.1.tar.gz#md5=24f8f339f1f1b00b2b43fe3c6910cbc1
Processing pcapy-0.11.1.tar.gz
Writing c:\users\terry\appdata\local\temp\easy_install-vf9ep5\pcapy-0.11.1\setup.cfg
Running pcapy-0.11.1\setup.py -q bdist_egg --dist-dir c:\users\terry\appdata\local\temp\easy_install-vf9ep5\pcapy-0.11.1\egg-dist-tmp-0vrahf
error: Setup script exited with error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27

原来pcapy下载下来不是直接可用的,而是需要先编译,按照提示在浏览器中打开了http://aka.ms/vcpython27链接,跳转到微软官网上下载了Microsoft Visual C++ Compiler for Python 2.7,然后安装,安装位置是%appdata%\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0,安装后继续easy_install,结果又报一错误。

...
Running pcapy-0.11.1\setup.py -q bdist_egg --dist-dir c:\users\terry\appdata\local\temp\easy_install-ger_s1\pcapy-0.11.1\egg-dist-tmp-kl4a0h
pcapdumper.cc
pcapdumper.cc(11) : fatal error C1083: Cannot open include file: 'pcap.h': No such file or directory
error: Setup script exited with error: command 'C:\\Users\\terry\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2

由上可以看出来在编译pcapy时,还需要引用winpcap的头文件pcap.h,可以从winpcap网站下载,截止目前最新的版本是https://www.winpcap.org/install/bin/WpdPack_4_1_2.zip。由于我机器上已经有些c++的项目带了一些pcap的库,所以我直接在Visual C++ for Python的安装目录下找到了vcvarsall.bat,然后编辑之,修改INCLUDE和LIB路径加上winpcap开发sdk的安装目录(D:\VC_INCLUDE\winpcap那个是我加的):

set INCLUDE=D:\VC_INCLUDE\winpcap\Include;%VCINSTALLDIR%Include;%WindowsSdkDir%Include;%INCLUDE%
set LIB=D:\VC_INCLUDE\winpcap\Lib;%VCINSTALLDIR%Lib;%WindowsSdkDir%Lib;%LIB%
set LIBPATH=D:\VC_INCLUDE\winpcap\Lib;%VCINSTALLDIR%Lib;%WindowsSdkDir%Lib;%LIBPATH%

然后再编译,就成功了。

示例代码

使用pcap抓包,再使用dpkt解析包

#! python3
# coding: utf-8

__author__ = 'terry'

import logging
from winpcapy import WinPcapDevices
from winpcapy import WinPcapUtils

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='myapp.log',
                    filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

logging.info("当前机器上有以下网卡")
logging.info(WinPcapDevices.list_devices())

# Example Callback function to parse IP packets
def packet_callback(win_pcap, param, header, pkt_data):
    # Assuming IP (for real parsing use modules like dpkt)
    ip_frame = pkt_data[14:]
    # Parse ips
    src_ip = ".".join([str(ord(b)) for b in ip_frame[0xc:0x10]])
    dst_ip = ".".join([str(ord(b)) for b in ip_frame[0x10:0x14]])
    print("%s -> %s" % (src_ip, dst_ip))


# WinPcapUtils.capture_on("*Ethernet*", packet_callback)


import pcap
import dpkt

sniffer = pcap.pcap()
sniffer.setfilter('tcp port 80')  # 过滤功能,可以设置需要显示的


def process_packet(ptime, packet):
    tem = dpkt.ethernet.Ethernet(packet)
    if tem.data.data.__class__.__name__ == 'TCP':
        http_data = tem.data.data.data
        if len(http_data) > 0:
            if http_data.startswith(b"HTTP"):
                # http response
                response = dpkt.http.Response(http_data)
                pass
            else:
                # http request
                req = dpkt.http.Request(http_data)
                host = str(req.headers["host"])
                cookie = str(req.headers["cookie"])
                path = str(req.uri)
                if host.index("qianka.com"):
                    logging.info("QianKa message:" + host + cookie + path)
                pass


def print_http_packet(ts, buf):
    eth = dpkt.ethernet.Ethernet(buf)
    ip = eth.data
    # This is an oversimplification - IP packets can fragment if an MTU in the path is smaller than the MTU of the LAN
    # Also, this changes a little bit with IPv6.  To tell the difference between IPv4 and IPv6, you have to look
    # at the ethertype field, which is given by http://www.iana.org/assignments/ethernet-numbers.  IPv4 is 0x800 or 2048
    # and IPv6 is 0x86DD or 34525
    tcp = ip.data
    # This is an oversimplification - this is true if and only if the protocol field of the IP packet is 6.
    # See http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml for details of protocol numbers.
    # See http://tools.ietf.org/html/rfc791 for details on IPv4

    # If the destination port is 80 and there is data in the packet, then probably this is an HTTP request.
    # TO be certain, there should
    # be a TCP finite state machine in here.
    if tcp.dport == 80 and len(tcp.data) > 0:
        http_req = dpkt.http.Request(tcp.data)
        print("URI is ", http_req.uri)
        for header in http_req.headers.keys():
            print(header, http_req.headers[header])
        # ['_Request__methods', '_Request__proto', '__class__', '__delattr__', '__dict__', '__doc__',
        #  '__format__', '__getattribute__', '__getitem__', '__hash__', '__hdr_defaults__', '__init__',
        #  '__len__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
        # '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'body', 'data',
        # 'headers', 'method', 'pack', 'pack_hdr', 'unpack', 'uri', 'version']
        print("method is ", http_req.method)
        # 'body', 'data', 'headers', 'method', 'pack', 'pack_hdr', 'unpack', 'uri', 'version'
        print("HTTP headers, packed ", http_req.pack())
        print("HTTP version", http_req.version)
        print("HTTP data ", http_req.data)  # I think this is valid if the method is POST
    if tcp.sport == 80 and len(tcp.data) > 0:
        try:
            http = dpkt.http.Response(tcp.data)
            print("HTTP version is ", http.version)
            print("Status code is ", http.status)
            print("Status reason ", http.reason)
            for header in http.headers.keys():
                print(header, http.headers[header])
                # print "date", http.headers['date']
                # print "accept-ranges", http.headers['accept-ranges']
                # print "content-type", http.headers['content-type']
                #            print "connection", http.headers['connection']
                #            print "server", http.headers['server']
        except dpkt.dpkt.UnpackError:
            print("Encounted an unpacking error")


for ptime, packet in sniffer:
    try:
        # process_packet(ptime, packet)
        print_http_packet(ptime, packet)
    except Exception as e:
        # print(e)
        pass

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容