Python netifaces 模块,gateways() 实例源码

我们从Python开源项目中,提取了以下33个代码示例,用于说明如何使用netifaces.gateways()

项目:centos-base-consul    作者:zeroc0d3lab    | 项目源码 | 文件源码
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
项目:packet-queue    作者:google    | 项目源码 | 文件源码
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)
项目:deb-oslo.utils    作者:openstack    | 项目源码 | 文件源码
def _get_my_ipv4_address():
    """Figure out the best ipv4
    """
    LOCALHOST = '127.0.0.1'
    gtw = netifaces.gateways()
    try:
        interface = gtw['default'][netifaces.AF_INET][1]
    except (KeyError, IndexError):
        LOG.info(_LI('Could not determine default network interface, '
                     'using 127.0.0.1 for IPv4 address'))
        return LOCALHOST

    try:
        return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
    except (KeyError, IndexError):
        LOG.info(_LI('Could not determine IPv4 address for interface %s, '
                     'using 127.0.0.1'),
                 interface)
    except Exception as e:
        LOG.info(_LI('Could not determine IPv4 address for '
                     'interface %(interface)s: %(error)s'),
                 {'interface': interface, 'error': e})
    return LOCALHOST
项目:Cayenne-Agent    作者:myDevicesIoT    | 项目源码 | 文件源码
def GetNetworkId():
        ip = None
        network = None
        returnValue = {}
        try:
            import netifaces
            gws=netifaces.gateways()
            defaultNet = gws['default'].values()
            for key, val in defaultNet:
               ip = key
               network = val
            command = 'arp -n ' + ip + ' | grep ' + network + ' | awk \'{print $3}\''
            (output, retCode) = ServiceManager.ExecuteCommand(command)
            if int(retCode) > 0:
                return None
            returnValue['Ip'] = ip
            returnValue['Network'] = network
            returnValue['MAC'] = output.strip()
            del output
        except Exception as ex:
            debug('Could not initialize netifaces module: ' + str(ex))
        return returnValue

#{'stats': {'updated': 75, 'noise': 0, 'quality': 67, 'level': 213}, 'Frequency': b'2.412 GHz', 'Access Point': b'B8:55:10:AC:8F:D8', 'Mode': b'Master', 'Key': b'off', 'BitRate': b'54 Mb/s', 'ESSID': b'SRX-WR300WH'}
项目:raw-packet    作者:Vladimir-Ivanov-Git    | 项目源码 | 文件源码
def get_mac(iface, ip):
        gw_ip = ""
        gws = gateways()
        for gw in gws.keys():
            try:
                if str(gws[gw][AF_INET][1]) == iface:
                    gw_ip = str(gws[gw][AF_INET][0])
            except IndexError:
                if str(gws[gw][0][1]) == iface:
                    gw_ip = str(gws[gw][0][0])
        try:
            alive, dead = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), iface=iface, timeout=10, verbose=0)
            return str(alive[0][1].hwsrc)
        except IndexError:
            try:
                alive, dead = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=gw_ip), iface=iface, timeout=10, verbose=0)
                return str(alive[0][1].hwsrc)
            except:
                return "ff:ff:ff:ff:ff:ff"
        except:
            return "ff:ff:ff:ff:ff:ff"
项目:automatic-repo    作者:WZQ1397    | 项目源码 | 文件源码
def get_local_ip_address():
    import os
    import sys

    try:
        import netifaces
    except ImportError:
        try:
            command_to_execute = "pip install netifaces || easy_install netifaces"
            os.system(command_to_execute)
        except OSError:
            print "Can NOT install netifaces, Aborted!"
            sys.exit(1)
        import netifaces

    routingIPAddr = '127.0.0.1'

    for interface in netifaces.interfaces():
        if interface == netifaces.gateways()['default'][netifaces.AF_INET][1]:
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
            except KeyError:
                pass
    return routingIPAddr
