本文整理汇总了Python中netaddr.IPAddress.is_private方法的典型用法代码示例。如果您正苦于以下问题:Python IPAddress.is_private方法的具体用法?Python IPAddress.is_private怎么用?Python IPAddress.is_private使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netaddr.IPAddress
的用法示例。
在下文中一共展示了IPAddress.is_private方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_priv_info
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def get_priv_info(d_iface_to_addr=None):
s_net_id = None
s_priv_ip = None
s_priv_interface = None
if d_iface_to_addr is None:
d_iface_to_addr = get_iface_to_addr()
networks = search('net', 'name', '*')
for s_iface, d_addr in d_iface_to_addr.items():
if s_iface.startswith('lo'):
continue
if netifaces.AF_INET not in d_addr:
continue
ips = d_addr[netifaces.AF_INET]
for ip in ips:
o_ip = IPAddress(str(ip['addr']))
if not o_ip.is_private():
continue
if ip['addr'] == '127.0.0.1':
continue
for net in networks:
if (('netmask' in net) and
(o_ip in IPNetwork(net['netmask']))):
s_priv_ip = str(ip['addr'])
s_priv_interface = s_iface
s_net_id = net['name']
break
return (s_priv_ip, s_priv_interface, s_net_id)
示例2: get_ip_address
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def get_ip_address(self, test_address=None):
"""
try to get global IP address from interface information.
if failed, just return '127.0.0.1'
:param str test_address: ip address str if test to check global ip.
normally None.
:return: global ip address if successed, or '127.0.0.1'
"""
for iface_name in netifaces.interfaces():
iface_data = netifaces.ifaddresses(iface_name)
logging.debug('Interface: %s' % (iface_name, ))
ifaces = []
if netifaces.AF_INET in iface_data:
ifaces += iface_data[netifaces.AF_INET]
if netifaces.AF_INET6 in iface_data:
ifaces += iface_data[netifaces.AF_INET6]
for iface in ifaces:
ip = iface['addr']
ip = re.sub(r'\%.+$', '', ip)
if test_address is not None:
ip = test_address
addr = IPAddress(ip)
if not addr.is_loopback() and addr.is_unicast() and\
not addr.is_private():
logging.debug('global ip %s', addr)
return ip
logging.debug('no global ip')
return '127.0.0.1'
示例3: auto_select_target
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def auto_select_target(target, output=None):
"""Auto selection logic"""
print "Target: %s" % target
try:
inp=IPAddress(target);
if inp.is_private() or inp.is_loopback():
print "Internal IP Detected : Skipping"
sys.exit()
else:
print "Looks like an IP, running ipOsint...\n"
ipOsint.run(target, output)
except SystemExit:
print "exiting"
except AddrFormatError:
if re.match('[^@][email protected][^@]+\.[^@]+', target):
print "Looks like an EMAIL, running emailOsint...\n"
emailOsint.run(target, output)
elif get_tld(target, fix_protocol=True,fail_silently=True) is not None:
print "Looks like a DOMAIN, running domainOsint...\n"
domainOsint.run(target, output)
else:
print "Nothing Matched assuming username, running usernameOsint...\n"
usernameOsint.run(target, output)
except:
print "Unknown Error Occured"
示例4: to_server_dict
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def to_server_dict(server):
public_ips = [ip["addr"] for ip in server.addresses["public"]]
private_ips = [ip["addr"] for ip in server.addresses["private"]]
# Pick out first public IPv4 and IPv6 address
public_ipv4 = None
public_ipv6 = None
for ip in public_ips:
try:
ip_obj = IPAddress(ip)
except Exception:
continue
if not ip_obj.is_private():
if ip_obj.version == 4:
public_ipv4 = ip
elif ip_obj.version == 6:
public_ipv6 = ip
result = {
"id": server.id,
"name": server.name,
"status": server.status,
"image_id": server.image["id"],
"flavor_id": server.flavor["id"],
"public_ips": public_ips,
"private_ips": private_ips,
"public_ipv4": public_ipv4,
"public_ipv6": public_ipv6,
"key_name": server.key_name,
"metadata": server.metadata,
}
return result
示例5: call
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def call(self, url, context):
if self.url_can_resolve(url):
try:
ip = yield self.resolver.get_host_by_name(url.domain)
ip = IPAddress(ip)
except Exception:
# context["event"].target.respond(
# u'[Error] Failed to handle URL: {}'.format(
# url.to_string()
# )
# )
self.plugin.logger.exception("Error while checking DNS")
returnValue(STOP_HANDLING)
return
if ip.is_loopback() or ip.is_private() or ip.is_link_local() \
or ip.is_multicast():
self.plugin.logger.warn(
"Prevented connection to private/internal address"
)
returnValue(STOP_HANDLING)
return
headers = {}
if url.domain in context["config"]["spoofing"]:
user_agent = context["config"]["spoofing"][url.domain]
if user_agent:
headers["User-Agent"] = user_agent
else:
headers["User-Agent"] = context["config"].get(
"default_user_agent",
"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 "
"Firefox/36.0"
)
domain_langs = context.get("config") \
.get("accept_language", {}) \
.get("domains", {})
if url.domain in domain_langs:
headers["Accept-Language"] = domain_langs.get(url.domain)
else:
headers["Accept-Language"] = context.get("config") \
.get("accept_language", {}) \
.get("default", "en")
session = self.get_session(url, context)
session.get(unicode(url), headers=headers, stream=True,
background_callback=self.background_callback) \
.addCallback(self.callback, url, context, session) \
.addErrback(self.errback, url, context, session)
returnValue(STOP_HANDLING)
示例6: metadata_file_writer
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def metadata_file_writer(q, filename):
PLUGINS = load_metadata_plugins()
metadata_file = open(filename, "w")
ip_adresses = [0]
while True:
connection = q.get()
ip = connection[6]
ipAddress = IPAddress(hex_to_ip(ip))
if ip not in ip_adresses and not ipAddress.is_private() and not ipAddress.is_loopback():
ip_adresses.append(ip)
for p in PLUGINS:
p.set_connection(connection)
res = p.run()
if len(res):
metadata_file.write("%s, %s,%s\n" % (p.name, hex_to_ip(ip), res))
metadata_file.flush()
q.task_done()
示例7: _is_public
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def _is_public(self, ip):
ip = IPAddress(ip)
return ip.is_unicast() and not ip.is_private()
示例8: callback
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def callback(self, result, url, context, session):
response = result[0]
content = result[1]
self.plugin.logger.trace(
"Headers: {0}", list(response.headers)
)
self.plugin.logger.trace("HTTP code: {0}", response.status_code)
new_url = urlparse.urlparse(response.url)
if self.url_can_resolve(url):
try:
ip = yield self.resolver.get_host_by_name(new_url.hostname)
ip = IPAddress(ip)
except Exception:
# context["event"].target.respond(
# u'[Error] Failed to handle URL: {}'.format(
# url.to_string()
# )
# )
self.plugin.logger.exception("Error while checking DNS")
returnValue(STOP_HANDLING)
return
if ip.is_loopback() or ip.is_private() or ip.is_link_local() \
or ip.is_multicast():
self.plugin.logger.warn(
"Prevented connection to private/internal address"
)
returnValue(STOP_HANDLING)
return
if content is None:
self.plugin.logger.debug("No content returned")
return
soup = BeautifulSoup(content)
if soup.title and soup.title.text:
title = soup.title.text.strip()
title = re.sub("[\n\s]+", " ", title)
title = to_unicode(title)
title_limit = self.urls_plugin.config.get("max_title_length", 150)
if len(title) > title_limit:
title = title[:title_limit - 15] + u"... (truncated)"
if response.status_code == requests.codes.ok:
context["event"].target.respond(
u'"{0}" at {1}'.format(
title, new_url.hostname
)
)
else:
context["event"].target.respond(
u'[HTTP {0}] "{1}" at {2}'.format(
response.status_code,
title, new_url.hostname
)
)
else:
if response.status_code != requests.codes.ok:
context["event"].target.respond(
u'HTTP Error {0}: "{1}" at {2}'.format(
response.status_code,
STATUS_CODES.get(response.status_code, "Unknown"),
new_url.hostname
)
)
else:
self.plugin.logger.debug("No title")
self.save_session(session)
示例9: check_ip
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def check_ip(addr):
"""Verify that the server/client IP is valid"""
addr = IPAddress(addr)
if addr.version != 4 or not addr.is_private():
raise ValidationError("Only private IPv4 networks are supported.")
示例10: test_is_public
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def test_is_public():
ip = IPAddress('62.125.24.5')
assert ip.is_unicast() and not ip.is_private()
示例11: has_public_ip
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def has_public_ip(self):
ip = IPAddress(self.ip)
return ip.is_unicast() and not ip.is_private()
示例12: fifoReader
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def fifoReader(infile, q, exitSignal):
sleeptime=0.5
maxSleeptime=1.0
while True:
try:
if exitSignal.is_set(): break
line=infile.readline()
if not line:
time.sleep(1)
continue
if line=='ENDOFFILE':
break
try:
spl=line.split()
timestamp, queriedName, clientID, ipv4 = spl
except:
continue
else:
if not '.' in queriedName:
continue
try:
addr=IPAddress(ipv4)
except netaddr.AddrFormatError:
continue
else:
if (addr.is_unicast() and
not addr.is_private() and
not addr.is_reserved() and
not addr.is_loopback()):
try:
timestamp=int(timestamp)
except ValueError:
continue
else:
data = ((queriedName, clientID, [addr]),
timestamp)
queued=False
while not queued:
try:
q.put_nowait(data)
except Queue.Full:
# we saturated the queue, let's give the reading
# process some time to empty it again, where we don't
# try to put something in the queue and thereby lock it
# continuously
time.sleep(sleeptime)
if q.empty():
sleeptime*=0.5
elif q.qsize() >= q._maxsize:
sleeptime*=2
if sleeptime>maxSleeptime:
sleeptime=maxSleeptime
else:
queued=True
except KeyboardInterrupt:
break
q.put(None)
示例13: pcapReader
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
def pcapReader(q, exitSignal, infile=None, interface=None, thrsh=0):
if not infile and not interface:
# FIXME: write warning here
return
if infile:
pc=pcap.pcapObject()
try:
pc.open_offline(infile)
except IOError:
#log("could not open pcap interface "+str(input_interface)+"\n")
pass
if interface:
pc=pcap.pcapObject()
try:
#pc.open_live(interface, snaplen, promisc, read_timeout)
pc.open_live(interface, 1600, 0, 100)
except IOError:
#log("could not open pcap interface "+str(input_interface)+"\n")
pass
except Exception:
# most likely we got no permission to open the interface
sys.stderr.write('could not open interface. insufficient '
'permissions?\n')
q.put(None)
return
pc.setfilter('udp', 0, 0)
basets=0
newMappings=dict()
while True:
if exitSignal.is_set():
break
try:
packet=pc.next()
if not packet:
if infile:
# end of file
break
elif interface:
# read timeout
continue
payload=packet[1]
timestamp=int(packet[2])
# make sure we are dealing with IP traffic
# ref: http://www.iana.org/assignments/ethernet-numbers
try: eth = dpkt.ethernet.Ethernet(payload)
except: continue
if eth.type != 2048: continue
# make sure we are dealing with UDP
# ref: http://www.iana.org/assignments/protocol-numbers/
try: ip = eth.data
except: continue
if ip.p != 17: continue
# filter on UDP assigned ports for DNS
# ref: http://www.iana.org/assignments/port-numbers
try: udp = ip.data
except: continue
if udp.sport != 53 and udp.dport != 53: continue
# make the dns object out of the udp data and check for it being a RR (answer)
# and for opcode QUERY (I know, counter-intuitive)
try: dns = dpkt.dns.DNS(udp.data)
except: continue
if dns.qr != dpkt.dns.DNS_R: continue
if dns.opcode != dpkt.dns.DNS_QUERY: continue
if dns.rcode != dpkt.dns.DNS_RCODE_NOERR: continue
if len(dns.an) < 1: continue
if len(dns.qd) == 0: continue
aRecords=set()
queriedName=dns.qd[0].name
if not '.' in queriedName:
continue
#lastCname=queriedName
for answer in dns.an:
"""
FIXME: this doesn't work for multiple queries in one DNS packet
"""
#if answer.type == dpkt.dns.DNS_CNAME:
# lastCname=answer.cname
if answer.type == dpkt.dns.DNS_A:
ip=socket.inet_ntoa(answer.rdata)
try:
addr=IPAddress(ip)
except netaddr.AddrFormatError:
continue
else:
if (addr.is_unicast() and
not addr.is_private() and
#.........这里部分代码省略.........
示例14: IpAddress
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
class IpAddress(DatabaseObject):
''' Wraps the netaddr IPAddress class '''
uuid = Column(String(36),
unique=True,
nullable=False,
default=lambda: str(uuid4())
)
box_id = Column(Integer, ForeignKey('box.id'), nullable=False)
_address = Column(String(80))
_ip_address = None
visable = Column(Boolean, default=True)
@classmethod
def all(cls):
''' Returns a list of all objects in the database '''
return dbsession.query(cls).all()
@classmethod
def by_id(cls, _id):
''' Returns a the object with id of _id '''
return dbsession.query(cls).filter_by(id=_id).first()
@classmethod
def by_uuid(cls, _uuid):
''' Return and object based on a _uuid '''
return dbsession.query(cls).filter_by(uuid=_uuid).first()
@classmethod
def by_address(cls, address):
''' Return and object based on an address '''
return dbsession.query(cls).filter_by(_address=address).first()
@classmethod
def ipformat(self, value):
ipformat = value
if ipformat:
if ipformat.count(":") == 1:
#ip v4 with port
ipformat = ipformat.split(":")[0]
elif "]:" in ipformat:
#ip v6 with port
ipformat = ipformat.split("]:")[0]
#ip v6 enclosing
ipformat = ipformat.replace("[", "").replace("]", "")
if "/" in ipformat:
#remove any file info
ipformat = ipformat.split("/")[0]
return ipformat
@property
def address(self):
return self._address
@address.setter
def address(self, value):
ip = IPAddress(self.ipformat(value))
if ip.is_loopback():
raise ValidationError("You cannot use a loopback address")
if ip.is_multicast():
raise ValidationError("You cannot use a multicast address")
self._address = value
@property
def version(self):
if self._ip_address is None:
self._ip_address = IPAddress(self.ipformat(self._address))
return self._ip_address.version
@property
def is_private(self):
if self._ip_address is None:
self._ip_address = IPAddress(self.ipformat(self._address))
return self._ip_address.is_private()
def to_xml(self, parent):
ip_elem = ET.SubElement(parent, "ip")
ip_elem.set("version", str(self.version))
ET.SubElement(ip_elem, "address").text = self.address
def __repr__(self):
return "<IpAddress - %s>" % self.address
def __str__(self):
return self._address
def __eq__(self, other):
return self._address == other._address
def __ne__(self, other):
return not self == other
示例15: IpAddress
# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_private [as 别名]
class IpAddress(DatabaseObject):
''' Wraps the netaddr IPAddress class '''
uuid = Column(String(36), unique=True, nullable=False, default=lambda: str(uuid4()))
box_id = Column(Integer, ForeignKey('box.id'), nullable=False)
_address = Column(String(40), unique=True)
_ip_address = None
@classmethod
def all(cls):
''' Returns a list of all objects in the database '''
return dbsession.query(cls).all()
@classmethod
def by_id(cls, _id):
''' Returns a the object with id of _id '''
return dbsession.query(cls).filter_by(id=_id).first()
@classmethod
def by_uuid(cls, _uuid):
''' Return and object based on a _uuid '''
return dbsession.query(cls).filter_by(uuid=_uuid).first()
@classmethod
def by_address(cls, addr):
''' Return and object based on an address '''
return dbsession.query(cls).filter_by(address=addr).first()
@property
def address(self):
if self._ip_address is None:
self._ip_address = IPAddress(self._address)
return self._ip_address.format()
@address.setter
def address(self, value):
ip = IPAddress(value)
if ip.is_loopback():
raise ValueError("You cannot use a loopback address")
if ip.is_multicast():
raise ValueError("You cannot use a multicast address")
self._address = value
@property
def version(self):
if self._ip_address is None:
self._ip_address = IPAddress(self._address)
return self._ip_address.version
@property
def is_private(self):
if self._ip_address is None:
self._ip_address = IPAddress(self._address)
return self._ip_address.is_private()
def to_xml(self, parent):
ip_elem = ET.SubElement(parent, "ip")
ip_elem.set("version", str(self.version))
ET.SubElement(ip_elem, "address").text = self.address
def __repr__(self):
return "<IpAddress - %s>" % self.address
def __str__(self):
return self._address
def __eq__(self, other):
return self._address == other._address
def __ne__(self, other):
return not self == other