当前位置: 首页>>代码示例>>Python>>正文


Python netifaces.interfaces函数代码示例

本文整理汇总了Python中netifaces.interfaces函数的典型用法代码示例。如果您正苦于以下问题:Python interfaces函数的具体用法?Python interfaces怎么用?Python interfaces使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了interfaces函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __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

示例2: ap_vlan_iface_test_and_prepare_environ

def ap_vlan_iface_test_and_prepare_environ():
    ifaces = netifaces.interfaces()
    if "dummy0" in ifaces:
        raise Exception("dummy0 already exists before")
    ifaces = netifaces.interfaces()
    if "dummy0.1" in ifaces:
        raise Exception("dummy0.1 already exists before")

    subprocess.call(['ip', 'link', 'add', 'dummy0', 'type', 'dummy'])
    subprocess.call(['ifconfig', 'dummy0', 'up'])

    ifaces = netifaces.interfaces()
    if not("dummy0" in ifaces):
        raise HwsimSkip("failed to add dummy0 - missing kernel config DUMMY ?")

    subprocess.call(['ip', 'link', 'add', 'link', 'dummy0', 'name', 'dummy0.1',
                     'type', 'vlan', 'id', '1'])

    ifaces = netifaces.interfaces()
    if not("dummy0.1" in ifaces):
        raise HwsimSkip("failed to add dummy0.1 - missing kernel config VLAN_8021Q ?")

    subprocess.call(['ip', 'link', 'del', 'dummy0.1'])

    ifaces = netifaces.interfaces()
    if "dummy0.1" in ifaces:
        raise Exception("dummy0.1 was not removed before testing")
开发者ID:cococorp,项目名称:hostap-upstream,代码行数:27,代码来源:test_ap_vlan.py

示例3: run_ap

    def run_ap(self):
        run_program("killall airbase-ng hostapd")
        time.sleep(4)

        # Make sure interface exists
        if self.wlan_iface not in netifaces.interfaces():
            logging.error("No such interface: '%s'" % self.wlan_iface)
            if not self.hostapd:
                return False
        proc = run_program(self.airb_cmd)
        if proc.poll():
            logging.error("Airbase has terminated. Cannot continue.")
            return False

        # Wait for airbase self.rogueif interface to come up
        while self.rogueif not in netifaces.interfaces(): #Should add a timeout
            logging.debug("Waiting for airbase interface to come up.")
            time.sleep(1)

        self.procs['airbase'] = proc
        logging.debug("Airbase interface is up. Setting IP...")
        run_program(self.set_ip_cmd)

        # Wait for IP to be set
        ipSet = False
        while not ipSet:
            try:
                if netifaces.ifaddresses(self.rogueif)[2][0]['addr']:
                    ipSet = True
            except Exception:
                time.sleep(2)
                pass

        logging.info("IP address for access point has been set.")
        return True
开发者ID:ProGamerGov,项目名称:snoopy-ng,代码行数:35,代码来源:rogee.py

示例4: 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

示例5: __init__

    def __init__(self, args):
        super(CommonComputeSetup, self).__init__()
        self._args = args

        # Using keystone admin password for nova/neutron if not supplied
        if not self._args.neutron_password:
            self._args.neutron_password = self._args.keystone_admin_password

        self.multi_net = False
        if self._args.non_mgmt_ip:
            self.multi_net = True
            self.vhost_ip = self._args.non_mgmt_ip
        else:
            self.vhost_ip = self._args.self_ip

        self.dev = None  # Will be physical device
        if self._args.physical_interface:
            # During re-provision/upgrade vhost0 will be present
            # so vhost0 should be treated as dev,
            # which is used to get netmask/gateway
            if 'vhost0' in netifaces.interfaces():
                self.dev = 'vhost0'
            # During intial provision actual interface should be treated as dev
            # which is used to get netmask/gateway
            elif self._args.physical_interface in netifaces.interfaces():
                self.dev = self._args.physical_interface
            else:
                raise KeyError('Interface %s in present' %
                               self._args.physical_interface)
        else:
            # Get the physical device and provision status
            # if reprov is False, it means fresh install
            #              True,  it means reprovision
            (self.dev, self.reprov) = self.get_device_info(self.vhost_ip)
开发者ID:Juniper,项目名称:contrail-controller,代码行数:34,代码来源:common.py

示例6: ip_relay_callback

