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")
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()
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)
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)
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
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!')
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
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
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"])
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'
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
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
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__)
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)
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]
def run(self): print('Escolha a interface de rede a ser usada:') for i, val in enumerate(netifaces.interfaces()): print(i, '-', val) while True: print('Digite:') try: opt = int(sys.stdin.readline()) if opt >= len(netifaces.interfaces()) or opt < 0: raise Exception() except Exception: print('Entrada invalida') else: break self.myAddr = str(netifaces.ifaddresses(netifaces.interfaces()[opt])[2][0]['addr']) print('Utilizando o ip ', self.myAddr) while True: print('Defina um delay para o relógio(em ms):') try: self.delay = int(sys.stdin.readline()) if self.delay <= 0: raise Exception() except Exception: print('Entrada invalida') else: break Thread(target=self.clock).start() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(SERVER_ADDRESS) group = socket.inet_aton(MULTICAST_GROUP) mreq = struct.pack('4sL', group, socket.INADDR_ANY) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) inputs = [self.sock, sys.stdin] outputs = [] while True: print("Aguardando acao...") readable, writable, exceptional = select.select(inputs, outputs, inputs) for io in readable: if io == self.sock: self.handleUDPPacket(self.sock) elif io == sys.stdin: self.startBully(self.sock) sys.stdin.readline() if self.isCoord == True: self.startBerkeley(self.sock)
def test_host_interface_cleanup(driver): """Host interfaces are removed when their associated networks are destroyed. """ with sample_network(driver, "pub", public=True) as pub: with sample_node(driver, networks=[pub]): iface = pub.host_interface assert iface in netifaces.interfaces() assert iface in netifaces.interfaces() assert iface not in netifaces.interfaces() with sample_network(driver, "priv") as priv: with sample_node(driver, networks=[priv]): assert priv.host_interface is None
def add_ovsbridge_linuxbridge(name, bridge): ''' Add linux bridge to the named openvswitch bridge :param name: Name of ovs bridge to be added to Linux bridge :param bridge: Name of Linux bridge to be added to ovs bridge :returns: True if veth is added between ovs bridge and linux bridge, False otherwise''' try: import netifaces except ImportError: if six.PY2: apt_install('python-netifaces', fatal=True) else: apt_install('python3-netifaces', fatal=True) import netifaces ovsbridge_port = "veth-" + name linuxbridge_port = "veth-" + bridge log('Adding linuxbridge {} to ovsbridge {}'.format(bridge, name), level=INFO) interfaces = netifaces.interfaces() for interface in interfaces: if interface == ovsbridge_port or interface == linuxbridge_port: log('Interface {} already exists'.format(interface), level=INFO) return with open('/etc/network/interfaces.d/{}.cfg'.format( linuxbridge_port), 'w') as config: config.write(BRIDGE_TEMPLATE.format(linuxbridge_port=linuxbridge_port, ovsbridge_port=ovsbridge_port, bridge=bridge)) subprocess.check_call(["ifup", linuxbridge_port]) add_bridge_port(name, linuxbridge_port)
def _ip_local_host(ip_addr): """ This function will iterate over all interfaces on the system and compare their IP addresses with the one given as a parameter :param ip_addr: IP addr :type ip_addr: str :return int """ for intf in netifaces.interfaces(): addr_list_dict = netifaces.ifaddresses(intf) # Some interfaces have no address if addr_list_dict: # Some interfaces have no IPv4 address. if netifaces.AF_INET in addr_list_dict: inet_addr_list = addr_list_dict[netifaces.AF_INET] for value in inet_addr_list: if value['addr'] == ip_addr: return True if netifaces.AF_INET6 in addr_list_dict: inet_addr_list = addr_list_dict[netifaces.AF_INET6] for value in inet_addr_list: if value['addr'] == ip_addr: return True return False
def setUp(self): ''' check the availability of perftest package installed perftest package should be installed ''' sm = SoftwareManager() depends = ["openssh-clients", "perftest"] for pkg in depends: if not sm.check_installed(pkg) and not sm.install(pkg): self.skip("%s package is need to test" % pkg) interfaces = netifaces.interfaces() self.flag = self.params.get("ext_flag", default="0") self.IF = self.params.get("Iface", default="") self.PEER_IP = self.params.get("PEERIP", default="") if self.IF not in interfaces: self.skip("%s interface is not available" % self.IF) if self.PEER_IP == "": self.skip("%s peer machine is not available" % self.PEER_IP) self.CA = self.params.get("CA_NAME", default="mlx4_0") self.PORT = self.params.get("PORT_NUM", default="1") self.PEER_CA = self.params.get("PEERCA", default="mlx4_0") self.PEER_PORT = self.params.get("PEERPORT", default="1") self.to = self.params.get("timeout", default="600") self.tool_name = self.params.get("tool", default="") if self.tool_name == "": self.skip("should specify tool name") self.log.info("test with %s" % (self.tool_name)) self.test_op = self.params.get("test_opt", default="").split(",") self.ext_test_op = self.params.get("ext_opt", default="").split(",")
def test_collect_only_alive_interfaces(self): container = SystemContainer() container.discover_objects() os_obj = container.objects.values().pop() collector = SystemMetricsCollector(object=os_obj) collector.collect() collector.collect() # double collect is needed, because otherwise we do not collect metrics properly # get interfaces info all_interfaces = netifaces.interfaces() alive_interfaces = set() down_interfaces = set() for interface_name, interface in psutil.net_if_stats().iteritems(): if interface.isup: alive_interfaces.add(interface_name) else: down_interfaces.add(interface_name) # check collected_metrics = os_obj.statsd.current net_metrics_found = False for metric in collected_metrics['counter'].keys(): if metric.startswith('system.net.') and '|' in metric: net_metrics_found = True metric_name, label_name = metric.split('|') assert_that(all_interfaces, has_item(label_name)) assert_that(alive_interfaces, has_item(label_name)) assert_that(down_interfaces, not_(has_item(label_name))) assert_that(net_metrics_found, equal_to(True))
def _load_ips_netifaces(): """load ip addresses with netifaces""" import netifaces global LOCALHOST local_ips = [] public_ips = [] # list of iface names, 'lo0', 'eth0', etc. for iface in netifaces.interfaces(): # list of ipv4 addrinfo dicts ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, []) for entry in ipv4s: addr = entry.get('addr') if not addr: continue if not (iface.startswith('lo') or addr.startswith('127.')): public_ips.append(addr) elif not LOCALHOST: LOCALHOST = addr local_ips.append(addr) if not LOCALHOST: # we never found a loopback interface (can this ever happen?), assume # common default LOCALHOST = '127.0.0.1' local_ips.insert(0, LOCALHOST) local_ips.extend(['0.0.0.0', '']) LOCAL_IPS[:] = uniq_stable(local_ips) PUBLIC_IPS[:] = uniq_stable(public_ips)
def interface_addresses(family=netifaces.AF_INET): """Returns local addresses of any network associated with a local interface that has broadcast (and probably multicast) capability.""" return [addr['addr'] for i in netifaces.interfaces() for addr in netifaces.ifaddresses(i).get(family) or [] if 'broadcast' in addr]
def _list_network_interfaces(): interfaces = None if hasnetifaces == 1: interfaces = netifaces.interfaces() return interfaces
def pull(self): for interface in netifaces.interfaces(): interface_uri = self.uri_ref(interface) self.graph.add((interface_uri, RDF.type, T['Interface'])) self.graph.add((interface_uri, T['Name'], Literal(interface))) for t, addresses in netifaces.ifaddresses(interface).items(): classname = { 2 : 'IPv4Address', 17: 'MACAddress', 10: 'IPv6Address'}[t] for i, address in enumerate(addresses): address_uri = os.path.join(interface_uri, 'addresses', classname, str(i)) if t in [2,10]: self.graph.add((address_uri, RDF.type, T['IPAddress'])) version = { 2: '4', 10: '6' }[t] self.graph.add((address_uri, T['Version'], Literal(version))) self.graph.add((address_uri, T['Type'], Literal("IPv%s"%version))) elif t == 17: self.graph.add((address_uri, T['Type'], Literal('MAC'))) self.graph.add((address_uri, RDF.type, T[classname])) for k, v in address.items(): dataproperty = { 'addr' : 'Address', 'peer' : 'Peer', 'broadcast': 'Broadcast', 'netmask' : 'NetMask'}[k] self.graph.add((address_uri, T[dataproperty], Literal(v))) self.graph.add((address_uri, T['locates'], interface_uri)) self.graph.add((interface_uri, T['locatedAt'], address_uri))
def main(): #PORT = parametro de entrada global tabela lista_Interfaces = list() argumentos = sys.argv[1:] host_name = "" for i in xrange(len(argumentos)): if argumentos[i] == '-h': host_name = argumentos[i+1] tabela = route.router(host_name) for ifName in interfaces(): ifinfo = ifaddresses(ifName).setdefault(AF_INET)[0] addr = ifinfo['addr'] netmask = ifinfo['netmask'] aux = InterfacesInfo(ifinfo, addr, netmask) lista_Interfaces.append(aux) tabela.preenche_viz(lista_Interfaces) enviar = ThreadEnviaTabela() enviar.start() receber = ThreadRecebeTabela() receber.start()
def get_network_buoy_info(interface): """Returns info about the network and buoy in the given net interface.""" ret = {} n_info = netifaces.interfaces().get(interface) if n_info: """ AF_LINK: {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': 'a0:ce:c8:05:35:f9'}], AF_INET: 2: [{'broadcast': '10.172.203.255', 'netmask': '255.255.255.0', 'addr': '10.172.203.199'}], AF_INET6: 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::a2ce:c8ff:fe05:35f9%eth1'}]} """ # Get the addresses for the given interface ret['AF_INET'] = n_info.get(netifaces.AF_INET) # IPv4 ret['AF_INET6'] = n_info.get(netifaces.AF_INET6) # IPv6 ret['AF_LINK'] = n_info[netifaces.AF_LINK] # link layer interface """ {2: [('10.0.1.1', 'en0', True), ('10.2.1.1', 'en1', False)], 30: [('fe80::1', 'en0', True)], 'default': { 2: ('10.0.1.1', 'en0'), 30: ('fe80::1', 'en0') }} """ # Get the default gateways for IPv4 and IPv6 ret['gateways'] = {} ret['gateways']['AF_INET'] = netifaces.gateways()['default'].get( netifaces.AF_INET) ret['gateways']['AF_INET6'] = netifaces.gateways()['default'].get( netifaces.AF_INET6) return ret
def find_interface(self): for iface in netifaces.interfaces(): if iface.startswith('lo'): continue addrs = netifaces.ifaddresses(iface) if not addrs.has_key(netifaces.AF_INET): continue src_mac = addrs[netifaces.AF_LINK][0]['addr'] src_ip = addrs[netifaces.AF_INET][0]['addr'] if not src_mac or not src_ip: continue print "Trying if:", iface, src_ip, src_mac testsock = socket(AF_INET, SOCK_DGRAM) testsock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) testsock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) testsock.bind((src_ip, self.inport)) msg = Message(MT_PTYPE_SESSIONSTART, src_mac, self.dst_mac, self.session_key, 0) testsock.sendto(msg.get_buffer(), ('255.255.255.255', MACTELNET_PORT)) inlist, _, _ = select((self.insock,), (), (), 2) if len(inlist) > 0: self.outsock = testsock self.src_mac = src_mac self.src_ip = src_ip return True testsock.close() return False
def get_all_interface_ip(): interface_list = '' for interface in netifaces.interfaces(): addr = netifaces.ifaddresses(interface).get(netifaces.AF_INET) if addr: interface_list += "%s," % addr[0].get('addr') return interface_list
def get_lan_ip(): ip = '127.0.0.1' if ip.startswith("127.") and os.name != "nt": candidate_interfaces = [ "eth0", "eth1", "eth2", "en0", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0", ] interfaces = netifaces.interfaces() for ifname in interfaces: if ifname not in candidate_interfaces: continue try: print ifname ip = get_interface_ip(ifname) break except IOError: pass return ip
def get_networkinterfaces(): return netifaces.interfaces()
def get_devices(self): try: return [IPDevice(iface) for iface in netifaces.interfaces()] except (OSError, MemoryError): LOG.error(_LE("Failed to get network interfaces.")) return []
def getIPAddress(iface): if (iface in netifaces.interfaces()): return netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] else: return '0'
def getNetworkMask(iface): if (iface in netifaces.interfaces()): return netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['netmask'] else: return '0'
def hosts(): return _hosts(ifaddresses(if_) for if_ in interfaces())
import soco import yeelight from netifaces import interfaces, AF_INET, ifaddresses if __name__ == '__main__': # select interface if needed. data = [ifaddresses(i) for i in interfaces()] interface = False for d in data: if d.get(AF_INET): # use the WLAN interface if d[AF_INET][0]['addr'].startswith('192.168.3'): interface = d[AF_INET][0]['addr'] sonos = list(soco.discover(timeout=10, interface_addr=interface))[0] bulb = yeelight.Bulb( yeelight.discover_bulbs(timeout=10, interface=interface)[0].get('ip')) try: print(sonos) if sonos: sonos.play_mode = 'REPEAT_ONE' sonos.play_uri( 'http://img.tukuppt.com/newpreview_music/09/01/52/5c89f044e48f61497.mp3' ) sonos.play() sonos.volumn = 6 print(bulb) if bulb: bulb.toggle() except KeyboardInterrupt as e:
def _interface_exists(self, interface): """Determine if a given network adapter exists on the node""" return (interface in netifaces.interfaces())
def get_network_interfaces(): if_data = {} for interface in netifaces.interfaces(): if_data[interface] = netifaces.ifaddresses(interface) return if_data
"CHR": "↑", "FULL": "⤒", }, #"FULL": "⥍ ⇞ ☢",} # status={"DIS": "⇂", "CHR": "↿", "FULL": "⥍",}, # status={"DIS": "⇂", "CHR": "↿", "FULL": "⥮",}, ) try: st.register('backlight', backlight='intel_backlight', format='☀{percentage:3.0f}%') #TODO# make portable except FileNotFoundError: # there is no intel_backlight pass # Note: requires both netifaces and basiciw (for essid and quality) wl = next((i for i in netifaces.interfaces() if i.startswith('wl')), None) if wl: st.register("network", interface=wl, format_up="{essid} {quality:.0f}%") st.register( "disk", path="/media/data", format="data {avail:.0f}G", ) st.register( "disk", path="/", format="root {avail:.0f}G", )
def get_local_interfaces(all_=False): """ Returns a dictionary of name:ip key value pairs. Linux Only! Source: https://gist.github.com/bubthegreat/24c0c43ad159d8dfed1a5d3f6ca99f9b Args: all_ (bool): If False, filter virtual interfaces such VMWare, Docker etc... Returns: dict """ ip_dict = {} excluded_interfaces = ('lo', 'docker', 'br-', 'veth', 'vmnet') if platform.system() == 'Linux': # Max possible bytes for interface result. # Will truncate if more than 4096 characters to describe interfaces. MAX_BYTES = 4096 # We're going to make a blank byte array to operate on. # This is our fill char. FILL_CHAR = b'\0' # Command defined in ioctl.h for the system operation for get iface # list. # Defined at https://code.woboq.org/qt5/include/bits/ioctls.h.html # under /* Socket configuration controls. */ section. SIOCGIFCONF = 0x8912 # Make a dgram socket to use as our file descriptor that we'll # operate on. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Make a byte array with our fill character. names = array.array('B', MAX_BYTES * FILL_CHAR) # Get the address of our names byte array for use in our struct. names_address, names_length = names.buffer_info() # Create a mutable byte buffer to store the data in mutable_byte_buffer = struct.pack('iL', MAX_BYTES, names_address) # mutate our mutable_byte_buffer with the results of get_iface_list. # NOTE: mutated_byte_buffer is just a reference to # mutable_byte_buffer - for the sake of clarity we've defined # them as separate variables, however they are the same address # space - that's how fcntl.ioctl() works since the mutate_flag=True # by default. mutated_byte_buffer = fcntl.ioctl(sock.fileno(), SIOCGIFCONF, mutable_byte_buffer) # Get our max_bytes of our mutated byte buffer # that points to the names variable address space. max_bytes_out, names_address_out = struct.unpack( 'iL', mutated_byte_buffer) # Convert names to a bytes array - keep in mind we've mutated the # names array, so now our bytes out should represent the bytes # results of the get iface list ioctl command. namestr = names.tostring() namestr[:max_bytes_out] bytes_out = namestr[:max_bytes_out] # Each entry is 40 bytes long. The first 16 bytes are the # name string. The 20-24th bytes are IP address octet strings in # byte form - one for each byte. # Don't know what 17-19 are, or bytes 25:40. for i in range(0, max_bytes_out, 40): name = namestr[i:i + 16].split(FILL_CHAR, 1)[0] name = name.decode() ip_bytes = namestr[i + 20:i + 24] full_addr = [] for netaddr in ip_bytes: if isinstance(netaddr, int): full_addr.append(str(netaddr)) elif isinstance(netaddr, str): full_addr.append(str(ord(netaddr))) if not name.startswith(excluded_interfaces) or all_: ip_dict[name] = '.'.join(full_addr) else: try: import netifaces except ImportError: CLI.colored_print( 'You must install netinfaces first! Please ' 'type `pip install netifaces --user`', CLI.COLOR_ERROR) sys.exit(1) for interface in netifaces.interfaces(): if not interface.startswith(excluded_interfaces) or all_: ifaddresses = netifaces.ifaddresses(interface) if ifaddresses.get(netifaces.AF_INET) and \ ifaddresses.get(netifaces.AF_INET)[0].get('addr'): interfaces = ifaddresses.get(netifaces.AF_INET) ip_dict[interface] = interfaces[0].get('addr') return ip_dict
def scan(adapter, scantime, verbose, number, nearby, jsonprint, out, allmacaddresses, nocorrection, loop, sort, targetmacs): """Monitor wifi signals to count the number of people around you""" # print("OS: " + os.name) # print("Platform: " + platform.system()) try: tshark = which("tshark") except: if platform.system() != 'Darwin': print( 'tshark not found, install using\n\napt-get install tshark\n') else: print( 'wireshark not found, install using: \n\tbrew install wireshark' ) print( 'you may also need to execute: \n\tbrew cask install wireshark-chmodbpf' ) return if jsonprint: number = True if number: verbose = False if len(adapter) == 0: if os.name == 'nt': print('You must specify the adapter with -a ADAPTER') print('Choose from the following: ' + ', '.join(netifaces.interfaces())) return title = 'Please choose the adapter you want to use: ' adapter, index = pick(netifaces.interfaces(), title) # print("Using %s adapter and scanning for %s seconds..." % # (adapter, scantime)) if not number: # Start timer t1 = threading.Thread(target=showTimer, args=(scantime, )) t1.daemon = True t1.start() # Scan with tshark command = [ tshark, '-I', '-i', adapter, '-a', 'duration:' + scantime, '-w', '/tmp/tshark-temp' ] if verbose: print(' '.join(command)) run_tshark = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, nothing = run_tshark.communicate() if not number: t1.join() # Read tshark output command = [ tshark, '-r', '/tmp/tshark-temp', '-T', 'fields', '-e', 'wlan.sa', '-e', 'wlan.bssid', '-e', 'radiotap.dbm_antsignal' ] if verbose: print(' '.join(command)) run_tshark = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, nothing = run_tshark.communicate() # read target MAC address targetmacset = set() if targetmacs != '': targetmacset = fileToMacSet(targetmacs) foundMacs = {} for line in output.decode('utf-8').split('\n'): if verbose: print(line) if line.strip() == '': continue mac = line.split()[0].strip().split(',')[0] dats = line.split() if len(dats) == 3: if ':' not in dats[0] or len(dats) != 3: continue if mac not in foundMacs: foundMacs[mac] = [] dats_2_split = dats[2].split(',') if len(dats_2_split) > 1: rssi = float(dats_2_split[0]) / 2 + float(dats_2_split[1]) / 2 else: rssi = float(dats_2_split[0]) foundMacs[mac].append(rssi) if not foundMacs: print("Found no signals, are you sure %s supports monitor mode?" % adapter) return for key, value in foundMacs.items(): foundMacs[key] = float(sum(value)) / float(len(value)) # Find target MAC address in foundMacs if targetmacset: sys.stdout.write(RED) for mac in foundMacs: if mac in targetmacset: print("Found MAC address: %s" % mac) print("rssi: %s" % str(foundMacs[mac])) sys.stdout.write(RESET) cellphone = [ 'Motorola Mobility LLC, a Lenovo Company', 'GUANGDONG OPPO MOBILE TELECOMMUNICATIONS CORP.,LTD', 'Huawei Symantec Technologies Co.,Ltd.', 'Microsoft', 'HTC Corporation', 'Samsung Electronics Co.,Ltd', 'SAMSUNG ELECTRO-MECHANICS(THAILAND)', 'BlackBerry RTS', 'LG ELECTRONICS INC', 'Apple, Inc.', 'LG Electronics', 'OnePlus Tech (Shenzhen) Ltd', 'Xiaomi Communications Co Ltd', 'LG Electronics (Mobile Communications)' ] cellphone_people = [] androids = 0 iphones = 0 for mac in foundMacs: oui_id = 'Not in OUI' if mac[:8] in oui: oui_id = oui[mac[:8]] if verbose: print(mac, oui_id, oui_id in cellphone) if allmacaddresses or oui_id in cellphone: if not nearby or (nearby and foundMacs[mac] > -70): cellphone_people.append({ 'company': oui_id, 'rssi': foundMacs[mac], 'mac': mac }) if oui_id == 'Apple, Inc.': iphones += 1 else: androids += 1 if sort: cellphone_people.sort(key=lambda x: x['rssi'], reverse=True) if verbose: print(json.dumps(cellphone_people, indent=2)) # US / Canada: https://twitter.com/conradhackett/status/701798230619590656 percentage_of_people_with_phones = 0.7 if nocorrection: percentage_of_people_with_phones = 1 num_people = int( round(len(cellphone_people) / percentage_of_people_with_phones)) if number and not jsonprint: print("Total: {}".format(num_people)) print("iPhones: {} Androids: {}".format(iphones, androids)) #print(cellphone_people) # adding IFTTT post iftttpost(iphones, androids) elif jsonprint: print(json.dumps(cellphone_people, indent=2)) else: if num_people == 0: print("No one around (not even you!).") elif num_people == 1: print("No one around, but you.") else: print("There are about %d people around." % num_people) if out: with open(out, 'a') as f: data_dump = {'cellphones': cellphone_people, 'time': time.time()} f.write(json.dumps(data_dump) + "\n") if verbose: print("Wrote %d records to %s" % (len(cellphone_people), out)) os.remove('/tmp/tshark-temp') return adapter
coverage_file = args.coverage_file coverage_dir = args.coverage_dir temp_dir = args.temp_dir size_file = args.chromosome_sizes if not os.path.isfile(coverage_file): print("[ERROR] Coverage file {} not existing!".format(coverage_file)) exit(1) # output = options["output"] # format = output.split(".")[-1] # hostname = socket.gethostname() # host = socket.gethostbyname(hostname) # fqdn = socket.getfqdn() interface = 'ib0' if 'ib0' in netifaces.interfaces( ) else netifaces.interfaces()[0] hostname = socket.gethostbyaddr( netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']) pid = os.getpid() print("[SYSTEM] [TECH] [NODE] RANK:{} HOSTNAME:{} PID:{}".format( rank, hostname, pid)) if rank == 0: print( "[SYSTEM] LAUNCHED PARALLEL REDITOOLS WITH THE FOLLOWING OPTIONS:", options, args) region = None if args.region: region = re.split("[:-]", args.region) if not region or len(region) == 2 or (len(region) == 3
def setUp(self): """ To check and install dependencies for the test """ self.peer_user = self.params.get("peer_user", default="root") self.peer_public_ip = self.params.get("peer_public_ip", default="") self.peer_ip = self.params.get("peer_ip", default="") self.peer_password = self.params.get("peer_password", '*', default="None") interfaces = netifaces.interfaces() self.iface = self.params.get("interface", default="") if self.iface not in interfaces: self.cancel("%s interface is not available" % self.iface) self.ipaddr = self.params.get("host_ip", default="") self.netmask = self.params.get("netmask", default="") local = LocalHost() self.networkinterface = NetworkInterface(self.iface, local) try: self.networkinterface.add_ipaddr(self.ipaddr, self.netmask) self.networkinterface.save(self.ipaddr, self.netmask) except Exception: self.networkinterface.save(self.ipaddr, self.netmask) self.networkinterface.bring_up() self.session = Session(self.peer_ip, user=self.peer_user, password=self.peer_password) if not self.session.connect(): self.cancel("failed connecting to peer") smm = SoftwareManager() detected_distro = distro.detect() pkgs = ['gcc'] if detected_distro.name == "Ubuntu": pkgs.append('openssh-client') elif detected_distro.name == "SuSE": pkgs.append('openssh') else: pkgs.append('openssh-clients') for pkg in pkgs: if not smm.check_installed(pkg) and not smm.install(pkg): self.cancel("%s package is need to test" % pkg) cmd = "%s install %s" % (smm.backend.base_command, pkg) output = self.session.cmd(cmd) if not output.exit_status == 0: self.cancel( "unable to install the package %s on peer machine " % pkg) if self.peer_ip == "": self.cancel("%s peer machine is not available" % self.peer_ip) self.timeout = self.params.get("TIMEOUT", default="600") self.mtu = self.params.get("mtu", default=1500) self.remotehost = RemoteHost(self.peer_ip, self.peer_user, password=self.peer_password) self.peer_interface = self.remotehost.get_interface_by_ipaddr( self.peer_ip).name self.peer_networkinterface = NetworkInterface(self.peer_interface, self.remotehost) self.remotehost_public = RemoteHost(self.peer_public_ip, self.peer_user, password=self.peer_password) self.peer_public_networkinterface = NetworkInterface( self.peer_interface, self.remotehost_public) if self.peer_networkinterface.set_mtu(self.mtu) is not None: self.cancel("Failed to set mtu in peer") if self.networkinterface.set_mtu(self.mtu) is not None: self.cancel("Failed to set mtu in host") self.netperf_run = str(self.params.get("NETSERVER_RUN", default=0)) self.netperf = os.path.join(self.teststmpdir, 'netperf') netperf_download = self.params.get("netperf_download", default="https:" "//github.com/HewlettPackard/" "netperf/archive/netperf-2.7.0.zip") tarball = self.fetch_asset(netperf_download, expire='7d') archive.extract(tarball, self.netperf) self.version = "%s-%s" % ("netperf", os.path.basename(tarball.split('.zip')[0])) self.neperf = os.path.join(self.netperf, self.version) destination = "%s:/tmp" % self.peer_ip output = self.session.copy_files(self.neperf, destination, recursive=True) if not output: self.cancel("unable to copy the netperf into peer machine") cmd = "cd /tmp/%s;./configure --build=powerpc64le;make" % self.version output = self.session.cmd(cmd) if not output.exit_status == 0: self.fail("test failed because command failed in peer machine") os.chdir(self.neperf) process.system('./configure --build=powerpc64le', shell=True) build.make(self.neperf) self.perf = os.path.join(self.neperf, 'src', 'netperf') self.expected_tp = self.params.get("EXPECTED_THROUGHPUT", default="90") self.duration = self.params.get("duration", default="300") self.min = self.params.get("minimum_iterations", default="1") self.max = self.params.get("maximum_iterations", default="15") self.option = self.params.get("option", default='')
def get_interfaces(): interfaces = netifaces.interfaces() return interfaces
def node_info(req): #, device): if req == 'info': with os.popen('df %s -h' % RESULTS_DIR) as df: disk_free = df.read() disk_usage = RESULTS_DIR + " Not Found on disk" CARDS = {} IPs = [] CFG.load() try: disk_usage = disk_free.split("\n")[1].split() #the following returns something like this: [['eno1', 'ec:b1:d7:66:2e:3a', '192.168.1.1'], ['enp0s20u12', '74:da:38:49:f8:2a', '155.198.232.206']] adapters_list = [ [ i, netifaces.ifaddresses(i)[17][0]['addr'], netifaces.ifaddresses(i)[2][0]['addr'] ] for i in netifaces.interfaces() if 17 in netifaces.ifaddresses(i) and 2 in netifaces.ifaddresses(i) and netifaces.ifaddresses(i)[17][0]['addr'] != '00:00:00:00:00:00' ] for ad in adapters_list: CARDS[ad[0]] = {'MAC': ad[1], 'IP': ad[2]} IPs.append(ad[2]) with os.popen('git rev-parse --abbrev-ref HEAD') as df: GIT_BRANCH = df.read() or "Not detected" #df = subprocess.Popen(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=subprocess.PIPE) #GIT_BRANCH = df.communicate()[0].decode('utf-8') with os.popen('git status -s -uno') as df: NEEDS_UPDATE = df.read() != "" #df = subprocess.Popen(['git', 'status', '-s', '-uno'], stdout=subprocess.PIPE) #NEEDS_UPDATE = df.communicate()[0].decode('utf-8') != "" with os.popen('systemctl status ethoscope_node.service') as df: try: ACTIVE_SINCE = df.read().split("\n")[2] except: ACTIVE_SINCE = "Not running through systemd" except Exception as e: logging.error(e) return { 'active_since': ACTIVE_SINCE, 'disk_usage': disk_usage, 'IPs': IPs, 'CARDS': CARDS, 'GIT_BRANCH': GIT_BRANCH, 'NEEDS_UPDATE': NEEDS_UPDATE } elif req == 'time': return {'time': datetime.datetime.now().isoformat()} elif req == 'timestamp': return {'timestamp': datetime.datetime.now().timestamp()} elif req == 'log': with os.popen("journalctl -u ethoscope_node -rb") as log: l = log.read() return {'log': l} elif req == 'daemons': #returns active or inactive for daemon_name in SYSTEM_DAEMONS.keys(): with os.popen("systemctl is-active %s" % daemon_name) as df: SYSTEM_DAEMONS[daemon_name]['active'] = df.read().strip() return SYSTEM_DAEMONS elif req == 'folders': return CFG.content['folders'] elif req == 'users': return CFG.content['users'] elif req == 'incubators': return CFG.content['incubators'] elif req == 'sensors': return sensor_scanner.get_all_devices_info() else: raise NotImplementedError()
def get_interfaces(): netifaces = import_netifaces() if not netifaces: return [] return netifaces.interfaces() #@UndefinedVariable
def get_avail_interfaces(self): interfaces = ni.interfaces() return interfaces
######################################################################################################################## # ARGUMENT VERIRIFCATION # # This is where you put any logic to verify the arguments, and failure messages # ######################################################################################################################## auth_pass = args.auth_pass if auth_pass is None: print 'WARNING: Using this container without a set auth pass will make this container insecure.' auth_pass = '******' vrid = args.vrid if vrid is None: print 'WARNING: Not setting a vrid could result in a conflict. Please specify a vrid to avoid possible conflicts' vrid = 1 # Check if the track_iface is a valid iface if args.track_iface not in netifaces.interfaces(): print "The iface %s does not appear to be a valid interface on this host, terminating..." % args.track_iface sys.exit( 0 ) # This should be a return 0 to prevent the container from restarting. vips = [] # Check and import the included VIPs for vip in args.include: vip_check(vips, vip, False) # Check and import the excluded VIPs: if args.exclude is not None: for vip in args.exclude: vip_check(vips, vip, True)
from netifaces import interfaces, ifaddresses, AF_INET if len(sys.argv) == 1: print "\ntry to help with buffer overflows \n" print "usage: \n" print " %s <buffer> " % sys.argv[0] print " %s <buffer> <EIP> " % sys.argv[0] print " %s <badchars> " % sys.argv[0] print " %s <JMPESP> " % sys.argv[0] print " %s <ASLR_DEP>" % sys.argv[0] print " %s <shellcode> " % sys.argv[0] print "\n" elif str(sys.argv[1]) == 'shellcode': print """\nmsfvenom -p PAYLOAD LHOST=IP LPORT=CALLBACK_PORT -f c -e x86/shikata_ga_nai -b "BADCHARS" \n""" for ifaceName in interfaces(): addresses = [ i['addr'] for i in ifaddresses(ifaceName).setdefault( AF_INET, [{ 'addr': 'No IP addr' }]) ] print '%s: %s' % (ifaceName, ', '.join(addresses)) elif str(sys.argv[1]) == 'badchars': badchars = ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20" "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30" "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40" "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
def setUp(self): ''' To check and install dependencies for the test ''' smm = SoftwareManager() detected_distro = distro.detect() pkgs = ["gcc"] if detected_distro.name == "Ubuntu": pkgs.append('openssh-client') elif detected_distro.name == "SuSE": pkgs.append('openssh') else: pkgs.append('openssh-clients') 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", default="") self.peer_ip = self.params.get("peer_ip", default="") if self.iface not in interfaces: self.cancel("%s interface is not available" % self.iface) if self.peer_ip == "": self.cancel("%s peer machine is not available" % self.peer_ip) self.tmo = self.params.get("TIMEOUT", default="600") self.iperf_run = self.params.get("IPERF_RUN", default="0") self.netserver_run = self.params.get("NETSERVER_RUN", default="0") self.iper = os.path.join(self.teststmpdir, 'iperf') self.netperf = os.path.join(self.teststmpdir, 'netperf') if detected_distro.name == "Ubuntu": cmd = "service ufw stop" # FIXME: "redhat" as the distro name for RHEL is deprecated # on Avocado versions >= 50.0. This is a temporary compatibility # enabler for older runners, but should be removed soon elif detected_distro.name in ['rhel', 'fedora', 'redhat']: cmd = "systemctl stop firewalld" elif detected_distro.name == "SuSE": if detected_distro.version == 15: cmd = "systemctl stop firewalld" else: cmd = "rcSuSEfirewall2 stop" elif detected_distro.name == "centos": cmd = "service iptables stop" else: self.cancel("Distro not supported") if process.system("%s && ssh %s %s" % (cmd, self.peer_ip, cmd), ignore_status=True, shell=True) != 0: self.cancel("Unable to disable firewall") tarball = self.fetch_asset( 'ftp://ftp.netperf.org/netperf/' 'netperf-2.7.0.tar.bz2', expire='7d') archive.extract(tarball, self.netperf) version = os.path.basename(tarball.split('.tar.')[0]) self.neperf = os.path.join(self.netperf, version) tmp = "scp -r %s root@%s:" % (self.neperf, self.peer_ip) if process.system(tmp, shell=True, ignore_status=True) != 0: self.cancel("unable to copy the netperf into peer machine") tmp = "cd /root/netperf-2.7.0;./configure ppc64le;make" cmd = "ssh %s \"%s\"" % (self.peer_ip, tmp) if process.system(cmd, shell=True, ignore_status=True) != 0: self.fail("test failed because command failed in peer machine") time.sleep(5) os.chdir(self.neperf) process.system('./configure ppc64le', shell=True) build.make(self.neperf) self.perf = os.path.join(self.neperf, 'src') time.sleep(5) tarball = self.fetch_asset( 'iperf.zip', locations=['https://github.com/esnet/iperf/archive/master.zip'], expire='7d') archive.extract(tarball, self.iper) self.ipe = os.path.join(self.iper, 'iperf-master') tmp = "scp -r %s root@%s:" % (self.ipe, self.peer_ip) if process.system(tmp, shell=True, ignore_status=True) != 0: self.cancel("unable to copy the iperf into peer machine") tmp = "cd /root/iperf-master;./configure;make" cmd = "ssh %s \"%s\"" % (self.peer_ip, tmp) if process.system(cmd, shell=True, ignore_status=True) != 0: self.fail("test failed because command failed in peer machine") time.sleep(5) os.chdir(self.ipe) process.system('./configure', shell=True) build.make(self.ipe) self.iperf = os.path.join(self.ipe, 'src')
def get_hostip(req=None): ''' Look up the ip number for a given requested interface name. If interface is not given, do some magic. ''' global _hostip _hostip = None if _hostip: return _hostip AF_INET = netifaces.AF_INET # We create a ordered preference list, consisting of: # - given arglist # - white list (hardcoded preferred interfaces) # - black_list (hardcoded unfavorable interfaces) # - all others (whatever is not in the above) # Then this list is traversed, we check if the interface exists and has an # IP address. The first match is used. if req: if not isinstance(req, list): req = [req] else: req = [] white_list = [ 'ipogif0', # Cray's 'br0', # SuperMIC 'eth0', # desktops etc. 'wlan0' # laptops etc. ] black_list = [ 'lo', # takes the 'inter' out of the 'net' 'sit0' # ? ] all = netifaces.interfaces() rest = [iface for iface in all if iface not in req and iface not in white_list and iface not in black_list] preflist = req + white_list + rest for iface in preflist: if iface not in all: continue info = netifaces.ifaddresses(iface) if AF_INET not in info: continue if not len(info[AF_INET]): continue if not info[AF_INET][0].get('addr'): continue ip = info[AF_INET][0].get('addr') if ip: _hostip = ip return ip raise RuntimeError('could not determine ip on %s' % preflist)
def run(): #nics = {} #count = 100 nics, count = read_rttables("/etc/iproute2/rt_tables") ipr = IPRoute() cmd = "echo 1 > /proc/sys/net/ipv4/conf/all/arp_ignore" p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) p.wait() while True: for interface in netifaces.interfaces(): if interface == "lo": continue try: ip = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] mask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask'] except KeyError: ip = "" mask = "" continue if nics.has_key(interface): state = ipr.get_links(ipr.link_lookup(ifname=interface))[0].get_attr('IFLA_OPERSTATE') #rule operation table_id = int(nics[interface]) ipret = ipr.get_rules(table=table_id) if ipret: iprlist = {} if ipret: for i in ipret[0]['attrs']: iprlist[i[0]] = i[1] #current ip is NULL if not ip or state == "DOWN": print interface, " ", table_id, " ", state, " del ", ip, " ", " ", mask, "\n" ipr.rule("del", table=table_id, priority=iprlist['FRA_PRIORITY']) else: if ip != iprlist['FRA_SRC']: print interface, " neq del ", ip, " ", " ", mask, "\n" ipr.rule("del", table=table_id, priority=iprlist['FRA_PRIORITY']) ipr.rule("add", table=table_id, src=ip) else: if ip: #add rule if state != "DOWN": ipr.rule("add", table=table_id, src=ip) #route operation if state == "DOWN": continue routelist = ipr.get_routes(table=table_id) if routelist: pass else: idx = ipr.link_lookup(ifname=interface)[0] ipss = IPS(ip).make_net(mask) ipr.route('add', dst=str(ipss), oif=idx, prefsrc=ip, table=table_id) else: #only once count += 1 cmd = "echo \"%d %s\" >> /etc/iproute2/rt_tables" % (count, interface) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) p.wait() #update table id nics[interface] = count
def main(): if os.getuid() != 0: sys.exit('must be run as root') parser = argparse.ArgumentParser() parser.add_argument('-c', '--controller-ip', default=CONTROLLER_IP, help='controller IP address') parser.add_argument('-p', '--controller-port', default=CONTROLLER_PORT, help='controller port') parser.add_argument('-d', '--debug-file', default=DEBUG_FILEPATH, help='debug file') parser.add_argument('-D', '--disable-debug', action='store_true', help='disable debug logging') parser.add_argument('-P', '--print-stdout', action='store_true', help='print debug info to stdout') parser.add_argument('-o', '--output-dir', default='output', help='captcp output directory') parser.add_argument('-j', '--json-file', default='captcp.json', help='captcp json file') parser.add_argument('-a', '--alias', default='', help='unique alias in network') parser.add_argument('-t', '--run-time', type=int, default=2, help='tcpdump run time') parser.add_argument('-k', '--packet-count', type=int, default=1000, help='tcpdump packet count') args = parser.parse_args() if not args.disable_debug: logging.basicConfig(level=logging.DEBUG, filename=args.debug_file) if args.print_stdout: rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler(sys.stdout) streamHandler.setLevel(logging.DEBUG) rootLogger.addHandler(streamHandler) # http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python bcast_ifaces = [] for iface in netifaces.interfaces(): ifaddr = netifaces.ifaddresses(iface) if netifaces.AF_INET in ifaddr: ipv4 = ifaddr[netifaces.AF_INET][0] addr_s = ipv4['addr'] addr = struct.unpack('>L', socket.inet_aton(addr_s))[0] net = struct.unpack('>L', socket.inet_aton(BROADCAST_NET_S))[0] mask = (0xffffffff << (32 - BROADCAST_MASK_BITS)) & 0xffffffff if (addr & mask) == (net & mask): bcast_ifaces.append({'name': iface, 'ipv4': ipv4}) done_event = threading.Event() threads = [] t1 = threading.Thread(target=listen_worker, args=[done_event, bcast_ifaces]) t2 = threading.Thread(target=query_worker, args=[done_event, args, bcast_ifaces]) t3 = threading.Thread(target=update_worker, args=[done_event, args]) t4 = threading.Thread(target=flow_worker, args=[done_event, args]) threads.extend([t1, t2, t3, t4]) for t in threads: t.start() try: while not done_event.is_set(): time.sleep(0.1) except KeyboardInterrupt: done_event.set() print '\nClosing...' for t in threads: t.join()
def getMacAddress(iface): if (iface in netifaces.interfaces()): return netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'] else: return '0'
#!/usr/bin/env python2 import re, netifaces resolv = open("/etc/resolv.conf") domains = [] servers = [] # get the first interface after lo0 interface = netifaces.interfaces().pop(1) host = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] for line in resolv.readlines(): domain_match = re.search(r"domain (.*)", line) search_match = re.search(r"search (.*)", line) server_match = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line) if search_match: domain = search_match.group(1) domains.append(domain) continue if domain_match: domain = domain_match.group(1) domains.append(domain) continue if server_match:
def check_interface(interface): interface_list = ni.interfaces() if interface in interface_list: return True else: return False
def _get_html(self): cust_js = None interfaces = ni.interfaces() my_ip = '127.0.0.1' HardwareScreen.display_in_use = http.request.httprequest.remote_addr with open( os.path.join(os.path.dirname(__file__), "../static/src/js/worker.js")) as js: cust_js = js.read() with open( os.path.join(os.path.dirname(__file__), "../static/src/css/cust_css.css")) as css: cust_css = css.read() display_ifaces = "" for iface_id in interfaces: iface_obj = ni.ifaddresses(iface_id) ifconfigs = iface_obj.get(ni.AF_INET, []) for conf in ifconfigs: if conf.get('addr'): display_ifaces += "<tr><td>" + iface_id + "</td>" display_ifaces += "<td>" + conf.get('addr') + "</td>" display_ifaces += "<td>" + conf.get( 'netmask') + "</td></tr>" # What is my external IP ? if iface_id != 'lo': my_ip = conf.get('addr') my_ip_port = my_ip + ":" + self_port html = """ <!DOCTYPE html> <html> <head> <title class="origin">Odoo -- Point of Sale</title> <script type="text/javascript" class="origin" src="http://""" + my_ip_port + """/web/static/lib/jquery/jquery.js" > </script> <script type="text/javascript" class="origin"> """ + cust_js + """ </script> <link rel="stylesheet" class="origin" href="http://""" + my_ip_port + """/web/static/lib/bootstrap/css/bootstrap.css" > </link> <script class="origin" src="http://""" + my_ip_port + """/web/static/lib/bootstrap/js/bootstrap.min.js"></script> <style class="origin"> """ + cust_css + """ </style> </head> <body class="original_body"> <div hidden class="shadow"></div> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <h1>Odoo Point of Sale</h1> <h2>POSBox Client display</h2> <h3>My IPs</h3> <table id="table_ip" class="table table-condensed"> <tr> <th>Interface</th> <th>IP</th> <th>Netmask</th> </tr> """ + display_ifaces + """ </table> <p>The customer cart will be displayed here once a Point of Sale session is started.</p> <p>Odoo version 11 or above is required.</p> </div> </div> </div> </body> </html> """ return html
exit( "Root permisson is required to operate on network interfaces. \nNow Aborting." ) #setting log file name filename = "spoof.log" # Set logging structure logging.basicConfig(format='%(levelname)s: %(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename=filename, filemode="a", level=logging.DEBUG) # Read available network interfaces available_interfaces = netifaces.interfaces() # Check the connected interface interface = netifaces.gateways()['default'][netifaces.AF_INET][1] # Check if specified interface is valid if not interface in available_interfaces: exit("Interface {} not available.".format(interface)) # Retrieve network addresses (IP, broadcast) from the network interfaces addrs = netifaces.ifaddresses(interface) #handling keyerror 2 which is cause due to netifaces try: local_ip = addrs[netifaces.AF_INET][0]["addr"] broadcast = addrs[netifaces.AF_INET][0]["broadcast"] except KeyError:
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import cgi import cgitb; cgitb.enable() import multiprocessing import os from timeit import Timer import netifaces ifaces_list = netifaces.interfaces() ifaces = [] ifaces.append(ifaces_list[1]) ifaces.append(ifaces_list[2]) ifaces.append(ifaces_list[0]) ip = '' for iface in ifaces: #prefer eth if str(iface).find("eth") > -1 and netifaces.ifaddresses(iface).has_key(2) == True: ip = netifaces.ifaddresses(iface)[2][0]["addr"] break if str(iface).find("wlan") > -1 and netifaces.ifaddresses(iface).has_key(2) == True: ip = netifaces.ifaddresses(iface)[2][0]["addr"] break if str(iface).find("lo") > -1: ip = netifaces.ifaddresses(iface)[2][0]["addr"]
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False, fatal=True, exc_list=None): """Return the assigned IP address for a given interface, if any. :param iface: network interface on which address(es) are expected to be found. :param inet_type: inet address family :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :return: list of ip addresses """ # Extract nic if passed /dev/ethX if '/' in iface: iface = iface.split('/')[-1] if not exc_list: exc_list = [] try: inet_num = getattr(netifaces, inet_type) except AttributeError: raise Exception("Unknown inet type '%s'" % str(inet_type)) interfaces = netifaces.interfaces() if inc_aliases: ifaces = [] for _iface in interfaces: if iface == _iface or _iface.split(':')[0] == iface: ifaces.append(_iface) if fatal and not ifaces: raise Exception("Invalid interface '%s'" % iface) ifaces.sort() else: if iface not in interfaces: if fatal: raise Exception("Interface '%s' not found " % (iface)) else: return [] else: ifaces = [iface] addresses = [] for netiface in ifaces: net_info = netifaces.ifaddresses(netiface) if inet_num in net_info: for entry in net_info[inet_num]: if 'addr' in entry and entry['addr'] not in exc_list: addresses.append(entry['addr']) if fatal and not addresses: raise Exception("Interface '%s' doesn't have any %s addresses." % (iface, inet_type)) return sorted(addresses)