本文整理汇总了Python中scapy.error.log_loading.warning函数的典型用法代码示例。如果您正苦于以下问题:Python warning函数的具体用法?Python warning怎么用?Python warning使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了warning函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _read_config_file
def _read_config_file(cf, _globals=globals(), _locals=locals(), interactive=True):
"""Read a config file: execute a python file while loading scapy, that may contain
some pre-configured values.
If _globals or _locals are specified, they will be updated with the loaded vars.
This allows an external program to use the function. Otherwise, vars are only available
from inside the scapy console.
params:
- _globals: the globals() vars
- _locals: the locals() vars
- interactive: specified whether or not errors should be printed using the scapy console or
raised.
ex, content of a config.py file:
'conf.verb = 42\n'
Manual loading:
>>> _read_config_file("./config.py"))
>>> conf.verb
42
"""
log_loading.debug("Loading config file [%s]", cf)
try:
exec(compile(open(cf).read(), cf, 'exec'), _globals, _locals)
except IOError as e:
if interactive:
raise
log_loading.warning("Cannot read config file [%s] [%s]", cf, e)
except Exception as e:
if interactive:
raise
log_loading.exception("Error during evaluation of config file [%s]", cf)
示例2: _reload
def _reload(self):
self.pdfreader = None
self.psreader = None
# We try some magic to find the appropriate executables
self.dot = win_find_exe("dot")
self.tcpdump = win_find_exe("windump")
self.tshark = win_find_exe("tshark")
self.tcpreplay = win_find_exe("tcpreplay")
self.display = self._default
self.hexedit = win_find_exe("hexer")
self.sox = win_find_exe("sox")
self.wireshark = win_find_exe("wireshark", "wireshark")
self.powershell = win_find_exe(
"powershell",
installsubdir="System32\\WindowsPowerShell\\v1.0",
env="SystemRoot"
)
self.cscript = win_find_exe("cscript", installsubdir="System32",
env="SystemRoot")
self.cmd = win_find_exe("cmd", installsubdir="System32",
env="SystemRoot")
if self.wireshark:
try:
manu_path = load_manuf(os.path.sep.join(self.wireshark.split(os.path.sep)[:-1]) + os.path.sep + "manuf") # noqa: E501
except (IOError, OSError): # FileNotFoundError not available on Py2 - using OSError # noqa: E501
log_loading.warning("Wireshark is installed, but cannot read manuf !") # noqa: E501
manu_path = None
scapy.data.MANUFDB = conf.manufdb = manu_path
self.os_access = (self.powershell is not None) or (self.cscript is not None) # noqa: E501
示例3: load_services
def load_services(filename):
spaces = re.compile(b"[ \t]+|\n")
tdct = DADict(_name="%s-tcp" % filename)
udct = DADict(_name="%s-udp" % filename)
try:
with open(filename, "rb") as fdesc:
for line in fdesc:
try:
shrp = line.find(b"#")
if shrp >= 0:
line = line[:shrp]
line = line.strip()
if not line:
continue
lt = tuple(re.split(spaces, line))
if len(lt) < 2 or not lt[0]:
continue
if lt[1].endswith(b"/tcp"):
tdct[lt[0]] = int(lt[1].split(b'/')[0])
elif lt[1].endswith(b"/udp"):
udct[lt[0]] = int(lt[1].split(b'/')[0])
except Exception as e:
log_loading.warning(
"Couldn't parse file [%s]: line [%r] (%s)",
filename,
line,
e,
)
except IOError:
log_loading.info("Can't open /etc/services file")
return tdct, udct
示例4: load_services
def load_services(filename):
spaces = re.compile("[ \t]+|\n")
tdct=DADict(_name="%s-tcp"%filename)
udct=DADict(_name="%s-udp"%filename)
try:
f=open(filename)
for l in f:
try:
shrp = l.find("#")
if shrp >= 0:
l = l[:shrp]
l = l.strip()
if not l:
continue
lt = tuple(re.split(spaces, l))
if len(lt) < 2 or not lt[0]:
continue
if lt[1].endswith("/tcp"):
tdct[lt[0]] = int(lt[1].split('/')[0])
elif lt[1].endswith("/udp"):
udct[lt[0]] = int(lt[1].split('/')[0])
except Exception as e:
log_loading.warning("Couldn't file [%s]: line [%r] (%s)" % (filename,l,e))
f.close()
except IOError:
log_loading.info("Can't open /etc/services file")
return tdct,udct
示例5: apply_ipython_style
def apply_ipython_style(shell):
"""Updates the specified IPython console shell with
the conf.color_theme scapy theme."""
try:
from IPython.terminal.prompts import Prompts, Token
except Exception:
from scapy.error import log_loading
log_loading.warning(
"IPython too old. Shell color won't be handled."
)
return
from scapy.config import conf
if isinstance(conf.prompt, Prompts):
shell.prompts_class = conf.prompt # Set custom prompt style
else:
class ClassicPrompt(Prompts):
def in_prompt_tokens(self, cli=None):
return [(Token.Prompt, str(conf.prompt)), ]
def out_prompt_tokens(self):
return [(Token.OutPrompt, ''), ]
shell.prompts_class = ClassicPrompt # Apply classic prompt style
shell.highlighting_style_overrides = { # Register and apply scapy color style # noqa: E501
Token.Prompt: Color.ansi_to_pygments(conf.color_theme.style_prompt),
}
try:
get_ipython().refresh_style()
except NameError:
pass
示例6: _update_pcapdata
def _update_pcapdata(self):
"""Supplement more info from pypcap and the Windows registry"""
# XXX: We try eth0 - eth29 by bruteforce and match by IP address,
# because only the IP is available in both pypcap and dnet.
# This may not work with unorthodox network configurations and is
# slow because we have to walk through the Windows registry.
for n in range(30): # change 30 to 15
guess = "eth%s" % n
win_name = pcapdnet.pcap.ex_name(guess)
if win_name.endswith("}"):
try:
uuid = win_name[win_name.index("{"):win_name.index("}")+1]
keyname = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % uuid
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname)
except WindowsError:
log_loading.debug("Couldn't open 'HKEY_LOCAL_MACHINE\\%s' (for guessed pcap iface name '%s')." % (keyname, guess))
continue
try:
ip_list = _winreg.QueryValueEx(key, "IPAddress")[0]
ip_list = [ ipx.encode("utf-8") for ipx in ip_list ]
fixed_ip = _winreg.QueryValueEx(key, "IPAddress")[0][0].encode("utf-8")
except (WindowsError, UnicodeDecodeError, IndexError):
log_loading.debug("Query ip address of %s error " % (guess,) )
fixed_ip = None
ip_list = []
try:
dhcp_ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0].encode("utf-8")
except (WindowsError, UnicodeDecodeError, IndexError):
dhcp_ip = None
# "0.0.0.0" or None means the value is not set (at least not correctly).
# If both fixed_ip and dhcp_ip are set, fixed_ip takes precedence
if fixed_ip is not None and fixed_ip != "0.0.0.0":
ip = fixed_ip
elif dhcp_ip is not None and dhcp_ip != "0.0.0.0":
ip = dhcp_ip
ip_list = [dhcp_ip]
else:
log_loading.debug('continue ...')
continue
except IOError:
log_loading.warning("IOError")
continue
else:
if ip == self.ip or self.ip in ip_list:
self.pcap_name = guess
self.win_name = win_name
self.uuid = uuid
self.ip_list = ip_list
break
else:
raise PcapNameNotFoundError
示例7: load_from_powershell
def load_from_powershell(self):
for i in get_windows_if_list():
try:
interface = NetworkInterface(i)
self.data[interface.name] = interface
except (KeyError, PcapNameNotFoundError):
pass
if len(self.data) == 0:
log_loading.warning("No match between your pcap and windows network interfaces found. "
"You probably won't be able to send packets. "
"Deactivating unneeded interfaces and restarting Scapy might help."
"Check your winpcap and powershell installation, and access rights.")
示例8: __new__
def __new__(cls, name, bases, dct):
from scapy.error import log_loading
import traceback
try:
for tb in traceback.extract_stack()+[("??",-1,None,"")]:
f,l,_,line = tb
if line.startswith("class"):
break
except:
f,l="??",-1
raise
log_loading.warning("Deprecated (no more needed) use of NewDefaultValues (%s l. %i).", f, l)
return super(NewDefaultValues, cls).__new__(cls, name, bases, dct)
示例9: read_routes
def read_routes():
routes = []
release = platform.release()
try:
if release in ["post2008Server", "8"]:
routes = read_routes_post2008()
elif release == "XP":
routes = read_routes_xp()
else:
routes = read_routes_7()
except Exception as e:
log_loading.warning("Error building scapy routing table : %s"%str(e))
else:
if not routes:
log_loading.warning("No default IPv4 routes found. Your Windows release may no be supported and you have to enter your routes manually")
return routes
示例10: load_from_dnet
def load_from_dnet(self):
"""Populate interface table via dnet"""
for i in pcapdnet.dnet.intf():
try:
# XXX: Only Ethernet for the moment: localhost is not supported by dnet and pcap
# We only take interfaces that have an IP address, because the IP
# is used for the mapping between dnet and pcap interface names
# and this significantly improves Scapy's startup performance
if i["name"].startswith("eth") and "addr" in i:
self.data[i["name"]] = NetworkInterface(i)
except (KeyError, PcapNameNotFoundError):
pass
if len(self.data) == 0:
log_loading.warning("No match between your pcap and dnet network interfaces found. "
"You probably won't be able to send packets. "
"Deactivating unneeded interfaces and restarting Scapy might help.")
示例11: read_routes
def read_routes():
ok = 0
routes = []
ip = "(\d+\.\d+\.\d+\.\d+)"
# On Vista and Windows 7 the gateway can be IP or 'On-link'.
# But the exact 'On-link' string depends on the locale, so we allow any text.
gw_pattern = "(.+)"
metric_pattern = "(\d+)"
delim = "\s+" # The columns are separated by whitespace
netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern])
pattern = re.compile(netstat_line)
f = os.popen("netstat -rn")
for l in f.readlines():
match = re.search(pattern, l)
if match:
dest = match.group(1)
mask = match.group(2)
gw = match.group(3)
netif = match.group(4)
metric = match.group(5)
try:
intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
except OSError:
log_loading.warning(
"Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest
)
continue
if not intf.has_key("addr"):
break
addr = str(intf["addr"])
addr = addr.split("/")[0]
dest = atol(dest)
mask = atol(mask)
# If the gateway is no IP we assume it's on-link
gw_ipmatch = re.search("\d+\.\d+\.\d+\.\d+", gw)
if gw_ipmatch:
gw = gw_ipmatch.group(0)
else:
gw = netif
routes.append((dest, mask, gw, str(intf["name"]), addr))
f.close()
return routes
示例12: load_manuf
def load_manuf(filename):
manufdb = ManufDA(_name=filename)
with open(filename, "rb") as fdesc:
for line in fdesc:
try:
line = line.strip()
if not line or line.startswith(b"#"):
continue
oui, shrt = line.split()[:2]
i = line.find(b"#")
if i < 0:
lng = shrt
else:
lng = line[i + 2:]
manufdb[oui] = plain_str(shrt), plain_str(lng)
except Exception:
log_loading.warning("Couldn't parse one line from [%s] [%r]",
filename, line, exc_info=True)
return manufdb
示例13: load_manuf
def load_manuf(filename):
"""Load manuf file from Wireshark.
param:
- filename: the file to load the manuf file from"""
manufdb = ManufDA(_name=filename)
with open(filename, "rb") as fdesc:
for line in fdesc:
try:
line = line.strip()
if not line or line.startswith(b"#"):
continue
parts = line.split(None, 2)
oui, shrt = parts[:2]
lng = parts[2].lstrip(b"#").strip() if len(parts) > 2 else ""
lng = lng or shrt
manufdb[oui] = plain_str(shrt), plain_str(lng)
except Exception:
log_loading.warning("Couldn't parse one line from [%s] [%r]",
filename, line, exc_info=True)
return manufdb
示例14: load_manuf
def load_manuf(filename):
try:
manufdb=ManufDA(_name=filename)
for l in open(filename):
try:
l = l.strip()
if not l or l.startswith("#"):
continue
oui,shrt=l.split()[:2]
i = l.find("#")
if i < 0:
lng=shrt
else:
lng = l[i+2:]
manufdb[oui] = shrt,lng
except Exception,e:
log_loading.warning("Couldn't parse one line from [%s] [%r] (%s)" % (filename, l, e))
except IOError:
#log_loading.warning("Couldn't open [%s] file" % filename)
pass
return manufdb
示例15: get_if_raw_hwaddr
# From if_packet.h
PACKET_HOST = 0 # To us
PACKET_BROADCAST = 1 # To all
PACKET_MULTICAST = 2 # To group
PACKET_OTHERHOST = 3 # To someone else
PACKET_OUTGOING = 4 # Outgoing of any type
PACKET_LOOPBACK = 5 # MC/BRD frame looped back
PACKET_USER = 6 # To user space
PACKET_KERNEL = 7 # To kernel space
PACKET_FASTROUTE = 6 # Fastrouted frame
# Unused, PACKET_FASTROUTE and PACKET_LOOPBACK are invisible to user space
with os.popen("%s -V 2> /dev/null" % conf.prog.tcpdump) as _f:
if _f.close() >> 8 == 0x7f:
log_loading.warning("Failed to execute tcpdump. Check it is installed and in the PATH") # noqa: E501
TCPDUMP = 0
else:
TCPDUMP = 1
del(_f)
def get_if_raw_hwaddr(iff):
return struct.unpack("16xh6s8x", get_if(iff, SIOCGIFHWADDR))
def get_if_raw_addr(iff):
try:
return get_if(iff, SIOCGIFADDR)[20:24]
except IOError:
return b"\0\0\0\0"