WinPcap has compatibility issues with Windows 10, therefore it's recommended to use Npcap (Nmap's packet sniffing library for Windows, based on the WinPcap/Libpcap libraries, but with improved speed, portability, security, and efficiency). Please enable WinPcap API-compatible mode during the library installation.
安装下载后的Npcap安装包,如果电脑带有无线网卡,记得勾选“support raw 802.11 traffic(and monitor mode) for wireless adapters”。需要注意的是,如果电脑已经安装过winpcap软件,在安装Npcap时会弹窗提示卸载Winpcap,此时需要关闭wireshark或是其它相关的软件
安装pypcap
将Npcap SDK文件夹和pypcap源码文件夹放在一个目录下
将Npcap SDK文件夹名称修改为wpdpack
进入pypcap源码目录,执行python setup.py install即可完成安装
在第三步需要注意的是,如果Python版本为3.7.2(其它大于3.7的版本没试过)有可能编译失败,因为有个头文件pystate.h在高版本会有更新,导致结构体_ts PyThreadState中的某些参数不识别,从而提示错误pcap.c(22849): error C2039: 'exc_value': is not a member of '_ts'等。之后我将版本换至3.6.6后便正常编译了。
安装完成后,可以进入python执行import pcap查看是否已经可以正常导入。
简单使用
1 2 3 4 5 6 7 8 9 10 11
import pcap
# list all of the Internet devices devs = pcap.findalldevs() print(*devs, sep='\n')
pc = pcap.pcap(devs[3], promisc=True, immediate=True, timeout_ms=50) # fiter http pcakets pc.setfilter('tcp port 80') for ptime, pdata in pc: print(ptime, pdata)
➜ python Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pcap >>> pcap.findalldevs() ['enp2s0', 'any', 'lo', 'nflog', 'nfqueue', 'usbmon1', 'usbmon2'] >>>
import getopt import sys import datetime import time import os import platform
if'Windows'in platform.platform(): import winreg as wr
IF_REG = r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318}' defgetInterfaceByName(name): '''Get guid of interface from regedit of windows system
Args: name: interface name
Returns: An valid guid value or None.
Example: getInterfaceByName('eth0') ''' reg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE) reg_key = wr.OpenKey(reg, IF_REG) for i inrange(wr.QueryInfoKey(reg_key)[0]): subkey_name = wr.EnumKey(reg_key, i) try: reg_subkey = wr.OpenKey(reg_key, subkey_name + r'\Connection') Name = wr.QueryValueEx(reg_subkey, 'Name')[0] wr.CloseKey(reg_subkey) if Name == name: returnr'\Device\NPF_' + subkey_name except FileNotFoundError as e: pass