用scapy写一个pcap

时间:2015-11-16 16:55:06

标签: python pcap scapy

我过滤掉所有NBNS流量后尝试写入pcap文件。这给了我一个语法错误。

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)

我发现语法错误的答案只是...str(ports))))末尾的缺失括号,但现在我有一个不同的错误。

  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

2 个答案:

答案 0 :(得分:4)

我正在尝试你的脚本,但无法按照它的编写方式进行。我改变了一点,我认为它做你需要的。希望这会有所帮助。

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

答案 1 :(得分:-1)

pkt[UDP].sport通常应该是整数而不是字符串。 str(ports)应仅用ports替换。

我正在使用scapy v3.x.如果你仍然有问题,请尝试使用scapy 3.x(pip install scapy-python3),我将能够跟进你。从python2到python3的唯一必要更改我在此代码示例中看到的是用输入替换raw_input。