Python使用scapy库监听指定的网卡数据并转发

  • 监听指定网卡中的数据(UDP)
  • 数据转发
    具体实现代码如下:
python 复制代码
from scapy.all import *
from scapy.layers.inet import UDP, IP
from scapy.layers.l2 import Ether


def Callback(packet):
    # 目的IP
    dst_ip = packet[IP].dst
    # 源IP
    src_ip = packet[IP].src
    # 目的端口
    dst_port = packet[UDP].dport
    # 数据
    value = packet['Raw'].load
    # 目的MAC地址
    dst_mac = packet['Ether'].dst
    # 源MAC地址
    src_mac = packet['Ether'].src
    print(f"收:{packet}")
    # 转发数据
    forward_udp(dst_mac, src_mac, dst_ip, src_ip, dst_port, value)


def forward_udp(dst_mac, src_mac, dst_ip, src_ip, dst_port, value):
    """
    转发数据至指定目标
    :param dst_mac: 目的MAC
    :param src_mac: 源MAC
    :param dst_ip: 目的IP
    :param src_ip: 源IP
    :param dst_port: 目的端口
    :param value: 数据
    :return:
    """
    # 创建以太网层
    eth = Ether(dst=dst_mac, src=src_mac)
    # 创建IP层
    ip = IP(src=src_ip, dst=dst_ip)
    # 创建UDP层
    udp = UDP(dport=dst_port + 1)
    # 创建一个UDP数据包
    packet = eth / ip / udp / Raw(value)
    print(f"发:{packet}")
    # 通过原始套接字发送数据包,iface:指定网卡名称
    sendp(packet, iface="WLAN")


if __name__ == '__main__':
	# 目标地址
	IP = '192.168.3.1'
	# 目标端口
	Port = '9999'
	# 监听的规则,iface:监听的网卡名称
    sniff(filter=f"udp and host {IP} and port  {Port}", iface="WLAN", count=-1, prn=Callback)
相关推荐
AI探索者36 分钟前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者37 分钟前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽3 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时7 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿9 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python