def plot(self, f, lfilter=None, plot_xy=False, **kargs): """Applies a function to each packet to get a value that will be plotted with matplotlib. A list of matplotlib.lines.Line2D is returned. lfilter: a truth function that decides whether a packet must be plotted """ # Python 2 backward compatibility f = lambda_tuple_converter(f) lfilter = lambda_tuple_converter(lfilter) # Get the list of packets if lfilter is None: l = [f(*e) for e in self.res] else: l = [f(*e) for e in self.res if lfilter(*e)] # Mimic the default gnuplot output if kargs == {}: kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS if plot_xy: lines = plt.plot(*zip(*l), **kargs) else: lines = plt.plot(l, **kargs) # Call show() if matplotlib is not inlined if not MATPLOTLIB_INLINED: plt.show() return lines
def plot(self, f, lfilter=None, plot_xy=False, **kargs): """Applies a function to each packet to get a value that will be plotted with matplotlib. A list of matplotlib.lines.Line2D is returned. lfilter: a truth function that decides whether a packet must be plotted """ # Get the list of packets if lfilter is None: l = [f(e) for e in self.res] else: l = [f(e) for e in self.res if lfilter(e)] # Mimic the default gnuplot output if kargs == {}: kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS if plot_xy: lines = plt.plot(*zip(*l), **kargs) else: lines = plt.plot(l, **kargs) # Call show() if matplotlib is not inlined if not MATPLOTLIB_INLINED: plt.show() return lines
def plot(self, f, lfilter=None, plot_xy=False, **kargs): # type: (Callable, Optional[Callable], bool, Any) -> Line2D """Applies a function to each packet to get a value that will be plotted with matplotlib. A list of matplotlib.lines.Line2D is returned. lfilter: a truth function that decides whether a packet must be plotted """ # Python 2 backward compatibility f = lambda_tuple_converter(f) lfilter = lambda_tuple_converter(lfilter) # Get the list of packets if lfilter is None: lst_pkts = [f(*e) for e in self.res] else: lst_pkts = [f(*e) for e in self.res if lfilter(*e)] # Mimic the default gnuplot output if kargs == {}: kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS if plot_xy: lines = plt.plot(*zip(*lst_pkts), **kargs) else: lines = plt.plot(lst_pkts, **kargs) # Call show() if matplotlib is not inlined if not MATPLOTLIB_INLINED: plt.show() return lines
def multiplot(self, f, lfilter=None, plot_xy=False, **kargs): """Uses a function that returns a label and a value for this label, then plots all the values label by label. A list of matplotlib.lines.Line2D is returned. """ # Get the list of packets if lfilter is None: l = (f(e) for e in self.res) else: l = (f(e) for e in self.res if lfilter(e)) # Apply the function f to the packets d = {} for k, v in l: d.setdefault(k, []).append(v) # Mimic the default gnuplot output if not kargs: kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS if plot_xy: lines = [plt.plot(*zip(*pl), **dict(kargs, label=k)) for k, pl in six.iteritems(d)] else: lines = [plt.plot(pl, **dict(kargs, label=k)) for k, pl in six.iteritems(d)] plt.legend(loc="center right", bbox_to_anchor=(1.5, 0.5)) # Call show() if matplotlib is not inlined if not MATPLOTLIB_INLINED: plt.show() return lines
def multiplot(self, f, lfilter=None, plot_xy=False, **kargs): """Uses a function that returns a label and a value for this label, then plots all the values label by label. A list of matplotlib.lines.Line2D is returned. """ # Get the list of packets if lfilter is None: l = (f(e) for e in self.res) else: l = (f(e) for e in self.res if lfilter(e)) # Apply the function f to the packets d = {} for k, v in l: d.setdefault(k, []).append(v) # Mimic the default gnuplot output if not kargs: kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS if plot_xy: lines = [plt.plot(*zip(*pl), **dict(kargs, label=k)) for k, pl in six.iteritems(d)] else: lines = [plt.plot(pl, **dict(kargs, label=k)) for k, pl in six.iteritems(d)] plt.legend(loc="center right", bbox_to_anchor=(1.5, 0.5)) # Call show() if matplotlib is not inlined if not MATPLOTLIB_INLINED: plt.show() return lines
def get_windows_interfaces(): """Returns windows interfaces.""" if not conf.prog.os_access: return [] if is_new_release(): # This works only starting from Windows 8/2012 and up. For older Windows another solution is needed # Careful: this is weird, but Get-NetAdaptater works like: (Name isn't the interface name) # Name InterfaceDescription ifIndex Status MacAddress LinkSpeed # ---- -------------------- ------- ------ ---------- --------- # Ethernet Killer E2200 Gigabit Ethernet Contro... 13 Up D0-50-99-56-DD-F9 1 Gbps query = exec_query(['Get-NetAdapter'], [ 'InterfaceDescription', 'InterfaceIndex', 'Name', 'InterfaceGuid', 'MacAddress', 'InterfaceAlias' ]) # It is normal that it is in this order else: query = exec_query(['Get-WmiObject', 'Win32_NetworkAdapter'], [ 'Name', 'InterfaceIndex', 'InterfaceDescription', 'GUID', 'MacAddress', 'NetConnectionID' ]) x = [ iface for iface in (dict( zip(['name', 'win_index', 'description', 'guid', 'mac', 'netid'], line)) for line in query) if is_interface_valid(iface) ] return x
def _parse(self): def parse_digit(value, netmask): netmask = min(8, max(netmask, 0)) value = int(value) return (value & (0xff << netmask), (value | (0xff >> (8 - netmask))) + 1) self.parsed = [ parse_digit(x, y) for x, y in zip( struct.unpack("16B", in6_and(self.net, self.mask)), (x - self.plen for x in range(8, 129, 8)), ) ]
def _parse(self): def parse_digit(value, netmask): netmask = min(8, max(netmask, 0)) value = int(value) return (value & (0xff << netmask), (value | (0xff >> (8 - netmask))) + 1) self.parsed = [ parse_digit(x, y) for x, y in zip( struct.unpack("16B", in6_and(self.net, self.mask)), (x - self.plen for x in range(8, 129, 8)), ) ]
def multiplot( self, f, # type: Callable[..., Any] lfilter=None, # type: Optional[Callable[..., Any]] plot_xy=False, # type: bool **kargs # type: Any ): # type: (...) -> Line2D """Uses a function that returns a label and a value for this label, then plots all the values label by label. A list of matplotlib.lines.Line2D is returned. """ # Python 2 backward compatibility f = lambda_tuple_converter(f) if lfilter is not None: lfilter = lambda_tuple_converter(lfilter) # Get the list of packets if lfilter is None: lst_pkts = (f(*e) for e in self.res) else: lst_pkts = (f(*e) for e in self.res if lfilter(*e)) # Apply the function f to the packets d = {} # type: Dict[str, List[float]] for k, v in lst_pkts: d.setdefault(k, []).append(v) # Mimic the default gnuplot output if not kargs: kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS if plot_xy: lines = [ plt.plot(*zip(*pl), **dict(kargs, label=k)) for k, pl in six.iteritems(d) ] else: lines = [ plt.plot(pl, **dict(kargs, label=k)) for k, pl in six.iteritems(d) ] plt.legend(loc="center right", bbox_to_anchor=(1.5, 0.5)) # Call show() if matplotlib is not inlined if not MATPLOTLIB_INLINED: plt.show() return lines
def get_windows_if_list(): """Returns windows interfaces.""" if not conf.prog.os_access: return [] if is_new_release(): # This works only starting from Windows 8/2012 and up. For older Windows another solution is needed # Careful: this is weird, but Get-NetAdaptater works like: (Name isn't the interface name) # Name InterfaceDescription ifIndex Status MacAddress LinkSpeed # ---- -------------------- ------- ------ ---------- --------- # Ethernet Killer E2200 Gigabit Ethernet Contro... 13 Up D0-50-99-56-DD-F9 1 Gbps query = exec_query(['Get-NetAdapter'], ['InterfaceDescription', 'InterfaceIndex', 'Name', 'InterfaceGuid', 'MacAddress', 'InterfaceAlias']) # It is normal that it is in this order else: query = exec_query(['Get-WmiObject', 'Win32_NetworkAdapter'], ['Name', 'InterfaceIndex', 'InterfaceDescription', 'GUID', 'MacAddress', 'NetConnectionID']) return [ iface for iface in (dict(zip(['name', 'win_index', 'description', 'guid', 'mac', 'netid'], line)) for line in query) if is_interface_valid(iface) ]
def sndrcv(pks, pkt, timeout = None, inter = 0, verbose=None, chainCC=0, retry=0, multi=0): if not isinstance(pkt, Gen): pkt = SetGen(pkt) if verbose is None: verbose = conf.verb debug.recv = plist.PacketList([],"Unanswered") debug.sent = plist.PacketList([],"Sent") debug.match = plist.SndRcvList([]) nbrecv=0 ans = [] # do it here to fix random fields, so that parent and child have the same all_stimuli = tobesent = [p for p in pkt] notans = len(tobesent) hsent={} for i in tobesent: h = i.hashret() if h in hsent: hsent[h].append(i) else: hsent[h] = [i] if retry < 0: retry = -retry autostop=retry else: autostop=0 while retry >= 0: found=0 if timeout < 0: timeout = None rdpipe,wrpipe = os.pipe() rdpipe=os.fdopen(rdpipe) wrpipe=os.fdopen(wrpipe,"w") pid=1 try: pid = os.fork() if pid == 0: try: sys.stdin.close() rdpipe.close() try: i = 0 if verbose: print("Begin emission:") for p in tobesent: pks.send(p) i += 1 time.sleep(inter) if verbose: print("Finished to send %i packets." % i) except SystemExit: pass except KeyboardInterrupt: pass except: log_runtime.exception("--- Error in child %i" % os.getpid()) log_runtime.info("--- Error in child %i" % os.getpid()) finally: try: os.setpgrp() # Chance process group to avoid ctrl-C sent_times = [p.sent_time for p in all_stimuli if p.sent_time] six.moves.cPickle.dump( (conf.netcache,sent_times), wrpipe ) wrpipe.close() except: pass elif pid < 0: log_runtime.error("fork error") else: wrpipe.close() stoptime = 0 remaintime = None inmask = [rdpipe,pks] try: try: while True: if stoptime: remaintime = stoptime-time.time() if remaintime <= 0: break r = None if conf.use_bpf: from scapy.arch.bpf.supersocket import bpf_select inp = bpf_select(inmask) if pks in inp: r = pks.recv() elif not isinstance(pks, StreamSocket) and (FREEBSD or DARWIN or OPENBSD): inp, out, err = select(inmask,[],[], 0.05) if len(inp) == 0 or pks in inp: r = pks.nonblock_recv() else: inp = [] try: inp, out, err = select(inmask,[],[], remaintime) except (IOError, select_error) as exc: # select.error has no .errno attribute if exc.args[0] != errno.EINTR: raise if len(inp) == 0: break if pks in inp: r = pks.recv(MTU) if rdpipe in inp: if timeout: stoptime = time.time()+timeout del(inmask[inmask.index(rdpipe)]) if r is None: continue ok = 0 h = r.hashret() if h in hsent: hlst = hsent[h] for i, sentpkt in enumerate(hlst): if r.answers(sentpkt): ans.append((sentpkt, r)) if verbose > 1: os.write(1, "*") ok = 1 if not multi: del hlst[i] notans -= 1 else: if not hasattr(sentpkt, '_answered'): notans -= 1 sentpkt._answered = 1 break if notans == 0 and not multi: break if not ok: if verbose > 1: os.write(1, ".") nbrecv += 1 if conf.debug_match: debug.recv.append(r) except KeyboardInterrupt: if chainCC: raise finally: try: nc,sent_times = six.moves.cPickle.load(rdpipe) except EOFError: warning("Child died unexpectedly. Packets may have not been sent %i"%os.getpid()) else: conf.netcache.update(nc) for p,t in zip(all_stimuli, sent_times): p.sent_time = t os.waitpid(pid,0) finally: if pid == 0: os._exit(0) remain = list(itertools.chain(*six.itervalues(hsent))) if multi: remain = [p for p in remain if not hasattr(p, '_answered')] if autostop and len(remain) > 0 and len(remain) != len(tobesent): retry = autostop tobesent = remain if len(tobesent) == 0: break retry -= 1 if conf.debug_match: debug.sent=plist.PacketList(remain[:],"Sent") debug.match=plist.SndRcvList(ans[:]) #clean the ans list to delete the field _answered if (multi): for s,r in ans: if hasattr(s, '_answered'): del(s._answered) if verbose: print("\nReceived %i packets, got %i answers, remaining %i packets" % (nbrecv+len(ans), len(ans), notans)) return plist.SndRcvList(ans),plist.PacketList(remain,"Unanswered")