2015-10-16 148 views
2

有没有办法在Python Scapy中使用stdin读取.pcap(使用rdpcap)?每次我尝试任何东西时,都会收到错误消息(无法读取文件)。从Python中的STDIN中读取.pcap文件Scapy

用法是这样的:

python main.py < test_linux.pcap 

我已经实现了使用参数读取文件,但我还需要从标准输入读。

非常感谢。

回答

2

rdpcap()接口只接受文件名和文件名,因为它在内部对该文件名执行open(filename)操作。下面是通过临时文件解决方法:

from scapy.all import * 
import tempfile 
import sys 

if __name__=="__main__": 
    ftmp = tempfile.NamedTemporaryFile(delete=True) 
    ftmp.write(sys.stdin.read()) 
    ftmp.flush() 
    print rdpcap(ftmp.name) 
    ftmp.close() 

如果你不想解决了临时文件,你将不得不重新实现RawPcapReaderPcapReader采取了FD,而不是文件名。

from scapy.all import * 
import sys 

class RawPcapReaderFD(RawPcapReader): 
    """A stateful pcap reader. Each packet is returned as a string""" 

    def __init__(self, fd): 
     self.filename = "dummy" 
     try: 
      self.f = fd 
      magic = self.f.read(4) 
     except IOError: 
      self.f = fd 
      magic = self.f.read(4) 
     if magic == "\xa1\xb2\xc3\xd4": #big endian 
      self.endian = ">" 
     elif magic == "\xd4\xc3\xb2\xa1": #little endian 
      self.endian = "<" 
     else: 
      raise Scapy_Exception("Not a pcap capture file (bad magic)") 
     hdr = self.f.read(20) 
     if len(hdr)<20: 
      raise Scapy_Exception("Invalid pcap file (too short)") 
     vermaj,vermin,tz,sig,snaplen,linktype = struct.unpack(self.endian+"HHIIII",hdr) 

     self.linktype = linktype 

class PcapReader(RawPcapReaderFD): 
    def __init__(self, fd): 
     RawPcapReaderFD.__init__(self, fd) 
     try: 
      self.LLcls = conf.l2types[self.linktype] 
     except KeyError: 
      warning("PcapReader: unknown LL type [%i]/[%#x]. Using Raw packets" % (self.linktype,self.linktype)) 
      self.LLcls = conf.raw_layer 


print PcapReader(sys.stdin).read_all(-1) 
+0

非常感谢您提供非常有见地的解释。最终我转向了C++实现,这是IMO更快,但使用起来有点麻烦。 – Petr

1

通过@tintin答案是完全正确的,但现在Scapy的可以使用文件描述符作为参数为rdpcap()PcapReader()

所以rdpcap(sys.stdin)应该像预期的那样工作(如果您使用最近版本的Scapy)!