7

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
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Julie Brady
  • 79
  • 1
  • 1
  • 2

2 Answers2

8

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
Noob123
  • 528
  • 5
  • 10
  • Thanks! This helped me in writing custom packets to a pcap like this: `packet = Ether()/IP(src=src, dst=dst)/TCP(sport=sport, dport=dport, flags='A')/payload` (newline) `wrpcap(out_fname, packet, append=True)` – Luc Jun 23 '17 at 07:51
0

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.

Eriks Dobelis
  • 913
  • 7
  • 16