Python案例做嗅探?

wen 网络安全 48

本文目录导读:

Python案例做嗅探?

  1. 基础网络嗅探器(使用scapy)
  2. HTTP流量分析嗅探器
  3. ARP扫描与嗅探器
  4. WiFi密码嗅探器(仅供学习)
  5. 简易包过滤器
  6. 安装依赖
  7. 使用注意事项

我来为你介绍几个Python网络嗅探的实用案例,这些案例主要用于学习和测试目的,请注意遵守相关法律法规。

基础网络嗅探器(使用scapy)

from scapy.all import *
def packet_callback(packet):
    """处理捕获的数据包"""
    if IP in packet:
        ip_src = packet[IP].src
        ip_dst = packet[IP].dst
        if TCP in packet:
            # TCP数据包
            print(f"[TCP] {ip_src}:{packet[TCP].sport} -> {ip_dst}:{packet[TCP].dport}")
            if packet[TCP].payload:
                print(f"      Payload: {bytes(packet[TCP].payload)[:100]}")
        elif UDP in packet:
            # UDP数据包
            print(f"[UDP] {ip_src}:{packet[UDP].sport} -> {ip_dst}:{packet[UDP].dport}")
        elif ICMP in packet:
            # ICMP数据包(ping)
            print(f"[ICMP] {ip_src} -> {ip_dst}")
def basic_sniffer(interface="eth0", count=10):
    """基础嗅探器"""
    print(f"开始嗅探 {interface},捕获 {count} 个数据包...")
    # 捕获数据包
    packets = sniff(iface=interface, prn=packet_callback, count=count)
    print(f"\n捕获完成,共捕获 {len(packets)} 个数据包")
if __name__ == "__main__":
    # 使用示例
    basic_sniffer(interface="eth0", count=20)

HTTP流量分析嗅探器

from scapy.all import *
import re
class HttpSniffer:
    def __init__(self, interface="eth0"):
        self.interface = interface
        self.http_requests = []
    def extract_http_info(self, packet):
        """提取HTTP请求信息"""
        if TCP in packet and packet[TCP].payload:
            try:
                # 尝试解析HTTP请求
                payload = bytes(packet[TCP].payload).decode('utf-8', errors='ignore')
                if 'HTTP' in payload:
                    # 提取请求行
                    lines = payload.split('\r\n')
                    request_line = lines[0] if lines else ""
                    if request_line.startswith(('GET', 'POST', 'PUT', 'DELETE')):
                        # 提取URL
                        method, url, version = request_line.split(' ')
                        # 提取Host
                        host = ""
                        for line in lines:
                            if line.lower().startswith('host:'):
                                host = line.split(': ')[1]
                                break
                        return {
                            'method': method,
                            'host': host,
                            'url': url,
                            'timestamp': packet.time
                        }
            except:
                pass
        return None
    def analyze_http(self, packet):
        """分析HTTP流量"""
        info = self.extract_http_info(packet)
        if info:
            self.http_requests.append(info)
            print(f"[HTTP] {info['method']} {info['host']}{info['url']}")
            # 分析敏感信息
            payload = bytes(packet[TCP].payload).decode('utf-8', errors='ignore')
            if 'password' in payload.lower() or 'login' in payload.lower():
                print(f"[!] 检测到可能的敏感信息!")
                print(f"    Payload: {payload[:200]}")
    def start_sniffing(self, count=50):
        """开始嗅探"""
        print(f"开始HTTP流量嗅探 ({self.interface})...")
        sniff(iface=self.interface, 
              prn=self.analyze_http, 
              filter="tcp port 80", 
              count=count)
        print(f"\n捕获统计:")
        print(f"总HTTP请求: {len(self.http_requests)}")
# 使用示例
# sniffer = HttpSniffer("eth0")
# sniffer.start_sniffing(30)

ARP扫描与嗅探器

from scapy.all import *
import threading
from collections import defaultdict
class ArpSniffer:
    def __init__(self, interface="eth0"):
        self.interface = interface
        self.arp_table = defaultdict(list)
        self.running = False
    def detect_arp_spoof(self, packet):
        """检测ARP欺骗攻击"""
        if ARP in packet and packet[ARP].op == 2:  # ARP回复
            ip = packet[ARP].psrc
            mac = packet[ARP].hwsrc
            # 检查是否已有IP-MAC对应关系
            if ip in self.arp_table:
                if mac not in self.arp_table[ip]:
                    print(f"[!] ARP欺骗检测!")
                    print(f"    IP: {ip}")
                    print(f"    原MAC: {self.arp_table[ip][0]}")
                    print(f"    新MAC: {mac}")
            else:
                self.arp_table[ip].append(mac)
                print(f"[ARP] 新条目: {ip} -> {mac}")
    def scan_network(self, network="192.168.1.0/24"):
        """扫描网络设备"""
        print(f"扫描网络 {network}...")
        # 发送ARP请求
        ans, unans = arping(network, iface=self.interface, verbose=0)
        print(f"发现 {len(ans)} 个活跃设备:")
        for sent, received in ans:
            print(f"  IP: {received.psrc:15} MAC: {received.hwsrc}")
            self.arp_table[received.psrc].append(received.hwsrc)
    def start_sniffing(self):
        """开始ARP嗅探"""
        self.running = True
        print(f"开始ARP嗅探 ({self.interface})...")
        sniff(iface=self.interface,
              prn=self.detect_arp_spoof,
              filter="arp",
              store=0,
              stop_filter=lambda x: not self.running)