项目:dotfiles    作者:gbraad    | 项目源码 | 文件源码
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
项目:maas    作者:maas    | 项目源码 | 文件源码
def get_default_gateway_ip():
    """Return the default gateway IP."""
    gateways = netifaces.gateways()
    defaults = gateways.get('default')
    if not defaults:
        return

    def default_ip(family):
        gw_info = defaults.get(family)
        if not gw_info:
            return
        addresses = netifaces.ifaddresses(gw_info[1]).get(family)
        if addresses:
            return addresses[0]['addr']

    return default_ip(netifaces.AF_INET) or default_ip(netifaces.AF_INET6)
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def get_local_ip_address():
    import os
    import sys

    try:
        import netifaces
    except ImportError:
        try:
            command_to_execute = "pip install netifaces || easy_install netifaces"
            os.system(command_to_execute)
        except OSError:
            print "Can NOT install netifaces, Aborted!"
            sys.exit(1)
        import netifaces

    routingIPAddr = '127.0.0.1'

    for interface in netifaces.interfaces():
        if interface == netifaces.gateways()['default'][netifaces.AF_INET][1]:
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
            except KeyError:
                pass
    return routingIPAddr
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def get_ip_address_external():
    import os
    import sys

    try:
        import netifaces
    except ImportError:
        try:
            command_to_execute = "pip install netifaces || easy_install netifaces"
            os.system(command_to_execute)
        except OSError:
            print "Can NOT install netifaces, Aborted!"
            sys.exit(1)
        import netifaces

    routingIPAddr = '127.0.0.1'

    for interface in netifaces.interfaces():
        if interface == netifaces.gateways()['default'][netifaces.AF_INET][1]:
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
            except KeyError:
                pass
    return routingIPAddr
项目:Legion    作者:MooseDojo    | 项目源码 | 文件源码
def getLocalIP():
    default_iface = netifaces.gateways()['default'][netifaces.AF_INET][1]
    default_data = netifaces.ifaddresses(default_iface).setdefault(netifaces.AF_INET, [{'addr':'No IP addr'}])
    for i in default_data:
        return (i['addr'])
项目:raiden    作者:raiden-network    | 项目源码 | 文件源码
def map_none(self):
        if self.source_ip == '0.0.0.0':
            try:
                default_gw_if = netifaces.gateways()['default'][netifaces.AF_INET][1]
                self.source_ip = netifaces.ifaddresses(default_gw_if)[netifaces.AF_INET][0]['addr']
            except (OSError, IndexError, KeyError):
                log.critical("Couldn't get interface address. "
                             "Try specifying with '--nat ext:<ip>'.")
                raise
        log.warning('Using internal interface address. Connectivity issues are likely.')
        return PortMappedSocket(self.socket, 'NONE', self.source_ip, self.source_port)
项目:tools    作者:apertoso    | 项目源码 | 文件源码
def get_db_host():
    # first try to look for a loopback alias addr
    loopback_addr = get_lo_alias_addr()
    if loopback_addr:
        return loopback_addr

    # if we did not find any IP on the loopback if, find the
    # interface of the default gateway and use that.
    try:
        default_if = netifaces.gateways().get('default', {}).values()[0][1]
        if_addr = netifaces.ifaddresses(default_if)[netifaces.AF_INET][0].get(
            'addr')
        return if_addr
    except KeyError:
        raise Exception('Cannot find DB address for the current host')
项目:networkzero    作者:tjguk    | 项目源码 | 文件源码
def _find_ip4_addresses():
    """Find all the IP4 addresses currently bound to interfaces
    """
    global _ip4_addresses
    proto = socket.AF_INET
    if _ip4_addresses is None:
        _ip4_addresses = []

        #
        # Determine the interface for the default gateway
        # (if any) and, later, prioritise the INET address on
        # that interface.
        #
        default_gateway = netifaces.gateways()['default']
        if proto in default_gateway:
            _, default_gateway_interface = default_gateway[proto]
        else:
            default_gateway_interface = None

        for interface in netifaces.interfaces():
            for info in netifaces.ifaddresses(interface).get(netifaces.AF_INET, []):
                if info['addr']:
                    if interface == default_gateway_interface:
                        _ip4_addresses.insert(0, info['addr'])
                    else:
                        _ip4_addresses.append(info['addr'])

    return _ip4_addresses