def ip_relay_callback(packet):
	ether_dst = packet.sprintf("%Ether.dst%")
	ether_src = packet.sprintf("%Ether.src%")
	ip_src = packet.sprintf("%IP.src%")
	ip_dst = packet.sprintf("%IP.dst%")
	if ARP in packet:
		arp_p = ARP_POISION()
		arp_p.send_poision()
	else:
	#packet[IP].chksum = ""
	#packet.show()
		ni.interfaces()
		gate_addr = ni.gateways()['default'][2][0]
		my_mac = ni.ifaddresses('eth0')[ni.AF_LINK][0]['addr']
		target_addr = sys.argv[1]
		if packet[IP].src == target_addr  :
			packet[Ether].dst=global_gate_mac
			packet[Ether].src=my_mac
			if packet.haslayer(UDP):
				del packet[UDP].chksum	
				del packet[UDP].len
			del packet.chksum
			del packet.len
			sendp(packet, verbose=False)
		elif packet[IP].dst == target_addr  :
			packet[Ether].dst=global_target_mac
			packet[Ether].src=my_mac
			if packet.haslayer(UDP):
				del packet[UDP].chksum	
				del packet[UDP].len
			del packet.chksum
			del packet.len
			sendp(packet, verbose=False)
	return 
开发者ID:kcatss,项目名称:network-3,代码行数:34,代码来源:arp_spoof.py

示例7: __init__

	def __init__(self):
		self.ETHER_BROAD = "ff:ff:ff:ff:ff:ff"
		self.ARP_BROAD = "00:00:00:00:00:00"
		self.ETHER_PROTOCOL = 0x0806
		self.ARP_HARDWARE = 1
		self.ARP_PROTOCOL = 0x0800
		self.ARP_H_SIZE = 6
		self.ARP_PROTOCOL_SIZE = 4
		self.ARP_REQUEST = 1
		self.ARP_REPLY = 2
		#self.ARP_REPLY = ARP.is_at
		self.gate_addr = ""
		self.my_mac = ""
		self.my_addr = ""
		self.target_mac = ""
		self.gate_mac = ""
		self.target_addr = sys.argv[1]	
		self.mal_list=list()

		self.get_mal_site()
		ni.interfaces()
		self.get_my_mac()
		self.get_my_addr()
		self.get_gate_addr()	
		self.get_gate_mac()	
		self.get_target_mac()
开发者ID:kcatss,项目名称:network-4,代码行数:26,代码来源:mal_site.py

示例8: get_addrs_windows

def get_addrs_windows():
	ret = {}

	# TODO: this is the only way i know to list ipv4 addresses :-(
	for interface in netifaces.interfaces():
		addrs = netifaces.ifaddresses(interface)
		for addr in addrs:
			if not netifaces.AF_INET in addrs: continue
			for addr in addrs[netifaces.AF_INET]:
				a = addr['addr']
				if not 'inet' in ret:
					ret['inet'] = set()
				ret['inet'].add(a)

	lines = call('netsh interface ipv6 show address')

	for line in lines.split('\n'):
		if 'Temporary' in line: continue

		for word in line.split():
			word = word.strip().lower()

			# TODO: hackish but works
			try:
				a = ipaddress.IPv6Address(word)
			except:
				continue

			###if not ':' in word: continue
			###if not word.startswith('200'): continue

			if not 'inet6' in ret: ret['inet6'] = set()
			ret['inet6'].add(word)

	# disable ether for now
	'''
	lines = call('ipconfig /all')
	for word in lines.split():
		word = word.strip().lower()
		###if not re.match('..-..-..-..-..-..', word): continue

		word = word.replace('-', ':')

		if not 'ether' in ret: ret['ether'] = set()
		ret['ether'].add(word)
	'''

	# TODO: this is the only way i know to list ethernet addresses :-(
	for interface in netifaces.interfaces():
		addrs = netifaces.ifaddresses(interface)
		for addr in addrs:
			if not -1000 in addrs: continue
			for addr in addrs[-1000]:
				a = addr['addr']
				if not a: continue
				if not 'ether' in ret: ret['ether'] = set()
				ret['ether'].add(a)

	return ret
开发者ID:rpodgorny,项目名称:faddnsc,代码行数:59,代码来源:__init__.py

示例9: get_iface

def get_iface(protocol=None):
    if protocol == "IPv6":
        for iface in netifaces.interfaces():
            addrs = netifaces.ifaddresses(iface)
            for addr in addrs.get(netifaces.AF_INET6, []):
                print "%-8s %s" % (iface, addr["addr"])
    else:
        for iface in netifaces.interfaces():
            addrs = netifaces.ifaddresses(iface)
            for addr in addrs.get(netifaces.AF_INET, []):
                print "%-8s %s" % (iface, addr["addr"])
开发者ID:mattjorgs,项目名称:speedtest,代码行数:11,代码来源:interfaces.py

示例10: handle_ip_address_provision

def handle_ip_address_provision(req):
    global ip
    if req.ip_address_request == 'all_interfaces':
      print "Returning list of all interfaces: %s"%(ni.interfaces())
      return ';'.join(e for e in ni.interfaces())
    elif req.ip_address_request == 'local_ip':
      findValidIPAddress()
      print "Returning IP Address: [%s]"%(ip)
      return IPAddressServiceResponse(ip)
    else:
      return '127.0.0.1'
开发者ID:aniskoubaa,项目名称:ROSWebServices,代码行数:11,代码来源:ip_address_service.py

示例11: _listen

