本文整理汇总了Python中scapy.modules.six.iteritems函数的典型用法代码示例。如果您正苦于以下问题:Python iteritems函数的具体用法?Python iteritems怎么用?Python iteritems使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iteritems函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: load_mib
def load_mib(filenames):
the_mib = {'iso': ['1']}
unresolved = {}
for k in six.iterkeys(conf.mib):
mib_register(k, conf.mib[k].split("."), the_mib, unresolved)
if isinstance(filenames, (str, bytes)):
filenames = [filenames]
for fnames in filenames:
for fname in glob(fnames):
f = open(fname)
text = f.read()
cleantext = " ".join(_mib_re_strings.split(" ".join(_mib_re_comments.split(text))))
for m in _mib_re_oiddecl.finditer(cleantext):
gr = m.groups()
ident,oid = gr[0],gr[-1]
ident=fixname(ident)
oid = oid.split()
for i, elt in enumerate(oid):
m = _mib_re_both.match(elt)
if m:
oid[i] = m.groups()[1]
mib_register(ident, oid, the_mib, unresolved)
newmib = MIBDict(_name="MIB")
for k,o in six.iteritems(the_mib):
newmib[k]=".".join(o)
for k,o in six.iteritems(unresolved):
newmib[k]=".".join(o)
conf.mib=newmib
开发者ID:6WIND,项目名称:scapy,代码行数:31,代码来源:mib.py
示例2: multiplot
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
开发者ID:6WIND,项目名称:scapy,代码行数:35,代码来源:plist.py
示例3: __repr__
def __repr__(self):
lst = []
for num,layer in six.iteritems(self.num2layer):
if layer in self.layer2num and self.layer2num[layer] == num:
dir = "<->"
else:
dir = " ->"
lst.append((num,"%#6x %s %-20s (%s)" % (num, dir, layer.__name__,
layer._name)))
for layer,num in six.iteritems(self.layer2num):
if num not in self.num2layer or self.num2layer[num] != layer:
lst.append((num,"%#6x <- %-20s (%s)" % (num, layer.__name__,
layer._name)))
lst.sort()
return "\n".join(y for x,y in lst)
开发者ID:mcpat,项目名称:scapy,代码行数:15,代码来源:config.py
示例4: self_build
def self_build(self, field_pos_list=None):
""" Implements the swap-bytes functionality when building
this is based on a copy of the Packet.self_build default method.
The goal is to affect only the CAN layer data and keep
under layers (e.g LinuxCooked) unchanged
"""
if self.raw_packet_cache is not None:
for fname, fval in six.iteritems(self.raw_packet_cache_fields):
if self.getfieldval(fname) != fval:
self.raw_packet_cache = None
self.raw_packet_cache_fields = None
break
if self.raw_packet_cache is not None:
if conf.contribs['CAN']['swap-bytes']:
return CAN.inv_endianness(self.raw_packet_cache)
return self.raw_packet_cache
p = b""
for f in self.fields_desc:
val = self.getfieldval(f.name)
if isinstance(val, RawVal):
sval = raw(val)
p += sval
if field_pos_list is not None:
field_pos_list.append((f.name,
sval.encode('string_escape'),
len(p), len(sval)))
else:
p = f.addfield(self, p, val)
if conf.contribs['CAN']['swap-bytes']:
return CAN.inv_endianness(p)
return p
开发者ID:netkey,项目名称:scapy,代码行数:32,代码来源:can.py
示例5: _load
def _load(module, globals_dict=None, symb_list=None):
"""Loads a Python module to make variables, objects and functions
available globally.
The idea is to load the module using importlib, then copy the
symbols to the global symbol table.
"""
if globals_dict is None:
globals_dict = six.moves.builtins.__dict__
try:
mod = importlib.import_module(module)
if '__all__' in mod.__dict__:
# import listed symbols
for name in mod.__dict__['__all__']:
if symb_list is not None:
symb_list.append(name)
globals_dict[name] = mod.__dict__[name]
else:
# only import non-private symbols
for name, sym in six.iteritems(mod.__dict__):
if _validate_local(name):
if symb_list is not None:
symb_list.append(name)
globals_dict[name] = sym
except Exception:
log_interactive.error("Loading module %s", module, exc_info=True)
开发者ID:6WIND,项目名称:scapy,代码行数:27,代码来源:main.py
示例6: __init__
def __init__(self, name, default, *args, **kwargs):
if "implicit_tag" in kwargs:
err_msg = "ASN1F_CHOICE has been called with an implicit_tag"
raise ASN1_Error(err_msg)
self.implicit_tag = None
for kwarg in ["context", "explicit_tag"]:
setattr(self, kwarg, kwargs.get(kwarg))
ASN1F_field.__init__(self, name, None, context=self.context,
explicit_tag=self.explicit_tag)
self.default = default
self.current_choice = None
self.choices = {}
self.pktchoices = {}
for p in args:
if hasattr(p, "ASN1_root"): # should be ASN1_Packet
if hasattr(p.ASN1_root, "choices"):
for k, v in six.iteritems(p.ASN1_root.choices):
self.choices[k] = v # ASN1F_CHOICE recursion
else:
self.choices[p.ASN1_root.network_tag] = p
elif hasattr(p, "ASN1_tag"):
if isinstance(p, type): # should be ASN1F_field class
self.choices[p.ASN1_tag] = p
else: # should be ASN1F_PACKET instance
self.choices[p.network_tag] = p
self.pktchoices[hash(p.cls)] = (p.implicit_tag, p.explicit_tag) # noqa: E501
else:
raise ASN1_Error("ASN1F_CHOICE: no tag found for one field")
开发者ID:commial,项目名称:scapy,代码行数:28,代码来源:asn1fields.py
示例7: get_data
def get_data(self):
"""Returns a dictionary object, keys are strings "source >
destincation [content type]", and values are the content
fetched, also as a string.
"""
return {key: "".join(chr(byte) for byte in data)
for key, data in six.iteritems(self.data)}
开发者ID:6WIND,项目名称:scapy,代码行数:8,代码来源:lltd.py
示例8: dst_from_pkt
def dst_from_pkt(self, pkt):
for addr, condition in self.bindings.get(pkt.payload.__class__, []):
try:
if all(pkt.payload.getfieldval(field) == value
for field, value in six.iteritems(condition)):
return addr
except AttributeError:
pass
return self.defaultdst
开发者ID:martingalloar,项目名称:scapy,代码行数:9,代码来源:fields.py
示例9: __new__
def __new__(cls, name, bases, dct):
rdict={}
for k,v in six.iteritems(dct):
if isinstance(v, int):
v = cls.element_class(k,v)
dct[k] = v
rdict[v] = k
dct["__rdict__"] = rdict
return super(Enum_metaclass, cls).__new__(cls, name, bases, dct)
开发者ID:mcpat,项目名称:scapy,代码行数:9,代码来源:utils.py
示例10: dev_from_index
def dev_from_index(self, if_index):
"""Return interface name from interface index"""
for devname, iface in six.iteritems(self):
if iface.win_index == str(if_index):
return iface
if str(if_index) == "1":
# Test if the loopback interface is set up
if isinstance(scapy.consts.LOOPBACK_INTERFACE, NetworkInterface):
return scapy.consts.LOOPBACK_INTERFACE
raise ValueError("Unknown network interface index %r" % if_index)
开发者ID:dark-lbp,项目名称:scapy,代码行数:10,代码来源:__init__.py
示例11: _oid
def _oid(self, x):
"""Parse the OID id/OID generator, and return real OID"""
xl = x.strip(".").split(".")
p = len(xl) - 1
while p >= 0 and _mib_re_integer.match(xl[p]):
p -= 1
if p != 0 or xl[p] not in self.__dict__.values():
return x
xl[p] = next(k for k, v in six.iteritems(self.__dict__) if v == xl[p])
return ".".join(xl[p:])
开发者ID:commial,项目名称:scapy,代码行数:10,代码来源:mib.py
示例12: __init__
def __init__(self, name, default, enum, depends_on, fmt = "H"):
self.depends_on = depends_on
self.i2s_multi = enum
self.s2i_multi = {}
self.s2i_all = {}
for m in enum:
self.s2i_multi[m] = s2i = {}
for k,v in six.iteritems(enum[m]):
s2i[v] = k
self.s2i_all[v] = k
Field.__init__(self, name, default, fmt)
开发者ID:martingalloar,项目名称:scapy,代码行数:12,代码来源:fields.py
示例13: __new__
def __new__(cls, name, bases, dct): # XXX factorise a bit with Enum_metaclass.__new__() # noqa: E501
for b in bases:
for k, v in six.iteritems(b.__dict__):
if k not in dct and isinstance(v, ASN1Tag):
dct[k] = v.clone()
rdict = {}
for k, v in six.iteritems(dct):
if isinstance(v, int):
v = ASN1Tag(k, v)
dct[k] = v
rdict[v] = v
elif isinstance(v, ASN1Tag):
rdict[v] = v
dct["__rdict__"] = rdict
cls = type.__new__(cls, name, bases, dct)
for v in cls.__dict__.values():
if isinstance(v, ASN1Tag):
v.context = cls # overwrite ASN1Tag contexts, even cloned ones
return cls
开发者ID:plorinquer,项目名称:scapy,代码行数:21,代码来源:asn1.py
示例14: nmap_search
def nmap_search(sigs):
guess = 0, []
for osval, fprint in nmap_kdb.get_base():
score = 0.0
for test, values in six.iteritems(fprint):
if test in sigs:
score += nmap_match_one_sig(sigs[test], values)
score /= len(sigs)
if score > guess[0]:
guess = score, [osval]
elif score == guess[0]:
guess[1].append(osval)
return guess
开发者ID:plorinquer,项目名称:scapy,代码行数:13,代码来源:nmap.py
示例15: _import_star
def _import_star(m):
mod = importlib.import_module("." + m, "scapy.layers")
if '__all__' in mod.__dict__:
# only import the exported symbols in __all__
for name in mod.__dict__['__all__']:
__all__.append(name)
globals()[name] = mod.__dict__[name]
else:
# import all the non-private symbols
for name, sym in six.iteritems(mod.__dict__):
if _validate_local(name):
__all__.append(name)
globals()[name] = sym
开发者ID:mcpat,项目名称:scapy,代码行数:13,代码来源:all.py
示例16: reverse_lookup
def reverse_lookup(self, name, case_sensitive=False):
"""Find all MACs registered to a OUI
params:
- name: the OUI name
- case_sensitive: default to False
returns: a dict of mac:tuples (Name, Extended Name)
"""
if case_sensitive:
filtr = lambda x, l: any(x == z for z in l)
else:
name = name.lower()
filtr = lambda x, l: any(x == z.lower() for z in l)
return {k: v for k, v in six.iteritems(self.__dict__)
if filtr(name, v)}
开发者ID:commial,项目名称:scapy,代码行数:14,代码来源:data.py
示例17: i2m
def i2m(self, pkt, x):
v = self.depends_on(pkt)
if v in self.names:
these_names = self.names[v]
else:
these_names = {}
r = 0
for flag_set in x:
for i, val in six.iteritems(these_names):
if val.short == flag_set:
r |= 1 << i
break
else:
r |= 1 << int(flag_set[len('bit '):])
return r
开发者ID:martingalloar,项目名称:scapy,代码行数:16,代码来源:fields.py
示例18: fill_missing
def fill_missing(self):
"""
We do not want TLSServerKeyExchange.build() to overload and recompute
things everytime it is called. This method can be called specifically
to have things filled in a smart fashion.
XXX We should account for the point_format (before 'point' filling).
"""
s = self.tls_session
if self.curve_type is None:
self.curve_type = _tls_ec_curve_types["named_curve"]
if self.named_curve is None:
curve = ec.SECP256R1()
s.server_kx_privkey = ec.generate_private_key(curve,
default_backend())
curve_id = 0
for cid, name in six.iteritems(_tls_named_curves):
if name == curve.name:
curve_id = cid
break
self.named_curve = curve_id
else:
curve_name = _tls_named_curves.get(self.named_curve)
if curve_name is None:
# this fallback is arguable
curve = ec.SECP256R1()
else:
curve_cls = ec._CURVE_TYPES.get(curve_name)
if curve_cls is None:
# this fallback is arguable
curve = ec.SECP256R1()
else:
curve = curve_cls()
s.server_kx_privkey = ec.generate_private_key(curve,
default_backend())
if self.point is None:
pubkey = s.server_kx_privkey.public_key()
self.point = pubkey.public_numbers().encode_point()
# else, we assume that the user wrote the server_kx_privkey by himself
if self.pointlen is None:
self.pointlen = len(self.point)
if not s.client_kx_ecdh_params:
s.client_kx_ecdh_params = curve
开发者ID:6WIND,项目名称:scapy,代码行数:47,代码来源:keyexchange.py
示例19: init_session
def init_session(session_name, mydict=None):
global SESSION
global GLOBKEYS
scapy_builtins = {k: v for k, v in six.iteritems(importlib.import_module(".all", "scapy").__dict__) if _validate_local(k)} # noqa: E501
six.moves.builtins.__dict__.update(scapy_builtins)
GLOBKEYS.extend(scapy_builtins)
GLOBKEYS.append("scapy_session")
scapy_builtins = None # XXX replace with "with" statement
if session_name:
try:
os.stat(session_name)
except OSError:
log_loading.info("New session [%s]" % session_name)
else:
try:
try:
SESSION = six.moves.cPickle.load(gzip.open(session_name, "rb")) # noqa: E501
except IOError:
SESSION = six.moves.cPickle.load(open(session_name, "rb"))
log_loading.info("Using session [%s]" % session_name)
except EOFError:
log_loading.error("Error opening session [%s]" % session_name)
except AttributeError:
log_loading.error("Error opening session [%s]. Attribute missing" % session_name) # noqa: E501
if SESSION:
if "conf" in SESSION:
conf.configure(SESSION["conf"])
conf.session = session_name
SESSION["conf"] = conf
else:
conf.session = session_name
else:
conf.session = session_name
SESSION = {"conf": conf}
else:
SESSION = {"conf": conf}
six.moves.builtins.__dict__["scapy_session"] = SESSION
if mydict is not None:
six.moves.builtins.__dict__["scapy_session"].update(mydict)
update_ipython_session(mydict)
GLOBKEYS.extend(mydict)
开发者ID:segment-routing,项目名称:scapy,代码行数:46,代码来源:main.py
示例20: conversations
def conversations(self, getsrcdst=None, **kargs):
"""Graphes a conversations between sources and destinations and display it
(using graphviz and imagemagick)
getsrcdst: a function that takes an element of the list and
returns the source, the destination and optionally
a label. By default, returns the IP source and
destination from IP and ARP layers
type: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option # noqa: E501
target: filename or redirect. Defaults pipe to Imagemagick's display program # noqa: E501
prog: which graphviz program to use"""
if getsrcdst is None:
def getsrcdst(pkt):
"""Extract src and dst addresses"""
if 'IP' in pkt:
return (pkt['IP'].src, pkt['IP'].dst)
if 'IPv6' in pkt:
return (pkt['IPv6'].src, pkt['IPv6'].dst)
if 'ARP' in pkt:
return (pkt['ARP'].psrc, pkt['ARP'].pdst)
raise TypeError()
conv = {}
for p in self.res:
p = self._elt2pkt(p)
try:
c = getsrcdst(p)
except:
# No warning here: it's OK that getsrcdst() raises an
# exception, since it might be, for example, a
# function that expects a specific layer in each
# packet. The try/except approach is faster and
# considered more Pythonic than adding tests.
continue
if len(c) == 3:
conv.setdefault(c[:2], set()).add(c[2])
else:
conv[c] = conv.get(c, 0) + 1
gr = 'digraph "conv" {\n'
for (s, d), l in six.iteritems(conv):
gr += '\t "%s" -> "%s" [label="%s"]\n' % (
s, d, ', '.join(str(x) for x in l) if isinstance(l, set) else l
)
gr += "}\n"
return do_graph(gr, **kargs)
开发者ID:plorinquer,项目名称:scapy,代码行数:43,代码来源:plist.py
注:本文中的scapy.modules.six.iteritems函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论