[英]Reading .pcap file from STDIN in Python Scapy
is there a way how to read .pcap from stdin in Python Scapy (using rdpcap)? 有没有办法从Python Scapy中的stdin读取.pcap(使用rdpcap)? Every time I try anything I got an error (can't read the file).
每次尝试任何操作时,我都会出错(无法读取文件)。
The usage is like this: 用法是这样的:
python main.py < test_linux.pcap
I have already implemented reading a file using parameters but I also need reading from STDIN. 我已经实现了使用参数读取文件,但是我还需要从STDIN中读取。
Thanks a lot. 非常感谢。
The rdpcap()
interface takes a filename and only a filename as it internally performs the open(filename)
operation on that filename. rdpcap()
接口只接受一个文件名,因为它在内部对该open(filename)
执行open(filename)
操作。 Here's a workaround via tempfile: 这是通过tempfile解决的方法:
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()
If you do not want to work around with a tempfile you'll have to re-implement RawPcapReader
and PcapReader
to take a FD instead of the filename. 如果您不想使用临时文件,则必须重新实现
RawPcapReader
和PcapReader
以获取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)
The answer by @tintin is totally correct, but now scapy can use a file descriptor as argument for rdpcap()
and PcapReader()
. @tintin的答案是完全正确的,但是现在scapy可以使用文件描述符作为
rdpcap()
和PcapReader()
。
So rdpcap(sys.stdin)
should just work as expected (if you use a recent enough version of Scapy)! 因此,
rdpcap(sys.stdin)
应该可以按预期工作(如果您使用最新版本的Scapy)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.