Writing to a pcap with scapy

Julie Brady picture Julie Brady · Nov 16, 2015 · Viewed 18k times · Source

I'm trying to write to a pcap file once I filter out all NBNS traffic. This is giving me a syntax error.

from scapy.all import *

Capture = raw_input("Enter file path of pcap file: " )
pcap = rdpcap(Capture)

ports=137

filtered = (pkt for pkt in Capture if
    (UDP in pkt and 
    (pkt[UDP].sport in str(ports)))

wrpcap("filtered.pcap",filtered)

I found the answer for the syntax error was just a missing parenthesis at the end of ...str(ports)))) but now I have a different error.

  File "receiver2.py", line 18, in <module>
    wrpcap("filtered.pcap",filtered)
  File "/usr/lib/python2.7/dist-packages/scapy/utils.py", 
    line 470, in wrpcap
  PcapWriter(filename, *args, **kargs).write(pkt)
  File "/usr/lib/python2.7/dist-packages/scapy/utils.py", line 652, in write
    for p in pkt:
  File "receiver2.py", line 13, in <genexpr>
    (UDP in pkt and 
  TypeError: 'in <string>' requires string as left operand, not Packet_metaclass

Answer

Noob123 picture Noob123 · Nov 18, 2015

I was trying out your script but couldn't get it going the way it was written. I changed it a bit and I think it does what you need. Hope this helps.

from scapy.all import *

capture = raw_input("Enter file path of pcap file: " )
pcap = rdpcap(capture)

ports=137

def write(pkt):
    wrpcap('filtered.pcap', pkt, append=True)  #appends packet to output file

for pkt in pcap:
    if pkt.haslayer(UDP) and pkt.getlayer(UDP).sport == ports:  #checks for UDP layer and sport 137
        write(pkt)  #sends the packet to be written if it meets criteria
    else:
        pass