Julie Brady
Julie Brady

Reputation: 79

Writing to a pcap with scapy

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

Upvotes: 7

Views: 34196

Answers (2)

Noob123
Noob123

Reputation: 548

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

Upvotes: 9

Eriks Dobelis
Eriks Dobelis

Reputation: 913

pkt[UDP].sport should normally be integer not string. str(ports) shall be replaced with just ports.

I am using scapy v3.x. If you still have problems try it with scapy 3.x (pip install scapy-python3), and I will be able to follow through with you. The only required change from python2 to python3 I see in this code sample is replacing raw_input with input.

Upvotes: 0

Related Questions