# 使用示例
# sniffer = ArpSniffer("eth0")
# sniffer.scan_network("192.168.1.0/24")
# sniffer.start_sniffing()

WiFi密码嗅探器(仅供学习)

from scapy.all import *
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
class WifiSniffer:
    def __init__(self, interface="wlan0mon"):
        self.interface = interface
        self.probes = []
    def capture_probe_requests(self, packet):
        """捕获探测请求"""
        if packet.haslayer(Dot11) and packet.type == 0 and packet.subtype == 4:
            # 提取SSID
            if packet.haslayer(Dot11ProbeReq):
                try:
                    ssid = packet.info.decode('utf-8', errors='ignore')
                    if ssid:  # 忽略空SSID
                        mac = packet.addr2
                        print(f"[探针] 设备 {mac} 搜索网络: {ssid}")
                        self.probes.append({
                            'mac': mac,
                            'ssid': ssid,
                            'time': packet.time
                        })
                except:
                    pass
    def capture_handshake(self, packet):
        """捕获WPA握手包"""
        if packet.haslayer(EAPOL):
            print(f"[握手] 捕获到WPA握手包!")
            print(f"   源MAC: {packet.addr2}")
            print(f"   目的MAC: {packet.addr1}")
            # 保存握手包
            wrpcap("handshake.pcap", packet, append=True)
    def start_monitor(self, duration=60):
        """开始监控"""
        print(f"开始监控无线网络 ({self.interface})...")
        print("监控时间: {}秒".format(duration))
        # 混合模式嗅探
        sniff(iface=self.interface,
              prn=lambda x: self.capture_probe_requests(x) or self.capture_handshake(x),
              timeout=duration)
        print(f"\n捕获完成!")
        print(f"检测到 {len(self.probes)} 个探测请求")
# 使用前需要将网卡设置为监控模式
# sudo airmon-ng start wlan0
# 然后使用 wlan0mon 作为接口

简易包过滤器

from scapy.all import *
class PacketFilter:
    def __init__(self, interface="eth0"):
        self.interface = interface
        self.rules = []
    def add_rule(self, rule_type, value):
        """添加过滤规则"""
        self.rules.append({'type': rule_type, 'value': value})
    def apply_filter(self, packet):
        """应用过滤规则"""
        for rule in self.rules:
            if rule['type'] == 'ip_src':
                if IP in packet and packet[IP].src != rule['value']:
                    return False
            elif rule['type'] == 'ip_dst':
                if IP in packet and packet[IP].dst != rule['value']:
                    return False
            elif rule['type'] == 'port':
                if TCP in packet:
                    if packet[TCP].sport != rule['value'] and packet[TCP].dport != rule['value']:
                        return False
                elif UDP in packet:
                    if packet[UDP].sport != rule['value'] and packet[UDP].dport != rule['value']:
                        return False
            elif rule['type'] == 'protocol':
                if rule['value'].upper() == 'TCP' and TCP not in packet:
                    return False
                elif rule['value'].upper() == 'UDP' and UDP not in packet:
                    return False
                elif rule['value'].upper() == 'ICMP' and ICMP not in packet:
                    return False
        return True
    def filter_and_sniff(self, count=10):
        """过滤并嗅探"""
        print(f"使用规则过滤: {self.rules}")
        def callback(packet):
            if self.apply_filter(packet):
                print(f"通过过滤: {packet.summary()}")
        sniff(iface=self.interface, prn=callback, count=count)
# 使用示例
# filter = PacketFilter("eth0")
# filter.add_rule('protocol', 'TCP')
# filter.add_rule('port', 80)
# filter.filter_and_sniff(20)

安装依赖

# 安装scapy
pip install scapy
# 安装加密库(用于WPA嗅探)
pip install cryptography
# Linux下可能需要安装npcap或使用root权限
# Ubuntu/Debian:
sudo apt-get install python3-scapy
# Windows需要安装Npcap
# https://npcap.com/

使用注意事项

  1. 法律合规:仅在您拥有明确权限的网络上进行嗅探
  2. 权限要求:大多数操作系统需要root/管理员权限
  3. 网络接口:确保使用正确的网络接口名称
  4. 性能影响:大量数据包嗅探可能会影响系统性能

这些案例涵盖了网络嗅探的主要应用场景,从基础的包捕获到特定协议的分析,请始终在合法和道德的范围内使用这些技术。

抱歉,评论功能暂时关闭!