项目:psystem    作者:gokhanm    | 项目源码 | 文件源码
def default_gateway(self):
        """
            Default Interface Gateway
            Return: tuple
        """
        gws = netifaces.gateways()

        try:
            return gws['default'][netifaces.AF_INET]
        except KeyError:
            return gws['default'][netifaces.AF_INET6]
项目:psystem    作者:gokhanm    | 项目源码 | 文件源码
def all_gateways(self):
        """
            List of gateways on machine.
            Return: dict
        """
        return netifaces.gateways()
项目:Python-Penetration-Testing-for-Developers    作者:PacktPublishing    | 项目源码 | 文件源码
def get_gateways():
    gateway_dict = {}
    gws = netifaces.gateways()
    for gw in gws:
        try:
            gateway_iface = gws[gw][netifaces.AF_INET]
            gateway_ip, iface = gateway_iface[0], gateway_iface[1]
            gw_list =[gateway_ip, iface]
            gateway_dict[gw]=gw_list
        except:
            pass
    return gateway_dict
项目:Python-Penetration-Testing-for-Developers    作者:PacktPublishing    | 项目源码 | 文件源码
def get_networks(gateways_dict):
    networks_dict = {}
    for key, value in gateways.iteritems():
        gateway_ip, iface = value[0], value[1]
        hwaddress, addr, broadcast, netmask = get_addresses(iface)
        network = {'gateway': gateway_ip, 'hwaddr' : hwaddress, 'addr' : addr, '                                                                                        broadcast' : broadcast, 'netmask' : netmask}
        networks_dict[iface] = network
    return networks_dict
项目:Python-Penetration-Testing-for-Developers    作者:PacktPublishing    | 项目源码 | 文件源码
def get_gateways():
    gateway_dict = {}
    gws = netifaces.gateways()
    for gw in gws:
        try:
            gateway_iface = gws[gw][netifaces.AF_INET]
            gateway_ip, iface = gateway_iface[0], gateway_iface[1]
            gw_list =[gateway_ip, iface]
            gateway_dict[gw]=gw_list
        except:
            pass
    return gateway_dict
项目:Python-Penetration-Testing-for-Developers    作者:PacktPublishing    | 项目源码 | 文件源码
def get_networks(gateways_dict):
    networks_dict = {}
    for key, value in gateways.iteritems():
        gateway_ip, iface = value[0], value[1]
        hwaddress, addr, broadcast, netmask = get_addresses(iface)
        network = {'gateway': gateway_ip, 'hwaddr' : hwaddress, 'addr' : addr, 'broadcast' : broadcast, 'netmask' : netmask}
        networks_dict[iface] = network
    return networks_dict
