本文整理汇总了Python中scapy.error.log_loading.warning函数的典型用法代码示例。如果您正苦于以下问题:Python warning函数的具体用法?Python warning怎么用?Python warning使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了warning函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:6WIND,项目名称:scapy,代码行数:32,代码来源:main.py
示例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
开发者ID:plorinquer,项目名称:scapy,代码行数:30,代码来源:__init__.py
示例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
开发者ID:netkey,项目名称:scapy,代码行数:31,代码来源:data.py
示例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
开发者ID:thibaultdelmas,项目名称:scapy,代码行数:27,代码来源:data.py
示例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
开发者ID:commial,项目名称:scapy,代码行数:29,代码来源:themes.py
示例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
开发者ID:ogreworld,项目名称:ScapyExtension,代码行数:57,代码来源:__init__.py
示例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.")
开发者ID:ouje,项目名称:scapy,代码行数:12,代码来源:__init__.py
示例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)
开发者ID:6WIND,项目名称:scapy,代码行数:14,代码来源:base_classes.py
示例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
开发者ID:secdev,项目名称:scapy,代码行数:16,代码来源:__init__.py
示例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.")
开发者ID:0x0d,项目名称:hijack,代码行数:16,代码来源:__init__.py
示例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
开发者ID:0x0mar,项目名称:zarp,代码行数:43,代码来源:__init__.py
示例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
开发者ID:segment-routing,项目名称:scapy,代码行数:19,代码来源:data.py
示例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
开发者ID:commial,项目名称:scapy,代码行数:20,代码来源:data.py
示例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
开发者ID:guedou,项目名称:scapy-issues,代码行数:21,代码来源:data.py
示例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"
开发者ID:plorinquer,项目名称:scapy,代码行数:31,代码来源:linux.py
示例16: pcap_lib_version
# Detect Pcap version
version = pcap_lib_version()
if "winpcap" in version.lower():
if os.path.exists(os.environ["WINDIR"] + "\\System32\\Npcap\\wpcap.dll"):
warning("Winpcap is installed over Npcap. Will use Winpcap (see 'Winpcap/Npcap conflicts' in scapy's docs)", True)
elif platform.release() != "XP":
warning("WinPcap is now deprecated (not maintened). Please use Npcap instead", True)
elif "npcap" in version.lower():
conf.use_npcap = True
LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter"
except OSError as e:
def winpcapy_get_if_list():
return []
conf.use_winpcapy = False
if conf.interactive:
log_loading.warning("wpcap.dll is not installed. You won't be able to send/recieve packets. Visit the scapy's doc to install it")
# From BSD net/bpf.h
#BIOCIMMEDIATE=0x80044270
BIOCIMMEDIATE=-2147204496
class PcapTimeoutElapsed(Scapy_Exception):
pass
def get_if_raw_hwaddr(iff):
err = create_string_buffer(PCAP_ERRBUF_SIZE)
devs = POINTER(pcap_if_t)()
ret = b"\0\0\0\0\0\0"
if pcap_findalldevs(byref(devs), err) < 0:
return ret
开发者ID:thibaultdelmas,项目名称:scapy,代码行数:31,代码来源:pcapdnet.py
示例17: warning
if b"winpcap" in version.lower():
if os.path.exists(NPCAP_PATH + "\\wpcap.dll"):
warning("Winpcap is installed over Npcap. "
"Will use Winpcap (see 'Winpcap/Npcap conflicts' "
"in Scapy's docs)")
elif platform.release() != "XP":
warning("WinPcap is now deprecated (not maintained). "
"Please use Npcap instead")
elif b"npcap" in version.lower():
conf.use_npcap = True
LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter" # noqa: E501
except OSError:
conf.use_winpcapy = False
if conf.interactive:
log_loading.warning("wpcap.dll is not installed. "
"Restricted mode enabled ! "
"Visit the Scapy's doc to install it")
if conf.use_winpcapy:
def get_if_list():
"""Returns all pcap names"""
if not conf.cache_iflist:
load_winpcapy()
return [x[0] for x in conf.cache_iflist.values()]
else:
get_if_list = lambda: {}
class _PcapWrapper_winpcap: # noqa: F811
"""Wrapper for the WinPcap calls"""
def __init__(self, device, snaplen, promisc, to_ms, monitor=None):
开发者ID:commial,项目名称:scapy,代码行数:31,代码来源:pcapdnet.py
示例18: dict
MATPLOTLIB = 0
MATPLOTLIB_INLINED = 0
MATPLOTLIB_DEFAULT_PLOT_KARGS = dict()
log_loading.info("Can't import matplotlib. Won't be able to plot.")
# PYX
def _test_pyx():
"""Returns if PyX is correctly installed or not"""
try:
with open(os.devnull, 'wb') as devnull:
r = subprocess.check_call(["pdflatex", "--version"],
stdout=devnull, stderr=subprocess.STDOUT)
except (subprocess.CalledProcessError, OSError):
return False
else:
return r == 0
try:
import pyx # noqa: F401
if _test_pyx():
PYX = 1
else:
log_loading.warning("PyX dependencies are not installed ! Please install TexLive or MikTeX.") # noqa: E501
PYX = 0
except ImportError:
log_loading.info("Can't import PyX. Won't be able to use psdump() or pdfdump().") # noqa: E501
PYX = 0
开发者ID:commial,项目名称:scapy,代码行数:30,代码来源:extlib.py
示例19: read_routes
def read_routes():
ifaces.load_from_dnet()
zmap = {}
for i in ifaces:
for ip in ifaces.get(i).ip_list:
zmap[ip] = i
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")
import platform
is_win7 = not platform.platform().lower().startswith('windows-xp')
for l in f.readlines():
#l = l.encode('utf-8')
if is_win7:
str1 = u'永久路由'.encode('gbk')
if l.find( str1 )!=-1 or l.find('permanant route')!=-1 \
or l.find('Persistent Routes') !=-1 :
# Igore the permanant route on Vista and Win7
break
match = re.search(pattern,l)
if match:
dest2 = match.group(1)
mask = match.group(2)
gw = match.group(3)
netif = match.group(4)
metric = match.group(5)
dest = atol(dest2)
if dest >= I_MULTIIP_START and dest <= I_MULTIIP_END:
# multiple ip address
ifname = zmap.get(netif, 'lo0')
addr = netif
else:
try:
# If addrtxt is multicast IP, it will not function well
intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest2))
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]
ifname = str(intf["name"])
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))
# when a interface has multi IPs, addr may not be the correct OutIP
# So I extract the correct IP from ifaces
# by chenzongze 2012.07.24
output_ip = netif
for ifs in ifaces:
if addr in ifaces[ifs].ip_list:
for my_ip in ifaces[ifs].ip_list:
if ( atol(my_ip) & mask) == ( atol(gw) & mask ) and (mask !=0):
output_ip = my_ip
break
break
# Add metric by chenzongze 2012.07.24
routes.append((dest,mask,gw, ifname, output_ip, metric))
#.........这里部分代码省略.........
开发者ID:ogreworld,项目名称:ScapyExtension,代码行数:101,代码来源:__init__.py
示例20: load_protocols
MANUFDB = None
else:
IP_PROTOS = load_protocols("/etc/protocols")
ETHER_TYPES = load_ethertypes("/etc/ethertypes")
TCP_SERVICES, UDP_SERVICES = load_services("/etc/services")
MANUFDB = None
for prefix in ['/usr', '/usr/local', '/opt', '/opt/wireshark']:
try:
MANUFDB = load_manuf(os.path.join(prefix, "share", "wireshark",
"manuf"))
if MANUFDB:
break
except (IOError, OSError): # Same as above
pass
if not MANUFDB:
log_loading.warning("Cannot read wireshark manuf database")
#####################
# knowledge bases #
#####################
class KnowledgeBase:
def __init__(self, filename):
self.filename = filename
self.base = None
def lazy_init(self):
self.base = ""
def reload(self, filename=None):
开发者ID:segment-routing,项目名称:scapy,代码行数:31,代码来源:data.py
注:本文中的scapy.error.log_loading.warning函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论