本文整理汇总了Python中scapy.utils.PcapReader类的典型用法代码示例。如果您正苦于以下问题:Python PcapReader类的具体用法?Python PcapReader怎么用?Python PcapReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PcapReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: RdpcapSource
class RdpcapSource(Source):
"""Read packets from a PCAP file send them to low exit.
+----------+
>>-| |->>
| |
>-| [pcap]--|->
+----------+
"""
def __init__(self, fname, name=None):
Source.__init__(self, name=name)
self.fname = fname
self.f = PcapReader(self.fname)
def start(self):
print "start"
self.f = PcapReader(self.fname)
self.is_exhausted = False
def stop(self):
print "stop"
self.f.close()
def fileno(self):
return self.f.fileno()
def deliver(self):
p = self.f.recv()
print "deliver %r" % p
if p is None:
self.is_exhausted = True
else:
self._send(p)
开发者ID:guedou,项目名称:scapy-issues,代码行数:28,代码来源:scapypipes.py
示例2: sniff
def sniff(count=0, store=1, offline=None, prn = None, lfilter=None, L2socket=None, timeout=None, *arg, **karg):
"""Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets
Select interface to sniff by setting conf.iface. Use show_interfaces() to see interface names.
count: number of packets to capture. 0 means infinity
store: wether to store sniffed packets or discard them
prn: function to apply to each packet. If something is returned,
it is displayed. Ex:
ex: prn = lambda x: x.summary()
lfilter: python function applied to each packet to determine
if further action may be done
ex: lfilter = lambda x: x.haslayer(Padding)
offline: pcap file to read packets from, instead of sniffing them
timeout: stop sniffing after a given time (default: None)
L2socket: use the provided L2socket
"""
c = 0
if offline is None:
log_runtime.info('Sniffing on %s' % conf.iface)
if L2socket is None:
L2socket = conf.L2listen
s = L2socket(type=ETH_P_ALL, *arg, **karg)
else:
s = PcapReader(offline)
lst = []
if timeout is not None:
stoptime = time.time()+timeout
remain = None
while 1:
try:
if timeout is not None:
remain = stoptime-time.time()
if remain <= 0:
break
try:
p = s.recv(MTU)
except PcapTimeoutElapsed:
continue
if p is None:
break
if lfilter and not lfilter(p):
continue
if store:
lst.append(p)
c += 1
if prn:
r = prn(p)
if r is not None:
print(r)
if count > 0 and c >= count:
break
except KeyboardInterrupt:
break
s.close()
return plist.PacketList(lst,"Sniffed")
开发者ID:ouje,项目名称:scapy,代码行数:58,代码来源:__init__.py
示例3: read
def read(file_name, start, count):
'''
read packets from pcap according to the start packet number and total count
'''
reader = PcapReader(file_name)
if start > 0:
reader.read_all(start)
if count > 0:
return reader.read_all(count)
else:
return reader.read_all(-1)
开发者ID:susanpray,项目名称:python,代码行数:11,代码来源:pcapread.py
示例4: parse_pcap_files
def parse_pcap_files(self, pcapFiles, quite=True):
"""
Take one more more (list, or tuple) of pcap files and parse them
into the engine.
"""
if not hasattr(pcapFiles, '__iter__'):
if isinstance(pcapFiles, str):
pcapFiles = [pcapFiles]
else:
return
for i in range(0, len(pcapFiles)):
pcap = pcapFiles[i]
pcapName = os.path.split(pcap)[1]
if not quite:
sys.stdout.write("Reading PCap File: {0}\r".format(pcapName))
sys.stdout.flush()
if not os.path.isfile(pcap):
if not quite:
sys.stdout.write("Skipping File {0}: File Not Found\n".format(pcap))
sys.stdout.flush()
continue
elif not os.access(pcap, os.R_OK):
if not quite:
sys.stdout.write("Skipping File {0}: Permissions Issue\n".format(pcap))
sys.stdout.flush()
continue
pcapr = PcapReader(pcap) # pylint: disable=no-value-for-parameter
packet = pcapr.read_packet()
i = 1
try:
while packet:
if not quite:
sys.stdout.write('Parsing File: ' + pcap + ' Packets Done: ' + str(i) + '\r')
sys.stdout.flush()
self.parse_wireless_packet(packet)
packet = pcapr.read_packet()
i += 1
i -= 1
if not quite:
sys.stdout.write((' ' * len('Parsing File: ' + pcap + ' Packets Done: ' + str(i))) + '\r')
sys.stdout.write('Done With File: ' + pcap + ' Read ' + str(i) + ' Packets\n')
sys.stdout.flush()
except KeyboardInterrupt:
if not quite:
sys.stdout.write("Skipping File {0} Due To Ctl+C\n".format(pcap))
sys.stdout.flush()
except: # pylint: disable=bare-except
if not quite:
sys.stdout.write("Skipping File {0} Due To Scapy Exception\n".format(pcap))
sys.stdout.flush()
self.fragment_buffer = {}
pcapr.close()
开发者ID:jacobj10,项目名称:eapeak,代码行数:52,代码来源:parse.py
示例5: mysniff
def mysniff(self, *arg, **karg):
c = 0
if self.opened_socket is not None:
s = self.opened_socket
else:
if self.offline is None:
if self.L2socket is None:
self.L2socket = conf.L2listen
s = self.L2socket(type=ETH_P_ALL, *arg, **karg)
else:
s = PcapReader(self.offline)
lst = []
if self.timeout is not None:
stoptime = time.time() + self.timeout
remain = None
while 1:
if not self.running:
break
try:
if self.timeout is not None:
remain = stoptime - time.time()
if remain <= 0:
break
sel = select([s], [], [], remain)
if s in sel[0]:
p = s.recv(MTU)
if p is None:
break
if self.lfilter and not self.lfilter(p):
continue
if self.store:
lst.append(p)
c += 1
if self.prn:
r = self.prn(p)
if r is not None:
print r
if self.stop_filter and self.stop_filter(p):
break
if 0 < self.count <= c:
break
except KeyboardInterrupt:
break
if self.opened_socket is None:
s.close()
return plist.PacketList(lst, "Sniffed")
开发者ID:ShaneHarvey,项目名称:wepcracker,代码行数:48,代码来源:sniffingthread.py
示例6: __init__
def __init__(self, iface=None, promisc=None, filter=None, nofilter=False,
prog=None, *arg, **karg):
self.outs = None
args = ['-w', '-', '-s', '65535']
if iface is not None:
if WINDOWS:
try:
args.extend(['-i', iface.pcap_name])
except AttributeError:
args.extend(['-i', iface])
else:
args.extend(['-i', iface])
elif WINDOWS or DARWIN:
args.extend(['-i', conf.iface.pcap_name if WINDOWS else conf.iface]) # noqa: E501
if not promisc:
args.append('-p')
if not nofilter:
if conf.except_filter:
if filter:
filter = "(%s) and not (%s)" % (filter, conf.except_filter)
else:
filter = "not (%s)" % conf.except_filter
if filter is not None:
args.append(filter)
self.tcpdump_proc = tcpdump(None, prog=prog, args=args, getproc=True)
self.ins = PcapReader(self.tcpdump_proc.stdout)
开发者ID:commial,项目名称:scapy,代码行数:26,代码来源:supersocket.py
示例7: USBpcapSocket
class USBpcapSocket(SuperSocket):
"""
Read packets at layer 2 using USBPcapCMD
"""
def __init__(self, iface=None, *args, **karg):
_usbpcap_check()
if iface is None:
warning("Available interfaces: [%s]" %
" ".join(x[0] for x in get_usbpcap_interfaces()))
raise NameError("No interface specified !"
" See get_usbpcap_interfaces()")
self.outs = None
args = ['-d', iface, '-b', '134217728', '-A', '-o', '-']
self.usbpcap_proc = subprocess.Popen(
[conf.prog.usbpcapcmd] + args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
self.ins = PcapReader(self.usbpcap_proc.stdout)
def recv(self, x=MTU):
return self.ins.recv(x)
def close(self):
SuperSocket.close(self)
self.usbpcap_proc.kill()
开发者ID:commial,项目名称:scapy,代码行数:26,代码来源:usb.py
示例8: L2ListenTcpdump
class L2ListenTcpdump(SuperSocket):
desc = "read packets at layer 2 using tcpdump"
def __init__(self, iface=None, promisc=None, filter=None, nofilter=False,
prog=None, *arg, **karg):
self.outs = None
args = ['-w', '-', '-s', '65535']
if iface is not None:
if WINDOWS:
try:
args.extend(['-i', iface.pcap_name])
except AttributeError:
args.extend(['-i', iface])
else:
args.extend(['-i', iface])
elif WINDOWS or DARWIN:
args.extend(['-i', conf.iface.pcap_name if WINDOWS else conf.iface])
if not promisc:
args.append('-p')
if not nofilter:
if conf.except_filter:
if filter:
filter = "(%s) and not (%s)" % (filter, conf.except_filter)
else:
filter = "not (%s)" % conf.except_filter
if filter is not None:
args.append(filter)
self.tcpdump_proc = tcpdump(None, prog=prog, args=args, getproc=True)
self.ins = PcapReader(self.tcpdump_proc.stdout)
def recv(self, x=MTU):
return self.ins.recv(x)
def close(self):
SuperSocket.close(self)
self.tcpdump_proc.kill()
开发者ID:martingalloar,项目名称:scapy,代码行数:34,代码来源:supersocket.py
示例9: wait_for_packet
def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
"""
Wait for next packet captured with a timeout
:param timeout: How long to wait for the packet
:returns: Captured packet if no packet arrived within timeout
:raises Exception: if no packet arrives within timeout
"""
deadline = time.time() + timeout
if self._pcap_reader is None:
if not self.wait_for_capture_file(timeout):
raise CaptureTimeoutError("Capture file %s did not appear "
"within timeout" % self.out_path)
while time.time() < deadline:
try:
self._pcap_reader = PcapReader(self.out_path)
break
except:
self.test.logger.debug(
"Exception in scapy.PcapReader(%s): %s" %
(self.out_path, format_exc()))
if not self._pcap_reader:
raise CaptureTimeoutError("Capture file %s did not appear within "
"timeout" % self.out_path)
poll = False
if timeout > 0:
self.test.logger.debug("Waiting for packet")
else:
poll = True
self.test.logger.debug("Polling for packet")
while time.time() < deadline or poll:
if not self.verify_enough_packet_data_in_pcap():
self._test.sleep(0) # yield
poll = False
continue
p = self._pcap_reader.recv()
if p is not None:
if filter_out_fn is not None and filter_out_fn(p):
self.test.logger.debug(
"Packet received after %ss was filtered out" %
(time.time() - (deadline - timeout)))
else:
self.test.logger.debug(
"Packet received after %fs" %
(time.time() - (deadline - timeout)))
return p
self._test.sleep(0) # yield
poll = False
self.test.logger.debug("Timeout - no packets received")
raise CaptureTimeoutError("Packet didn't arrive within timeout")
开发者ID:chrisy,项目名称:vpp,代码行数:52,代码来源:vpp_pg_interface.py
示例10: __init__
def __init__(self, iface=None, *args, **karg):
_usbpcap_check()
if iface is None:
warning("Available interfaces: [%s]" %
" ".join(x[0] for x in get_usbpcap_interfaces()))
raise NameError("No interface specified !"
" See get_usbpcap_interfaces()")
self.outs = None
args = ['-d', iface, '-b', '134217728', '-A', '-o', '-']
self.usbpcap_proc = subprocess.Popen(
[conf.prog.usbpcapcmd] + args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
self.ins = PcapReader(self.usbpcap_proc.stdout)
开发者ID:commial,项目名称:scapy,代码行数:14,代码来源:usb.py
示例11: __init__
def __init__(self, iface=None, promisc=None, filter=None, nofilter=False,
prog=None, *arg, **karg):
self.outs = None
args = ['-w', '-', '-s', '65535']
if iface is not None:
args.extend(['-i', iface])
if not promisc:
args.append('-p')
if not nofilter:
if conf.except_filter:
if filter:
filter = "(%s) and not (%s)" % (filter, conf.except_filter)
else:
filter = "not (%s)" % conf.except_filter
if filter is not None:
args.append(filter)
self.ins = PcapReader(tcpdump(None, prog=prog, args=args, getfd=True))
开发者ID:thibaultdelmas,项目名称:scapy,代码行数:17,代码来源:supersocket.py
示例12: L2ListenTcpdump
class L2ListenTcpdump(SuperSocket):
desc = "read packets at layer 2 using tcpdump"
def __init__(self, iface=None, promisc=None, filter=None, nofilter=False,
prog=None, *arg, **karg):
self.outs = None
args = ['-w', '-', '-s', '65535']
if iface is not None:
args.extend(['-i', iface])
if not promisc:
args.append('-p')
if not nofilter:
if conf.except_filter:
if filter:
filter = "(%s) and not (%s)" % (filter, conf.except_filter)
else:
filter = "not (%s)" % conf.except_filter
if filter is not None:
args.append(filter)
self.ins = PcapReader(tcpdump(None, prog=prog, args=args, getfd=True))
def recv(self, x=MTU):
return self.ins.recv(x)
开发者ID:thibaultdelmas,项目名称:scapy,代码行数:22,代码来源:supersocket.py
示例13: start
def start(self):
print("start")
self.f = PcapReader(self.fname)
self.is_exhausted = False
开发者ID:commial,项目名称:scapy,代码行数:4,代码来源:scapypipes.py
示例14: __init__
def __init__(self, fname, name=None):
Source.__init__(self, name=name)
self.fname = fname
self.f = PcapReader(self.fname)
开发者ID:commial,项目名称:scapy,代码行数:4,代码来源:scapypipes.py
示例15: VppPGInterface
#.........这里部分代码省略.........
enough_data = False
# read packet header from pcap
packet_header_size = 16
caplen = None
end_pos = None
hdr = self._pcap_reader.f.read(packet_header_size)
if len(hdr) == packet_header_size:
# parse the capture length - caplen
sec, usec, caplen, wirelen = struct.unpack(
self._pcap_reader.endian + "IIII", hdr)
self._pcap_reader.f.seek(0, 2) # seek to end of file
end_pos = self._pcap_reader.f.tell() # get position at end
if end_pos >= orig_pos + len(hdr) + caplen:
enough_data = True # yay, we have enough data
self._pcap_reader.f.seek(orig_pos, 0) # restore original position
return enough_data
def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
"""
Wait for next packet captured with a timeout
:param timeout: How long to wait for the packet
:returns: Captured packet if no packet arrived within timeout
:raises Exception: if no packet arrives within timeout
"""
deadline = time.time() + timeout
if self._pcap_reader is None:
if not self.wait_for_capture_file(timeout):
raise CaptureTimeoutError("Capture file %s did not appear "
"within timeout" % self.out_path)
while time.time() < deadline:
try:
self._pcap_reader = PcapReader(self.out_path)
break
except:
self.test.logger.debug(
"Exception in scapy.PcapReader(%s): %s" %
(self.out_path, format_exc()))
if not self._pcap_reader:
raise CaptureTimeoutError("Capture file %s did not appear within "
"timeout" % self.out_path)
poll = False
if timeout > 0:
self.test.logger.debug("Waiting for packet")
else:
poll = True
self.test.logger.debug("Polling for packet")
while time.time() < deadline or poll:
if not self.verify_enough_packet_data_in_pcap():
self._test.sleep(0) # yield
poll = False
continue
p = self._pcap_reader.recv()
if p is not None:
if filter_out_fn is not None and filter_out_fn(p):
self.test.logger.debug(
"Packet received after %ss was filtered out" %
(time.time() - (deadline - timeout)))
else:
self.test.logger.debug(
"Packet received after %fs" %
(time.time() - (deadline - timeout)))
return p
self._test.sleep(0) # yield
开发者ID:chrisy,项目名称:vpp,代码行数:67,代码来源:vpp_pg_interface.py
注:本文中的scapy.utils.PcapReader类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论