def _listen():
    try:
        # socket used for MULTI
        s = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, NETLINK_GENERIC)
        s.bind((0, 1)) # bind to group 1 (MULTI group, temporary)
        
        # socket used for IOCTL
        s_ioctl = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        nlmsg = struct_nlmsg()
        
        try:
            global _multi_dict
            _multi_dict.clear()
            
            global _stop
            while not _stop:
                numbytes = s.recv_into(nlmsg, sizeof(struct_nlmsg))
                multimsg = struct_multimsg.from_address(addressof(nlmsg.data))
                devname  = _get_interface_name(s_ioctl, multimsg.idx)
                
            #    #ethX: ICE it should be always UP
            #    #double check
            #    #route add 128...13 gw 192.168.0.1 eth1
            #    #route add 128...52 gw 192.168.0.1 eth1
            #    eth_ifaces = [ ethiface for ethiface in netifaces.interfaces() if ETHFACE in ethiface ]
            #    if eth_ifaces.index(eth_ifaces[0]) >= 0:
            #        _multi_dict[eth_ifaces[0]] = 'UP'
            #    else:
            #        _multi_dict[eth_ifaces[0]] = 'DOWN'
                
                if 'ppp' in devname:
                    ppp_ifaces = [ iface for iface in netifaces.interfaces() if 'ppp' in iface ]
                    if ppp_ifaces.index(devname) >= 0: # is it an actual device?
                        if multimsg.state == LINK_UP:
                            _multi_dict[devname] = 'UP'
                        else:
                            _multi_dict[devname] = 'DOWN'
                
                if 'wlan' in devname:
                    wlan_ifaces = [ iface for iface in netifaces.interfaces() if 'wlan' in iface ]
                    if wlan_ifaces.index(devname) >= 0: # is it an actual device?
                        if multimsg.state == LINK_UP:
                            _multi_dict[devname] = 'UP'
                        else:
                            _multi_dict[devname] = 'DOWN'
            
        finally:
            s_ioctl.close()
            s.close()
        
    finally:
        global _thread
        _thread = None # signals that this thread has ended
开发者ID:grungerambow,项目名称:test,代码行数:53,代码来源:interfaceinfo.py

示例12: _startKademlia

    def _startKademlia(self):
        possible_interfaces = [iface for iface in netifaces.interfaces() if iface_searchterm in iface
                               and netifaces.ifaddresses(iface).has_key(netifaces.AF_INET)]
        if len(possible_interfaces) == 0:
            logging.error("No suitable interfaces found, tried the following: %s"%netifaces.interfaces())
        logging.debug("Interfaces: %s"%netifaces.ifaddresses(possible_interfaces[0]))
        ipAddr = netifaces.ifaddresses(possible_interfaces[0])[netifaces.AF_INET][0]["addr"]
        logging.debug("Node %s starts with %s on %s"%(self.name, self.peerlist, ipAddr))

        self.kademliaServer.listen(self.port, interface=ipAddr)
        serverDeferred = self.kademliaServer.bootstrap([(peer, emu_config.kademlia_default_port) for peer in self.peerlist])
        serverDeferred.addCallback(self.executeBot)
        serverDeferred.addErrback(self.errback)
开发者ID:icehawk1,项目名称:GameoverZeus,代码行数:13,代码来源:User.py

示例13: __init__

 def __init__(self):
     """Initialize
     """
     ##Name of interfaces
     self.names = []
     oldi = netifaces.interfaces()
     os.system("ip link add type veth")
     newi = netifaces.interfaces()
     for i in newi:
         if (i not in oldi):
             self.names.append(i)
     output.dbg("Created virtual interfaces "+str(self.names),
                self.__class__.__name__)
开发者ID:sharifelshenawy,项目名称:yapc,代码行数:13,代码来源:netintf.py

示例14: get_private_ips

def get_private_ips():
    ifaces = netifaces.interfaces()
    inet_ifaces = [
        netifaces.ifaddresses(i)[netifaces.AF_INET]
        for i in netifaces.interfaces()
        if netifaces.AF_INET in netifaces.ifaddresses(i)
    ]
    ips = []
    for i in inet_ifaces:
        for j in i:
            if not j["addr"].startswith("127"):
                ips.append(j["addr"])
    return ips
开发者ID:shaddi,项目名称:findthatbox,代码行数:13,代码来源:findthatbox_client.py

示例15: get_ip_addr

def get_ip_addr(*args):
    """
        Code from : http://code.activestate.com/recipes/439094/
    """
    if platform.system()=='Linux':
        if 'enp4s0' in ni.interfaces():
            return ni.ifaddresses('enp4s0')[ni.AF_INET][0]['addr']
        elif 'eth0' in ni.interfaces():
            return ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
    elif platform.system()=='Windows':
        import socket
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(("8.8.8.8",80))
        return s.getsockname()[0]
开发者ID:balajisriram,项目名称:BCore,代码行数:14,代码来源:__init__.py


注:本文中的netifaces.interfaces函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。