本文整理汇总了Python中netifaces.ifaddresses函数的典型用法代码示例。如果您正苦于以下问题:Python ifaddresses函数的具体用法?Python ifaddresses怎么用?Python ifaddresses使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ifaddresses函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: ip_addresses
def ip_addresses():
"""Find the IP addresses of the divices that look at file.
TODO: Make code so that when any divice is looking for data
logalyzer can find ip address and email to device, if the
ip address is seen multiple times then anotheremail is not
sent to device.
Returns:
ip_list: the list with the ip addresses
"""
# list for ip addresses
ip_list = []
# Interate over available interfaces
for interface in netifaces.interfaces():
# Ignore interfaces with no data
if bool(netifaces.ifaddresses(interface)) is False:
continue
# IPv4 addresses ALWAYS have a key of netifaces.AF_INET (2)
# Make sure this is the case for this interface
if netifaces.AF_INET in netifaces.ifaddresses(interface):
# Hooray we have an IPv4 address! Add it to the list
for interface_data in netifaces.ifaddresses(
interface)[netifaces.AF_INET]:
ip_list.append(interface_data['addr'])
# Return
return ip_list
开发者ID:jhar123,项目名称:logalyzer,代码行数:30,代码来源:logalyzer.py
示例2: _detect
def _detect(self):
"""uses the netifaces module to detect ifconfig information"""
theip = None
try:
if self.opts['family'] == 'INET6':
addrlist = netifaces.ifaddresses(self.opts['iface'])[netifaces.AF_INET6]
else:
addrlist = netifaces.ifaddresses(self.opts['iface'])[netifaces.AF_INET]
except ValueError as exc:
log.error("netifaces choked while trying to get network interface"
" information for interface '%s'", self.opts['iface'],
exc_info=exc)
else: # now we have a list of addresses as returned by netifaces
for pair in addrlist:
try:
detip = IPy.IP(pair['addr'])
except (TypeError, ValueError) as exc:
log.debug("Found invalid IP '%s' on interface '%s'!?",
pair['addr'], self.opts['iface'], exc_info=exc)
continue
if self.netmask is not None:
if detip in self.netmask:
theip = pair['addr']
else:
continue
else:
theip = pair['addr']
break # we use the first IP found
# theip can still be None at this point!
self.set_current_value(theip)
return theip
开发者ID:asmaps,项目名称:python-dyndnsc,代码行数:31,代码来源:iface.py
示例3: find_ip
def find_ip(iface):
if not iface or iface == "any":
return ("0.0.0.0", "")
if_ip4 = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]["addr"]
if_ip6 = netifaces.ifaddresses(iface)[netifaces.AF_INET6][0]["addr"]
return (if_ip4, if_ip6)
开发者ID:casparcedro,项目名称:opendht,代码行数:7,代码来源:dhtnetwork.py
示例4: main
def main(iface):
# Get IP and mask
ipHost = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
mask = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['netmask']
# Calculate the CIDR value
maskCIDR = maskToCIDR(mask)
tlwpa4230pIPs = []
network = ipaddress.ip_network('{}/{}'.format(ipHost, maskCIDR), strict=False)
print ('-- Scanning {} addresses...'.format(network.num_addresses - 2))
for addr in network.hosts():
# Check if the addr belongs to a TL-WPA4230P powerline adapter
res = checkTLWPA4230P(str(addr))
if res:
print('{} is a TL-WPA4230P powerline adapter!'.format(str(addr)))
tlwpa4230pIPs.append(str(addr))
print('-- Scan completed.')
# Open the web interface of the powerline adapters found
for ip in tlwpa4230pIPs:
print('Opening {} in web browser...'.format(ip))
xdgOpenProcess = subprocess.Popen(['xdg-open', 'http://{}'.format(ip)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
xdgOpenProcess.wait()
开发者ID:javiersevball,项目名称:TL-WPA4230P_finder,代码行数:28,代码来源:finder.py
示例5: __init__
def __init__(self):
# ----------------- NIC INFO -----------------
self.os = platform.dist()[0]
# If system is "debian":
if self.os == 'debian':
self.hostname = socket.gethostname()
self.iface = ni.interfaces()[1]
self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']
self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']
self.gateways = ni.gateways()['default'][ni.AF_INET][0]
# --- OS INFO ---------------------
self.os_ver = platform.dist()[1]
self.mac = ''.join('%012x' % get_mac())
self.ip_data = get_ip()
self.path_ip = '/etc/network/interfaces'
self.dns_file = '/etc/resolv.conf'
# If system is "Arch Linux":
else:
self.hostname = socket.gethostname()
self.iface = ni.interfaces()[1]
self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']
self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask']
self.gateways = ni.gateways()['default'][ni.AF_INET][0]
# --- OS INFO ---------------------
self.os_ver = platform.dist()[1]
self.mac = ''.join('%012x' % get_mac())
self.ip_data = get_ip()
self.path_ip = '/etc/netctl/eth0'
self.dns_file = '/etc/resolv.conf'
logger.debug('GET IP SETTING OK!')
开发者ID:jense-arntz,项目名称:Full-Stack-Server-Client-App,代码行数:31,代码来源:views.py
示例6: find_ip
def find_ip(iface):
if not iface or iface == 'any':
return ('0.0.0.0','')
if_ip4 = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
if_ip6 = netifaces.ifaddresses(iface)[netifaces.AF_INET6][0]['addr']
return (if_ip4, if_ip6)
开发者ID:yomgui1,项目名称:opendht,代码行数:7,代码来源:network.py
示例7: get_commotion_client_ip
def get_commotion_client_ip():
"""Check interfaces for a valid commotion client IP address"""
# Will interface impact commotion tests
commotion_interfaces = {}
commotion_client_ip = None
# Raw list of interfaces
# Could be rewritten as for __, iface in enumerate(ni.interfaces())
interfaces = ni.interfaces()
for iface in interfaces:
try:
if ni.ifaddresses(iface)[2][0]['addr'].startswith('10.'):
print(iface + " has a valid Commotion IP address: " \
+ ni.ifaddresses(iface)[2][0]['addr'])
commotion_client_ip = ni.ifaddresses(iface)[2][0]['addr']
else:
commotion_interfaces[iface] = False
print(iface + " not valid")
except KeyError:
commotion_interfaces[iface] = True
print(iface + " has been disconnected")
continue
try:
commotion_client_ip
except (exceptions.CommotionIPError, KeyError) as args:
print(args)
# This should only return one thing. Move interfaces somewhere else!
return commotion_interfaces, commotion_client_ip
开发者ID:areynold,项目名称:commotion-router-test-suite,代码行数:29,代码来源:router.py
示例8: getLocalIP
def getLocalIP():
if _platform == "darwin":
interfaceName = "en0"
else:
interfaceName = "eth0"
netifaces.ifaddresses(interfaceName)
return netifaces.ifaddresses(interfaceName)[2][0]['addr']
开发者ID:andycavatorta,项目名称:nervebox_2,代码行数:7,代码来源:discovery.py
示例9: get_interfaces
def get_interfaces(self):
'''
Retrieve the interfaces of the VM
'''
interfaces = netifaces.interfaces()
self.interfaces = []
for interface in interfaces:
if interface == 'lo':
continue
default_gw = ''
configuration_type = None
gws = netifaces.gateways()
if gws['default'] != {} and gws['default'][netifaces.AF_INET][1] == interface:
default_gw = gws['default'][netifaces.AF_INET][0]
interface_af_link_info = netifaces.ifaddresses(interface)[17]
if 2 in netifaces.ifaddresses(interface):
interface_af_inet_info = netifaces.ifaddresses(interface)[2]
ipv4_address = interface_af_inet_info[0]['addr']
netmask = interface_af_inet_info[0]['netmask']
else:
ipv4_address = ""
netmask = ""
if interface == constants.configuration_interface:
_type = 'config'
configuration_type = 'dhcp'
else:
_type = 'not_defined'
self.interfaces.append(Interface(name = interface, status = None,
mac_address = interface_af_link_info[0]['addr'],
ipv4_address = ipv4_address,
netmask = netmask,
default_gw = default_gw,
_type = _type,
configuration_type = configuration_type))
开发者ID:netgroup-polito,项目名称:un-orchestrator,代码行数:34,代码来源:dhcp_server.py
示例10: _update_widgets
def _update_widgets(self, widgets):
interfaces = [ i for i in netifaces.interfaces() if not i.startswith(self._exclude) ]
for widget in widgets:
widget.set("visited", False)
for intf in interfaces:
addr = []
state = "down"
try:
if netifaces.AF_INET in netifaces.ifaddresses(intf):
for ip in netifaces.ifaddresses(intf)[netifaces.AF_INET]:
if "addr" in ip and ip["addr"] != "":
addr.append(ip["addr"])
state = "up"
except Exception as e:
addr = []
widget = self.widget(intf)
if not widget:
widget = bumblebee.output.Widget(name=intf)
widgets.append(widget)
widget.full_text("{}".format(",".join(addr)))
#widget.full_text("{} {} {}".format(intf, state, ", ".join(addr)))
widget.set("intf", intf)
widget.set("state", state)
widget.set("visited", True)
for widget in widgets:
if widget.get("visited") == False:
widgets.remove(widget)
开发者ID:bse666,项目名称:dotfiles,代码行数:30,代码来源:nic.py
示例11: update
def update(self):
"""Update IP stats using the input method.
Stats is dict
"""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local' and not import_error_tag:
# Update stats using the netifaces lib
try:
default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
except (KeyError, AttributeError) as e:
logger.debug("Cannot grab the default gateway ({})".format(e))
else:
try:
stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
stats['mask_cidr'] = self.ip_to_cidr(stats['mask'])
stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
stats['public_address'] = self.public_address
except (KeyError, AttributeError) as e:
logger.debug("Cannot grab IP information: {}".format(e))
elif self.input_method == 'snmp':
# Not implemented yet
pass
# Update the stats
self.stats = stats
return self.stats
开发者ID:nicolargo,项目名称:glances,代码行数:31,代码来源:glances_ip.py
示例12: main
def main():
# bssid = get_bssid(iface)
# needs try / catch
iface = netifaces.gateways()['default'][netifaces.AF_INET][1]
conf.iface = iface
local_mac = netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr']
local_ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
print local_mac
print local_ip
bssid = get_bssid(iface)
nm = nmap.PortScanner()
nm_scan = nm.scan(hosts = '192.168.0.0/24', arguments='-sP')
eligible_hosts = collect_eligible_hosts(nm_scan, local_ip, '192.168.0.1')
display_eligible_hosts(eligible_hosts)
user_choice = ask_user()
enable_monitor_mode(iface)
# client_to_deauth = eligible_hosts[2].mac_address
while (True):
for e in eligible_hosts:
for n in range(20):
sendp(RadioTap()/Dot11(type=0,subtype=12,addr1=test_client,addr2=bssid,addr3=bssid)/Dot11Deauth(reason=7))
开发者ID:m4ttclendenen,项目名称:deauth,代码行数:29,代码来源:deauth.py
示例13: run
def run(self):
silent = positive(self.parameters['SILENT'].value)
import netifaces as n
ifs = n.interfaces()
result = {}
for iface in ifs:
afs = {}
for ad in n.ifaddresses(iface):
afs[n.address_families[ad]] = n.ifaddresses(iface)[ad]
result[iface] = afs
#output
if not silent:
for interface in result:
log.ok('%s:' % interface)
for afamily in result[interface]:
log.ok(' %s:' %afamily)
for addressid in range(0, len(result[interface][afamily])):
log.ok(' address %d:' % addressid)
address = result[interface][afamily][addressid]
for key in address:
log.ok(' %s = %s' % (key, address[key]))
#lib.kb.add('NETWORK INTERFACES', result)
for x in result:
lib.kb.add('NETWORK INTERFACES %s' % (x), result[x])
# # # # # # # #
return None
开发者ID:lightfaith,项目名称:locasploit,代码行数:29,代码来源:network_enumeration_interfaces.py
示例14: get_interfaces
def get_interfaces(self):
'''
Retrieve the interfaces of the VM
'''
interfaces = netifaces.interfaces()
self.interfaces = []
for interface in interfaces:
if interface == 'lo':
continue
default_gw = ''
gws = netifaces.gateways()
#logging.debug("GATEWAY: "+str(gws))
#logging.debug("GATEWAY: "+str(gws['default']))
#logging.debug("GATEWAY: "+str(gws['default'][netifaces.AF_INET]))
if gws['default'] == {}:
default_gw = ''
else:
for gw in gws[netifaces.AF_INET]:
if gw[1] == interface:
default_gw = gw[0]
interface_af_link_info = netifaces.ifaddresses(interface)[17]
if 2 in netifaces.ifaddresses(interface):
interface_af_inet_info = netifaces.ifaddresses(interface)[2]
ipv4_address = interface_af_inet_info[0]['addr']
netmask = interface_af_inet_info[0]['netmask']
else:
ipv4_address = ""
netmask = ""
self.interfaces.append(Interface(name = interface, status = None,
mac_address = interface_af_link_info[0]['addr'],
ipv4_address = ipv4_address,
netmask = netmask,
default_gw = default_gw))
开发者ID:netgroup-polito,项目名称:un-orchestrator,代码行数:33,代码来源:nat.py
示例15: get_mac_addresses
def get_mac_addresses(ifname=None,ignore_nas=True,with_ip4=False):
"""By default ignore stuff like firewire"""
try:
import netifaces
if ifname:
info = netifaces.ifaddresses(ifname)
return (( _unpack_mac(info.get(18)) or _unpack_mac(info.get(17)) ),)
else:
addresses = []
for ifce in netifaces.interfaces():
if_props = INTERFACES.get(ifce) or (False,False,False,False)
if_addrs = netifaces.ifaddresses(ifce)
#print ifce, if_addrs, if_props
if ignore_nas and if_props[2]: continue
if not if_props[1]: continue
ip4 = if_addrs.get(2)
ip6 = if_addrs.get(30)
if with_ip4 and not ip4: continue
mac = if_addrs.get(17) or if_addrs.get(18)
if mac:
addresses.append(_unpack_mac(mac))
return addresses
except Exception, e:
import uuid
# bit primitive, and not stable on mac
m = hex(uuid.getnode())[2:-1].zfill(12)
return ( ':'.join((m[0:2],m[2:4],m[4:6],m[6:8],m[8:10],m[10:12])), )
开发者ID:thepian,项目名称:thepian-lib,代码行数:27,代码来源:net.py
示例16: setUp
def setUp(self):
'''
To check and install dependencies for the test
'''
smm = SoftwareManager()
pkgs = ["ethtool", "net-tools"]
detected_distro = distro.detect()
if detected_distro.name == "Ubuntu":
pkgs.extend(["openssh-client", "iputils-ping"])
elif detected_distro.name == "SuSE":
pkgs.extend(["openssh", "iputils"])
else:
pkgs.extend(["openssh-clients", "iputils"])
for pkg in pkgs:
if not smm.check_installed(pkg) and not smm.install(pkg):
self.cancel("%s package is need to test" % pkg)
interfaces = netifaces.interfaces()
interface = self.params.get("interface")
if interface not in interfaces:
self.cancel("%s interface is not available" % interface)
mtu_list = self.params.get("size_val", default=1500)
self.mtu_list = mtu_list.split()
self.iface = interface
self.peer = self.params.get("peer_ip")
self.eth = "ethtool %s | grep 'Link detected:'" % self.iface
self.eth_state = process.system_output(self.eth, shell=True)
if AF_INET in netifaces.ifaddresses(self.iface):
self.ip_set = netifaces.ifaddresses(self.iface)[AF_INET][0]['addr']
开发者ID:balamuruhans,项目名称:avocado-misc-tests,代码行数:28,代码来源:net_data.py
示例17: get_host_ip4_addresses
def get_host_ip4_addresses():
ip_list = []
for interface in interfaces():
if AF_INET in ifaddresses(interface):
for link in ifaddresses(interface)[AF_INET]:
ip_list.append(link['addr'])
return ip_list
开发者ID:cloudviz,项目名称:agentless-system-crawler,代码行数:7,代码来源:misc.py
示例18: Get_LocalIP
def Get_LocalIP():
try:
import netifaces
interfaces = netifaces.interfaces();
for str in interfaces:
print(str)
chosen_interface = input('Please Choose The Network Interface From List Above =>')
if chosen_interface not in interfaces:
print('Wrong Input. Please Choose From List.')
Get_LocalIP()
else:
try:
ip = netifaces.ifaddresses(chosen_interface)[netifaces.AF_INET][0]['addr']
if ip == None:
print("Wrong Interface. Please Select Another One...")
else:
return netifaces.ifaddresses(chosen_interface)[netifaces.AF_INET][0]['addr']
except KeyError:
print("Wrong Interface. Please Select Another One...")
Get_LocalIP()
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
logging.error(repr(traceback.format_exception(exc_type, exc_value,
exc_traceback)))
raise
开发者ID:TR-ITC8061-16,项目名称:ITC8061,代码行数:25,代码来源:Utils.py
示例19: main
def main(cfg):
logger = logging.getLogger('Main')
logger.info('Available interfaces: {}.'.format(', '.join(netifaces.interfaces())))
interface_name = cfg['node']['interface']
if interface_name is not None:
if interface_name not in netifaces.interfaces():
logger.warn('There is no interface {}!'.format(interface_name))
return
else:
mac, broadcast_address = get_interface_mac_broadcast(netifaces.ifaddresses(interface_name))
if mac is None:
logger.warn('MAC not found on interface {}!'.format(interface_name))
if broadcast_address is None:
logger.warn('Broadcast address not found on interface {}!'.format(interface_name))
else:
for interface_name in netifaces.interfaces():
if interface_name.startswith('lo'):
continue
mac, broadcast_address = get_interface_mac_broadcast(netifaces.ifaddresses(interface_name))
if mac is not None and broadcast_address is not None:
break
if interface_name is None:
logger.warn('There is no available appropriate interfaces!')
return
logger.info('Used interface: {}. MAC: {}. Broadcast address: {}.'.format(interface_name, mac, broadcast_address))
mac = int(mac.replace(':', ''), 16)
logger.info('Integer MAC: {}.'.format(mac))
run_visualization_server(mac, broadcast_address, cfg)
开发者ID:ifmo-ctd-2012-networks,项目名称:labs,代码行数:30,代码来源:run_visualization.py
示例20: main
def main():
parser=argparse.ArgumentParser()
parser.add_argument("interface")
parser.add_argument("passwd")
parser.add_argument("-v6","--ipv6",action="store_true",help="use ipv6 address")
args=parser.parse_args()
password=args.passwd
local_addr=''
broadcast_addr=''
port=9890
so=''
if args.ipv6:
local_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET6][0]['addr']
broadcast_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET6][0]['broadcast']
so=socket.socket(socket.AF_INET6,socket.SOCK_DGRAM)
so.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
so.bind(('::',port))
else:
local_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET][0]['addr']
broadcast_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET][0]['broadcast']
so=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
so.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
so.bind(('0.0.0.0',port))
so.settimeout(5)
message=local_addr+'|'+password
so.sendto(message.encode('UTF-8'),(broadcast_addr,port))
so.recv(50) #clean up the echo of the package we just sent
try:
print("Raspberry Pi's IP address is {0}".format(so.recv(50).decode('UTF-8')))
except socket.timeout:
print('No response. Maybe the password is wrong.\n')
so.close()
开发者ID:Zumium,项目名称:whereismypi,代码行数:33,代码来源:whereismypi.py
注:本文中的netifaces.ifaddresses函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论