我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用netifaces.interfaces()。
def get_iface_from_addr(addr): """Work out on which interface the provided address is configured.""" for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) for inet_type in addresses: for _addr in addresses[inet_type]: _addr = _addr['addr'] # link local ll_key = re.compile("(.+)%.*") raw = re.match(ll_key, _addr) if raw: _addr = raw.group(1) if _addr == addr: log("Address '%s' is configured on iface '%s'" % (addr, iface)) return iface msg = "Unable to infer net iface on which '%s' is configured" % (addr) raise Exception(msg)
def ipv4(): """ Get all IPv4 addresses for all interfaces. """ try: from netifaces import interfaces, ifaddresses, AF_INET # to not take into account loopback addresses (no interest here) addresses = [] for interface in interfaces(): config = ifaddresses(interface) # AF_INET is not always present if AF_INET in config.keys(): for link in config[AF_INET]: # loopback holds a 'peer' instead of a 'broadcast' address if 'addr' in link.keys() and 'peer' not in link.keys(): addresses.append(link['addr']) return addresses except ImportError: return []
def network(interface=None): if interface: try: netifaces.ifaddresses(interface) interfaces = [interface] except ValueError: return jsonify({"message": "interface {} not available".format(interface)}), 404 else: interfaces = netifaces.interfaces() data = dict() for i in interfaces: try: data[i] = netifaces.ifaddresses(i)[2] except KeyError: data[i] = {"message": "AF_INET data missing"} return jsonify(data)
def __init__(self, data # Data suitable for this class ): valid, message = data_is_valid(data) if not valid: raise ValueError("Invalid data: %s" % message) self.cidrs = [] for iface in netifaces.interfaces(): ifaddrs = netifaces.ifaddresses(iface) if netifaces.AF_INET in ifaddrs: for ifaddr in ifaddrs[netifaces.AF_INET]: if 'addr' in ifaddr: self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr'])) if netifaces.AF_INET6 in ifaddrs: for ifaddr in ifaddrs[netifaces.AF_INET6]: if 'addr' in ifaddr: #add v6 but remove stuff like %eth0 that gets thrown on end of some addrs self.cidrs.append(ipaddr.IPNetwork(ifaddr['addr'].split('%')[0]))
def get_host_devices(iface_prefix=''): rst = {} for ifacename in netifaces.interfaces(): if not ifacename.startswith(iface_prefix): continue addrs = netifaces.ifaddresses(ifacename) if netifaces.AF_INET in addrs and netifaces.AF_LINK in addrs: ips = [addr['addr'] for addr in addrs[netifaces.AF_INET]] for ip in ips: if is_ip4_loopback(ip): break else: rst[ifacename] = {'INET': addrs[netifaces.AF_INET], 'LINK': addrs[netifaces.AF_LINK]} return rst
def get_interface_addresses(logger): import StaticUPnP_Settings interface_config = Namespace(**StaticUPnP_Settings.interfaces) ip_addresses = StaticUPnP_Settings.ip_addresses if len(ip_addresses) == 0: import netifaces ifs = netifaces.interfaces() if len(interface_config.include) > 0: ifs = interface_config.include if len(interface_config.exclude) > 0: for iface in interface_config.exclude: ifs.remove(iface) for i in ifs: addrs = netifaces.ifaddresses(i) if netifaces.AF_INET in addrs: for addr in addrs[netifaces.AF_INET]: ip_addresses.append(addr['addr']) logger.info("Regestering multicast on %s: %s"%(i, addr['addr'])) return ip_addresses
def internal_ip(pl, interface='auto', ipv=4): family = netifaces.AF_INET6 if ipv == 6 else netifaces.AF_INET if interface == 'auto': try: interface = next(iter(sorted(netifaces.interfaces(), key=_interface_key, reverse=True))) except StopIteration: pl.info('No network interfaces found') return None elif interface == 'default_gateway': try: interface = netifaces.gateways()['default'][family][1] except KeyError: pl.info('No default gateway found for IPv{0}', ipv) return None addrs = netifaces.ifaddresses(interface) try: return addrs[family][0]['addr'] except (KeyError, IndexError): pl.info("No IPv{0} address found for interface {1}", ipv, interface) return None
def configure(protocol, port, pipes, interface): remove_all() reactor.addSystemEventTrigger('after', 'shutdown', remove_all) # gets default (outward-facing) network interface (e.g. deciding which of # eth0, eth1, wlan0 is being used by the system to connect to the internet) if interface == "auto": interface = netifaces.gateways()['default'][netifaces.AF_INET][1] else: if interface not in netifaces.interfaces(): raise ValueError("Given interface does not exist.", interface) add(protocol, port, interface) manager = libnetfilter_queue.Manager() manager.bind(UP_QUEUE, packet_handler(manager, pipes.up)) manager.bind(DOWN_QUEUE, packet_handler(manager, pipes.down)) reader = abstract.FileDescriptor() reader.doRead = manager.process reader.fileno = lambda: manager.fileno reactor.addReader(reader)
def get_ip_address(iface): """Get IP address of the interface connected to the network. If there is no such an interface, then localhost is returned. """ if iface not in netifaces.interfaces(): LOG.warning("Can't find interface '%s' in the host list of interfaces", iface) return '127.0.0.1' address_family = netifaces.AF_INET if address_family not in netifaces.ifaddresses(iface): LOG.warning("Interface '%s' doesnt configured with ipv4 address", iface) return '127.0.0.1' for ifaddress in netifaces.ifaddresses(iface)[address_family]: if 'addr' in ifaddress: return ifaddress['addr'] else: LOG.warning("Can't find ip addr for interface '%s'", iface) return '127.0.0.1'
def extract_ipv6_info(): """ Extracts IPv6 information""" print ("IPv6 support built into Python: %s" %socket.has_ipv6) for interface in ni.interfaces(): all_addresses = ni.ifaddresses(interface) print ("Interface %s:" %interface) for family,addrs in all_addresses.items(): fam_name = ni.address_families[family] for addr in addrs: if fam_name == 'AF_INET6': addr = addr['addr'] has_eth_string = addr.split("%eth") if has_eth_string: addr = addr.split("%eth")[0] try: print (" IP Address: %s" %na.IPNetwork(addr)) print (" IP Version: %s" %na.IPNetwork(addr).version) print (" IP Prefix length: %s" %na.IPNetwork(addr).prefixlen) print (" Network: %s" %na.IPNetwork(addr).network) print (" Broadcast: %s" %na.IPNetwork(addr).broadcast) except Exception as e: print ("Skip Non-IPv6 Interface")
def inspect_ipv6_support(): """ Find the ipv6 address""" print ("IPV6 support built into Python: %s" %socket.has_ipv6) ipv6_addr = {} for interface in ni.interfaces(): all_addresses = ni.ifaddresses(interface) print ("Interface %s:" %interface) for family,addrs in all_addresses.items(): fam_name = ni.address_families[family] print (' Address family: %s' % fam_name) for addr in addrs: if fam_name == 'AF_INET6': ipv6_addr[interface] = addr['addr'] print (' Address : %s' % addr['addr']) nmask = addr.get('netmask', None) if nmask: print (' Netmask : %s' % nmask) bcast = addr.get('broadcast', None) if bcast: print (' Broadcast: %s' % bcast) if ipv6_addr: print ("Found IPv6 address: %s" %ipv6_addr) else: print ("No IPv6 interface found!")
def in6_getifaddr(): """ Returns a list of 3-tuples of the form (addr, scope, iface) where 'addr' is the address of scope 'scope' associated to the interface 'ifcace'. This is the list of all addresses of all interfaces available on the system. """ ret = [] interfaces = get_if_list() for i in interfaces: addrs = netifaces.ifaddresses(i) if netifaces.AF_INET6 not in addrs: continue for a in addrs[netifaces.AF_INET6]: addr = a['addr'].split('%')[0] scope = scapy.utils6.in6_getscope(addr) ret.append((addr, scope, i)) return ret
def get_lo_alias_addr(): # check all interfaces an try to find one with address 127.0.0.1 # If that interface has another address, that's the one we need. ifname_loopback = None for interface in netifaces.interfaces(): ip_addresses = [] interface_addresses = netifaces.ifaddresses(interface) if netifaces.AF_INET not in interface_addresses: continue for address_data in interface_addresses[netifaces.AF_INET]: if address_data.get('addr') == '127.0.0.1': ifname_loopback = interface elif address_data.get('addr'): ip_addresses.append(address_data.get('addr')) if interface == ifname_loopback and ip_addresses: return ip_addresses[0]
def setUp(self): ''' To check and install dependencies for the test ''' self.host_interfaces = self.params.get("host_interfaces", default="").split(",") if not self.host_interfaces: self.cancel("user should specify host interfaces") smm = SoftwareManager() if distro.detect().name == 'Ubuntu': pkg = 'iputils-ping' else: pkg = 'iputils' if not smm.check_installed(pkg) and not smm.install(pkg): self.cancel("Package %s is needed to test" % pkg) self.peer_ips = self.params.get("peer_ips", default="").split(",") interfaces = netifaces.interfaces() for self.host_interface in self.host_interfaces: if self.host_interface not in interfaces: self.cancel("interface is not available") self.count = self.params.get("count", default="1000")
def setUp(self): ''' To check and install dependencies for the test ''' smm = SoftwareManager() pkgs = ["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() self.iface = self.params.get("interface") if self.iface not in interfaces: self.cancel("%s interface is not available" % self.iface) self.peer = self.params.get("peer_ip", default="") if self.peer == "": self.cancel("peer ip should specify in input") self.user = self.params.get("user_name", default="root")
def setUp(self): """ Set up. """ self.iface = self.params.get("interface", default="") self.count = self.params.get("count", default="500") self.peer_ip = self.params.get("peer_ip", default="") self.drop = self.params.get("drop_accepted", default="10") # Check if interface exists in the system interfaces = netifaces.interfaces() if self.iface not in interfaces: self.cancel("%s interface is not available" % self.iface) if not self.peer_ip: self.cancel("peer ip should specify in input") # Install needed packages smm = SoftwareManager() if not smm.check_installed("tcpdump") and not smm.install("tcpdump"): self.cancel("Can not install tcpdump")
def get_interfaces(ignore_local=True): """ Retrieves the address of all external interfaces (lo 127.0.0.1 ignored) :return: List of tuples (interface, addr) """ interfaces = netifaces.interfaces() if_ext = [] for i in interfaces: if i == 'lo' and ignore_local: continue iface = netifaces.ifaddresses(i).get(netifaces.AF_INET) if iface: for j in iface: if_ext.append((i, j['addr'], j['netmask'])) return if_ext
def get_broadcast_addr_list(): import netifaces interfaces = [netifaces.ifaddresses(interface) for interface in netifaces.interfaces() ] bcast = [af_inet_info['broadcast'] if 'broadcast' in af_inet_info else af_inet_info['peer'] for interface in interfaces if netifaces.AF_INET in interface for af_inet_info in interface[netifaces.AF_INET] ] print('Broadcast address list:', bcast) return ' '.join(bcast)
def get_netifaces_addresses(): '''Get a list of addresses + broadcast using netifaces Yields (address, broadcast_address) ''' if netifaces is None: raise RuntimeError('netifaces unavailable') for iface in netifaces.interfaces(): interface = netifaces.ifaddresses(iface) if netifaces.AF_INET in interface: for af_inet_info in interface[netifaces.AF_INET]: addr = af_inet_info.get('addr', None) peer = af_inet_info.get('peer', None) broadcast = af_inet_info.get('broadcast', None) if addr is not None and broadcast is not None: yield (addr, broadcast) elif peer is not None and broadcast is not None: yield (peer, broadcast) elif addr is not None: yield (addr, addr) elif peer is not None: yield (peer, peer)
def ip(self, interface_name): """ interface: str, Interface Name return: List [{'broadcast': '10.100.0.255', 'addr': '10.100.0.164', 'netmask': '255.255.255.0'}] """ interface_check = self.interfaces if not interface_name in interface_check: raise WrongInterfaceName("Wrong Interface Name %s" % interface_name) addrs = netifaces.ifaddresses(interface_name) try: return addrs[netifaces.AF_INET] except KeyError: raise NotValidInterfaceName("Not valid interface name or may be virtual interface name %s" % interface_name)
def is_up(self, interface_name): ''' Return True if the interface is up, False otherwise. ''' interface_check = self.interfaces if not interface_name in interface_check: raise WrongInterfaceName("Wrong Interface Name %s" % interface_name) ifname = interface_name.encode(encoding='UTF-8') # Get existing device flags ifreq = struct.pack('16sh', ifname, 0) flags = struct.unpack('16sh', fcntl.ioctl(self.sock, SIOCGIFFLAGS, ifreq))[1] # Set new flags if flags & IFF_UP: return True else: return False
def netmask(self, interface_name, netmask): """ Checking interface first, if interface name found in Get().interfaces() validating Ipv4. After that applied ip address to interace interface_name = Applied Interface netmask = New netmask ip address """ interface_check = Get().interfaces valid_ipv4 = validators.ipv4(netmask) if not interface_name in interface_check: raise WrongInterfaceName("Wrong Interface Name %s" % interface_name) elif not valid_ipv4 is True: raise NotValidIPv4Address("Not Valid IPv4 Address %s" % netmask) else: prefix_len = self.get_net_size(netmask.split('.')) ifname = interface_name.encode(encoding='UTF-8') netmask = ctypes.c_uint32(~((2 ** (32 - prefix_len)) - 1)).value nmbytes = socket.htonl(netmask) ifreq = struct.pack('16sH2sI8s', ifname, AF_INET, b'\x00'*2, nmbytes, b'\x00'*8) fcntl.ioctl(self.sock, SIOCSIFNETMASK, ifreq)
def teardown_tunnels(self, tunnels, work_dir, config_file): """Function destroys the created tunnels Args: tunnels : list of existing tunnels work_dir : working directory path where the configuration files are located config_file : name of the honeypot configuration file """ logging.debug('Destroying tunnel interfaces.') config_file_location = os.path.join(work_dir, config_file) parser = ConfigParser() parser.read(config_file) try: tunnel_id = int(parser.getint("tunnel", "startid")) except (NoSectionError, NoOptionError): logger.error('Error: Incomplete honeyd.cfg configuration.') sys.exit(1) for i in range(0, len(tunnels)): tunnel_id += 1 name = 'tun' + str(tunnel_id) subprocess.Popen(['ip', 'link', 'set', name, 'down']) subprocess.Popen(['ip', 'tunnel', 'del', name]) for mode in ['ipip', 'ip_gre']: subprocess.Popen(['modprobe', '-r', mode])
def unhandled_exception(greenlet, expected_args): """Function cleans up after a greenlet dies unexpectedly Args: greenlet : object that died expected_args : list of arguments required for clean up """ tunnels, config, arp_daemon, web_server = expected_args logger.error('Error: Stopping honeypot: %s is dead: %s', greenlet, greenlet.exception) logger.info('Closing tunnel interfaces: %s', tunnels) Builder().teardown_tunnels(tunnels, package_directory, config) if arp_daemon: logging.info('Terminating arpd daemon.') arp_daemon.kill() if web_server: logging.info('Terminating web server.') web_server.kill() sys.exit(1)
def build_commands(self): # get additional options from the config file mode = self.config.get_collector_custom_data()["interfaces"]["mode"] ifaces = self.config.get_collector_custom_data()["interfaces"]["interfaces"] if mode == "inclusive": self.interfaces = ifaces else: self.interfaces = [iface for iface in netifaces.interfaces() if iface not in ifaces] # build commands for iface in self.interfaces: out_file_name = definitions.TIMESTAMP_PLACEHOLDER + "_" + iface self.output_filenames.append(out_file_name) out_file_path = os.path.join(self.output_dir, out_file_name + ".pcap") cmd = "dumpcap " \ + "-i " + str(iface) + " " \ + "-w " + str(out_file_path) self.commands.append(cmd)