def print_network(): """Print all system and ROS network information.""" print('NETWORK CONFIGURATION') for name, iface in ifcfg.interfaces().items(): for k, v in iface.items(): print_term(k, v) print('\n')
def get_0_5_mac_address(): # check whether envvar was set, and use that if available node_id = os.environ.get("MORANGO_NODE_ID") if node_id and len(node_id.strip()) >= 3: return _do_salted_hash(node_id) # first, try using ifcfg interfaces = [] try: interfaces = ifcfg.interfaces().values() except: # noqa: E722 pass for iface in sorted(interfaces, key=_device_sort_key): ether = iface.get("ether") if ether and not _mac_is_local(ether): return _do_salted_hash(ether) # fall back to trying uuid.getnode mac = uuid.getnode() # when uuid.getnode returns a fake MAC, it marks as multicast if not _mac_is_multicast(mac): return _do_salted_hash(_mac_int_to_ether(mac)) return ""
def get_ip_addresses(include_loopback=True): """Get a list of all the IP addresses for adapters on the local system. You can specify to either include the loopback device (127.0.0.1) or not. """ system = platform.system() if system.lower() in ["linux", "darwin", "macosx"]: # on Linux and OSX, use the ifcfg library to wrap ifconfig ips = [iface.get("inet") for iface in ifcfg.interfaces().values()] elif system.lower() == "windows": # on Windows, run ipconfig and parse the output ipconfig = os.popen("ipconfig /all").read() ips = [match[1] for match in re.findall("IP(v4)? Address[\.\: ]+([\d\.]+)", ipconfig)] # remove empty values for adapters without an IP ips = set(ips) - set([None, ""]) if include_loopback: ips = ips.union(["127.0.0.1"]) else: ips = ips - set(["127.0.0.1"]) return list(ips)
def check(self): """Check network configuration.""" result = Result() # check ifcfg import for windows and osx users ifcfg_ifaces = ifcfg.interfaces() has_loopback, has_non_loopback, has_multicast = _check_network_config_helper( ifcfg_ifaces) if not _is_unix_like_platform(): if not has_loopback and not has_non_loopback: # no flags found, otherwise one of them should be True. doctor_warn( 'Interface flags are not available on Windows. ' 'Run `ipconfig` to see what interfaces are available.') result.add_warning() return result if not has_loopback: doctor_error('No loopback IP address is found.') result.add_error() if not has_non_loopback: doctor_warn('Only loopback IP address is found.') result.add_warning() if not has_multicast: doctor_warn('No multicast IP address is found.') result.add_warning() return result
def findLocals(self): for name, interface in ifcfg.interfaces().items(): if name != 'lo': if 'broadcast' in interface: netmask = self.find_Mask(interface) ips = self.find_Ip(interface, netmask) rede = unicodedata.normalize('NFKD', name).encode( 'ascii', 'ignore') # print ("\n[*] %s" %name) # print ("(*) Interface: %s" % rede) # print ("(*) Ip: %s" % ips) # print ("(*) Mascara: %s" % netmask) conf.verb = 0 ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ips), timeout=2, iface=rede) for snd, rcv in ans: Mac, Ip = rcv.sprintf( r"%Ether.src% %ARP.psrc%").split() find = False for m in self.lmachine: if m.Ip == Ip: find = True break if find == False: self.scanIp(Ip, Mac) return self.lmachine
def find_interfaces(whitelist=None): try: interfaces = ifcfg.interfaces() except Exception as e: sys.stderr.write( "Unable to get interface info. Falling back to simple output. " "Error: {0}\n".format(e)) yield InterfaceInfo( None, None, dict(v=JSON_FORMAT_VER, _error="ifcfg failed: {}".format(e))) return if not interfaces: yield InterfaceInfo( None, None, dict(v=JSON_FORMAT_VER, _error="no output from ifcfg.interface()")) return for name, interface in interfaces.items(): if whitelist: if name not in whitelist: continue # Skip loopback adapter if name.startswith("lo"): continue if interface.get("status", None) == "inactive": continue if interface["inet"] is None: continue yield _filter_interface_attrs(interface)
def get_ip_addresses(include_loopback=True): """Get a list of all the IP addresses for adapters on the local system. You can specify to either include the loopback device (127.0.0.1) or not. """ system = platform.system() if system.lower() in ["linux", "darwin", "macosx"]: # on Linux and OSX, use the ifcfg library to wrap ifconfig ips = [iface.get("inet") for iface in ifcfg.interfaces().values()] elif system.lower() == "windows": # on Windows, run ipconfig and parse the output ipconfig = os.popen("ipconfig /all").read() ips = [ match[1] for match in re.findall( "IP(v4)? Address[\.\: ]+([\d\.]+)", ipconfig) ] # remove empty values for adapters without an IP ips = set(ips) - set([None, ""]) if include_loopback: ips = ips.union(["127.0.0.1"]) else: ips = ips - set(["127.0.0.1"]) return list(ips)
def check(self): """Check network configuration.""" result = Result() # check ifcfg import for windows and osx users try: ifcfg_ifaces = ifcfg.interfaces() except NameError: doctor_error('`ifcfg` module is not imported. ' 'Unable to run network check.') result.add_error() return result has_loopback, has_non_loopback, has_multicast = _check_network_config_helper( ifcfg_ifaces) if not _is_unix_like_platform(): if not has_loopback and not has_non_loopback: # no flags found, otherwise one of them should be True. doctor_error( 'No flags found. ' 'Run `ipconfig` on Windows or ' 'install `ifconfig` on Unix to check network interfaces.') result.add_error() return result if not has_loopback: doctor_error('No loopback IP address is found.') result.add_error() if not has_non_loopback: doctor_warn('Only loopback IP address is found.') result.add_warning() if not has_multicast: doctor_warn('No multicast IP address is found.') result.add_warning() return result
def chooseDevice(): devicesName = [] for index, [_, interface] in enumerate(ifcfg.interfaces().items()): devicesName.append(str(index + 1) + '.' + interface['device']) [print(x) for x in devicesName] choice = int(input()) return devicesName[choice - 1].split('.')[1]
def getIPv4(): try: interface1 = "Wireless LAN adapter Wi-Fi" interface2 = "wlan0" interface = "" if interface1 in ifcfg.interfaces(): interface = interface1 elif interface2 in ifcfg.interfaces(): interface = interface2 return ifcfg.interfaces()[interface]['inet'] except: return (([ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]]) + ["no IP found"])[0]
def by_ifcfg(): ip = None result = ifcfg.interfaces() for k, v in result.items(): if v['inet'] != None and v['inet'] != '127.0.0.1': return v['inet'] return ip
def get_ips(): ips_list = [] for interface, value in ic.interfaces().items(): if interface not in ['lo', 'docker0']: if value['inet'] is not None: dic = {'interface': interface, 'ip': value['inet']} ips_list.append(dic) return ips_list
def ips(): ips = [] for name, interface in ifcfg.interfaces().items(): for ip in interface['inet4']: if name == 'lo': continue ips.append(ip) string = ' '.join(ips) return string
def report(self): """Print system and ROS network information.""" # check ifcfg import for windows and osx users ifcfg_ifaces = ifcfg.interfaces() network_report = Report('NETWORK CONFIGURATION') for iface in ifcfg_ifaces.values(): for k, v in iface.items(): if v: network_report.add_to_report(k, v) return network_report
def check_network_config_helper(): """Check if loopback and multicast IP addresses are found.""" has_loopback, has_non_loopback, has_multicast = False, False, False for name, iface in ifcfg.interfaces().items(): flags = iface.get('flags') if 'LOOPBACK' in flags: has_loopback = True else: has_non_loopback = True if 'MULTICAST' in flags: has_multicast = True return has_loopback, has_non_loopback, has_multicast
def __fetch_mac_addresses(self): mac_addresses = {} for name, interface in ifcfg.interfaces().items(): address = interface['ether'] mac_addresses[name] = { 'address': address, 'vendor': self.__lookup_org_by_mac_address(address) if address is not None else None, } return mac_addresses
def is_ovpn_ready(): global OVPN_GTW try: ovpn_interface = ifcfg.interfaces()["tun0"] except: return False print("Openvpn not ready") ip = ovpn_interface["inet"] OVPN_GTW = ".".join(ovpn_interface["inet"].split(".")[:-1] + ["1"]) is_gtw_responding = ping(OVPN_GTW) return is_gtw_responding
def get_local_ether_interface(): import ifcfg import ipaddress for name, interface in ifcfg.interfaces().items(): ip_addr = interface.get('inet') ip_ether = interface.get('ether') if (ip_addr and ip_ether): i = ipaddress.ip_address(ip_addr) if (i.is_private): return interface return None
def _check_network_config_helper( ifcfg_ifaces: dict) -> Tuple[bool, bool, bool]: """Check if loopback and multicast IP addresses are found.""" has_loopback, has_non_loopback, has_multicast = False, False, False for name, iface in ifcfg.interfaces().items(): flags = iface.get('flags').lower() if 'loopback' in flags: has_loopback = True else: has_non_loopback = True if 'multicast' in flags: has_multicast = True return has_loopback, has_non_loopback, has_multicast
def me(*names, v6=False, all=False): import ifcfg inet = 'inet6' if v6 else 'inet' ips = { k: ifc[inet] for k, ifc in ifcfg.interfaces().items() if k not in _SKIP_ME and ifc.get(inet) } if names: return [ips.get(n) for n in names] if all: return ips return max_common_prefix('192.168.4', *ips.values(), n=2, split='.')
def is_ppp_interface_present(self): exists = False for name, interface in ifcfg.interfaces().items(): if interface['device'] == 'ppp0': exists = True if exists: logging.info('ppp0 interface is present.') else: logging.info('ppp0 interface is not present.') return exists
def report(self): """Print system and ROS network information.""" # check ifcfg import for windows and osx users try: ifcfg_ifaces = ifcfg.interfaces() except NameError: doctor_warn('ifcfg is not imported. Unable to generate network report.') return Report('') network_report = Report('NETWORK CONFIGURATION') for iface in ifcfg_ifaces.values(): for k, v in iface.items(): if v: network_report.add_to_report(k, v) return network_report
def get_ip(self, interface, logger): logger.info('-' * 35) logger.info('Initiating %s', interface) ip = self.dic[interface]['inet'] retry = 0 while ip is None: if retry > 5: logger.error('ifup %s', interface) call(['ifup', interface.replace('macvlan', 'vwan').replace('eth0.2', 'wan')]) retry = 0 self.dic = ifcfg.interfaces() ip = self.dic[interface]['inet'] retry += 1 time.sleep(5) logger.info('IP: %s', ip) return ip
def get_urls(listen_port=None): """ :param listen_port: if set, will not try to determine the listen port from other running instances. """ try: if listen_port: port = listen_port else: __, __, port = get_status() urls = [] interfaces = ifcfg.interfaces() for interface in filter(lambda i: i['inet'], interfaces.values()): urls.append("http://{}:{}/".format(interface['inet'], port)) return STATUS_RUNNING, urls except NotRunning as e: return e.status_code, []
def scripting_1(): found_target_ips = [] for name, interface in ifcfg.interfaces().items(): #using ifcfg to parse through interfaces. subnet = interface['inet'] + "/24" if subnet.startswith('127'): continue: nm = nmap.PortScanner() # now that we have the subnet and the ips running on that subnet, we just want to isolate the ips with an open port 22/ scan_ips = nm.scan(subnet, '22') for element in nm.all_hosts(): if nm[element]['tcp'][22]['state'] == 'open': found_target_ips.append(element) else: continue if interface['inet'] in found_target_ips: # But we need remove from the final list our host IP in order to not infect the host machine. found_target_ips.remove(interface['inet']) return found_target_ips
def get_local_hosts(): hosts = [] for name, interface in ifcfg.interfaces().items(): interface_ip = interface['inet'] if interface_ip is None: continue hosts.append((name, interface_ip, ASSOCIATED_IP)) for ip in [ip for ip in interface['inet4'] if ip != interface_ip]: hosts.append((name, ip, IP_V4)) for ip in [ip for ip in interface['inet6'] if ip != interface_ip]: hosts.append((name, ip, IP_V6)) return hosts
def interface_up( pl, interface, interface_up="{device} is up", interface_down="{device} is down", ): interface = ifcfg.interfaces().get(interface, {}) is_up = (interface.get("status", "inactive") == "active" or "up" in interface.get("flags", "")) if is_up: contents = interface_up.format(**interface) else: contents = interface_down.format(**interface) return [{ "contents": contents, }]
def GetInterfaces(self) -> dict: ''' get all interface info''' self.network_config.rescan() interfaces_from_etc = self.network_config.interfaces interfaces_from_ifcfg = ifcfg.interfaces() dhcp_ifacs = interfaces_from_ifcfg.keys() - interfaces_from_etc.keys() for ifac in dhcp_ifacs: interface = api.NetworkInterface() interface.name = ifac interface.addressing = 'dhcp' interface.up = True params = {} params['address'] = interfaces_from_ifcfg[ifac]['inet'] params['netmask'] = interfaces_from_ifcfg[ifac]['netmask'] interface.params = params interfaces_from_etc[ifac] = interface return interfaces_from_etc
def check(self): """Check network configuration.""" result = Result() # check ifcfg import for windows and osx users try: ifcfg_ifaces = ifcfg.interfaces() except NameError: result.add_error( 'ERROR: ifcfg is not imported. Unable to run network check.') return result has_loopback, has_non_loopback, has_multicast = _check_network_config_helper( ifcfg_ifaces) if not has_loopback: result.add_error('ERROR: No loopback IP address is found.') if not has_non_loopback: result.add_warning('Only loopback IP address is found.') if not has_multicast: result.add_warning('No multicast IP address is found.') return result
def get_urls(listen_port=None): """ :param listen_port: if set, will not try to determine the listen port from other running instances. """ try: if listen_port: port = listen_port else: __, __, port = get_status() urls = [] if port: try: interfaces = ifcfg.interfaces() for interface in filter(lambda i: i["inet"], interfaces.values()): urls.append("http://{}:{}/".format(interface["inet"], port)) except RuntimeError: logger.error("Error retrieving network interface list!") return STATUS_RUNNING, urls except NotRunning as e: return e.status_code, []
def network(self): result = [] details = psutil.net_io_counters(pernic=True) ip_details = ifcfg.interfaces() for net in details.keys(): net_dict = {} net_dict['interface'] = net if os.name != 'nt': net_dict['ip'] = ip_details[net]['inet'] if ip_details[net]['inet'] != None else 'None' net_dict['bytes_sent'] = details[net].bytes_sent net_dict['bytes_recv'] = details[net].bytes_recv net_dict['packets_sent'] = details[net].packets_sent net_dict['packets_recv'] = details[net].packets_recv net_dict['errin'] = details[net].errin net_dict['errout'] = details[net].errout net_dict['dropin'] = details[net].dropin net_dict['dropout'] = details[net].dropout result.append(net_dict) return tuple(result)
def populateInterfaces(self): newInterfaces = ifcfg.interfaces() self.interfaces = [] self.virtual = [] self.activeInterfaces = [] self.inactiveInterfaces = [] for i in newInterfaces.keys(): # get each interface one by one interface = newInterfaces[i] device = interface['device'] self.markStatus(interface) if device == WIRELESS_INTERFACE: self.wifiDevice = WIRELESS_INTERFACE self.wifi = interface['device'] elif device == WIRED_INTERFACE: self.wiredDevice = WIRED_INTERFACE self.wired = interface elif device.find('en') != -1: self.virtual.append(interface) else: self.other.append(interface) self.interfaces.append(newInterfaces[i])
def test_ifcfg(self): interfaces = ifcfg.interfaces() res = len(interfaces) > 0 ok_(res)
def test_ifcfg(self): ifcfg.distro = 'Linux' ifcfg.Parser = LinuxParser interfaces = ifcfg.interfaces(ifconfig=ifconfig_out.LINUX) res = len(interfaces) > 0 ok_(res)
def __init__(self): self.dic = ifcfg.interfaces()
def test_interfaces(self): ifcfg.Parser = WindowsParser interfaces = ifcfg.interfaces(ifconfig=ipconfig_out.WINDOWS_10_ETH) res = len(interfaces) > 0 ok_(res)
def execute(self, *args, **options): return ifcfg.interfaces()
def main(): print(json.dumps(ifcfg.interfaces(), indent=2))
def test_ifcfg(self): for interface in ifcfg.interfaces(): print(interface)
# from netconfig import NetConfig # # # net = NetConfig() # # config = net.getConfig() # # print config import ifcfg import json interfaces = ifcfg.interfaces() for i in interfaces.keys(): # print interfaces[i] interface = interfaces[i] for j in interface.keys(): if j is not None and interface is not None: print j + " : " + str(interface[j])
def _list_interfaces(self): return ifcfg.interfaces().values()