python - 监控模式下的 Scapy 嗅探

标签 python network-programming wifi scapy

我使用 scapy 编写了一个 python 脚本来嗅探 WIFI 网络中的 TCP 数据包,并查看两个目的地之间是否存在连接。 如果我不在监控模式下嗅探数据包,它会起作用,但当我在监控模式接口(interface)上嗅探时,它不起作用。

有什么想法可以使它发挥作用吗? 片段:

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import time

class deferring_delete(object):
def __init__(self, d):
    self._dict = d
def __enter__(self):
    self._deletes = set()
    return self
def __exit__(self, type, value, tb):
    for key in self._deletes:
        try:
            del self._dict[key]
        except KeyError:
            pass
    del self._deletes
def __delitem__(self, key):
    if key not in self._dict:
        raise KeyError(str(key))
    self._deletes.add(key)

packet_count = 0
packets = {}
accepted = {}
YOUR_IP = '10.0.0.1'
FILTER = "tcp and host not {0}".format(YOUR_IP) 

def handshake_status(packet):
    global packets,accepted,packet_count


    flag = packet[0][1].sprintf('%TCP.flags%')
    src_ip = packet[0][1].src
    dst_ip = packet[0][1].dst

    if flag == 'S':
        packets[packet_count] = {'src_ip': src_ip, 'dst_ip': dst_ip, 'time': time.ctime() , 'flag': flag} 
        print "%s ==> %s SYN_SENT" % (src_ip, dst_ip)
        packet_count += 1

    if flag == 'SA':
        for key , packet in packets.iteritems():
            if packet['src_ip'] == dst_ip:
                accepted[key] = packet

    if len(accepted) > 0:
        with deferring_delete(packets) as p:
            for key in accepted.keys():
                print "%s ==> %s ESTABLISHED" % (packets[key]['src_ip'], packets[key]['dst_ip'])
                del p[key]

        with deferring_delete(accepted) as a:
            for key in accepted.keys():
                del a[key]


if __name__ == '__main__':
    sniff(iface="mon0", filter=FILTER ,prn=handshake_status)

最佳答案

问题出在以下几行:

flag = packet[0][1].sprintf('%TCP.flags%')
src_ip = packet[0][1].src
dst_ip = packet[0][1].dst

尝试按如下方式重写它们:

flag = packet.getlayer(TCP).sprintf('%TCP.flags%')
src_ip = packet.getlayer(IP).src
dst_ip = packet.getlayer(IP).dst

关于python - 监控模式下的 Scapy 嗅探,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33619386/

相关文章:

ios - 如何在 iOS 编程中检查网络提供商名称?

Android 下载管理器 'Download Requires Network' 错误

python - Odoo 10 - 链接记录的计数值

python - Django 网址给我不同的方向

c - 使用 SO_REUSEADDR - 之前打开的套接字会发生什么?

c# - 端口 21 (FTP) 上的 NetworkStream 在收到值为 10(换行符)的字节时停止读取

python - 导入SWIG+python模块报错"undefined symbol"

python - 库达 API 错误 : [1] Call to cuLaunchKernel results in CUDA_ERROR_INVALID_VALUE in Python

C HTTP 服务器 - 多线程模型?

java - NetworkChangeReceiver的onReceive方法在3G和WIFI同时开启时被多次调用