项目:Python-Penetration-Testing-for-Developers    作者:PacktPublishing    | 项目源码 | 文件源码
def get_gateways():
    gateway_dict = {}
    gws = netifaces.gateways()
    for gw in gws:
        try:
            gateway_iface = gws[gw][netifaces.AF_INET]
            gateway_ip, iface = gateway_iface[0], gateway_iface[1]
            gw_list =[gateway_ip, iface]
            gateway_dict[gw]=gw_list
        except:
            pass
    return gateway_dict
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def _get_local_netinfo(iface):
    ifconfig = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]
    ifconfig['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
    ip = ipaddress.ip_interface(u'%s/%s' % (ifconfig['addr'], ifconfig['netmask']))
    ifconfig['network'] = str(ip.network.network_address)
    ifconfig['iface'] = iface

    return ifconfig
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def get_local_netinfo(iface=None):
    if not iface:
        try:
            iface = netifaces.gateways()['default'][netifaces.AF_INET][1]
        except (KeyError, IndexError):
            raise OSError('Main network interface was not found')

    if iface not in netifaces.interfaces():
        raise ValueError('Network interface "%s" is not available on this system' % iface)

    try:
        return _get_local_netinfo(iface)
    except (KeyError, IndexError):
        raise OSError('Network information for interface "%s" is not available' % iface)
项目:wifimitm    作者:mvondracek    | 项目源码 | 文件源码
def gateway(self):
        """
        Get current default gateway.
        """
        gateway = None
        gws = netifaces.gateways()
        for gw in gws[netifaces.AF_INET]:
            if gw[1] == self.name:
                gateway = gw[0]
                break
        assert gateway, 'No default gateway available.'
        return gateway
项目:netattack2    作者:chrizator    | 项目源码 | 文件源码
def __init__(self, interface):
        self.interface = interface
        self.hosts = {}
        self.advanced_scan = False
        try:
            self.local_ip = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
        except KeyError:
            self.local_ip = raw_input("\n{R}ERROR: Unable to retrieve local IP address\n{N}Please enter manually: ".format(R=RED, N=NORMAL))
        try:
            self.gateway_ip = netifaces.gateways()["default"][netifaces.AF_INET][0]
        except KeyError:
            self.gateway_ip = raw_input("\n{R}ERROR: Unable to retrieve gateway IP address\n{N}Please enter manually: ".format(R=RED, N=NORMAL))
项目:netattack2    作者:chrizator    | 项目源码 | 文件源码
def get_gateway_ip():
    # get the 'default' gateway

    try:
        return netifaces.gateways()['default'][netifaces.AF_INET][0]
    except KeyError:
        print("\n{R}ERROR: Unable to retrieve gateway IP address.\n{N}".format(R=RED, N=NORMAL))
        return raw_input("Please enter gateway IP address manually: ")
项目:WMD    作者:ThomasTJdev    | 项目源码 | 文件源码
def getGateway():
    """Get gateway address."""
    gws = netifaces.gateways()
    gateway = gws['default'][netifaces.AF_INET]
    logger.debug('Returning gateway')
    return gateway[0]
项目:voltha    作者:opencord    | 项目源码 | 文件源码
def _get_my_primary_interface():
    gateways = ni.gateways()
    assert 'default' in gateways, \
        ("No default gateway on host/container, "
         "cannot determine primary interface")
    default_gw_index = gateways['default'].keys()[0]
    # gateways[default_gw_index] has the format (example):
    # [('10.15.32.1', 'en0', True)]
    interface_name = gateways[default_gw_index][0][1]
    return interface_name
项目:sdnpwn    作者:smythtech    | 项目源码 | 文件源码
def run(params): 
  global verbose

  verbose = False
  testMethod = "arp"
  dstIP = ""
  count = 10
  interval = 1

  if("-m" in params):
    testMethod = (params[params.index("-m")+1]).lower()
  if("-t" in params):
    dstIP = params[params.index("-t")+1]
  if("-i" in params):
    interval = float(params[params.index("-i")+1])
  if("-c" in params):
    count = int(params[params.index("-c")+1])
  if("-v" in params):
    verbose = True

  if(dstIP == ""):
    sdnpwn.message("No target given, using default gateway", sdnpwn.NORMAL)
    try:
      dstIP = netifaces.gateways()['default'][netifaces.AF_INET][0]
    except:
      sdnpwn.message("Could not determine gateway address. Please specify a target using the -t option.", sdnpwn.ERROR)
      return
    sdnpwn.message("Default gateway detected as " + dstIP, sdnpwn.NORMAL)

  try:
    if(testForSDN(testMethod, dstIP, count, interval)):
      sdnpwn.message("SDN detected!", sdnpwn.SUCCESS)
    else:
      sdnpwn.message("SDN not detected", sdnpwn.WARNING)
  except PermissionError as e:
    sdnpwn.message("Needs root!", sdnpwn.ERROR)
项目:sdnpwn    作者:smythtech    | 项目源码 | 文件源码
def getDefaultGatewayIPAddress():
  return netifaces.gateways()['default'][netifaces.AF_INET][0]
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def getLocalIP():
    import netifaces
    routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]
    for interface in netifaces.interfaces():
        if interface == routingNicName:
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
                return interface, routingIPAddr
            except KeyError:
                pass
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def get_local_ip_address():
    import netifaces
    routingIPAddr = '127.0.0.1'
    for interface in netifaces.interfaces():
        if interface == netifaces.gateways()['default'][netifaces.AF_INET][1]:
            try:
                routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
            except KeyError:
                pass
    return routingIPAddr
项目:SonOTA    作者:mirko    | 项目源码 | 文件源码
def defaultinterface():
    '''The interface the default gateway is on, if there is one.'''
    try:
        return netifaces.gateways()['default'][netifaces.AF_INET][1]
    except:
        return None