def test_ipsec_rhel8_with_specific_arg_test(self): ipsec_tunnel = IPsecTunnel( IPv4Interface('192.168.1.1/24'), IPv4Interface('192.168.1.2/24'), 'aes128-sha2', 'SUPER_PASS_IPSEC', IPsecTunnel.Mode.TUNNEL, replay_window=128, encapsulation=IPsecTunnel.Encapsulation.YES, nic_offload=IPsecTunnel.Offload.YES, ) conn_file_obj = IPsecRHEL8ConnFile(ipsec_tunnel) excpexted_output = """\ conn IPv4_tunnel_aes128-sha2_encap-yes_192.168.1.1_192.168.1.2 \ttype=tunnel \tauthby=secret \tleft=192.168.1.1 \tright=192.168.1.2 \tphase2=esp \tphase2alg=aes128-sha2 \tkeyexchange=ike \tpfs=yes \tauto=start \tencapsulation=yes \treplay-window=128 \tnic-offload=yes """ self.assertEqual(excpexted_output, conn_file_obj._make_content())
def __init__(self, node1: Node, node2: Node): self.type: ConnectionType if isinstance(node1, Computer) and isinstance(node2, Computer): raise DemoerException( 'A connection between two Computers cannot be created') if isinstance(node1, Computer) and len(node1.connections) > 0 \ or isinstance(node2, Computer) and len(node2.connections) > 0: raise DemoerException('A Computer can have only one connection') if isinstance(node1, Router) and isinstance(node2, Router): for connection in node1.connections | node2.connections: if connection.type == ConnectionType.TUNNEL: raise DemoerException( 'A Router can have only one tunnel connection') self.type = ConnectionType.TUNNEL else: self.type = ConnectionType.INTRA_NETWORK self.node1 = node1 self.node2 = node2 self.address1 = IPv4Interface('0.0.0.0/0') self.address2 = IPv4Interface('0.0.0.0/0') self.arg: Any
def _check_ip(net_if, ip_addr): """Check if interface has IP and if it matches target IP Args: net_if : DVB network interface name ip_addr : Target IP address for the DVB interface slash subnet mask Returns: (Bool, Bool) Tuple of booleans. The first indicates whether interface already has an IP. The second indicates whether the interface IP (if existing) matches with respect to a target IP. """ try: res = subprocess.check_output(["ip", "addr", "show", "dev", net_if], stderr=subprocess.DEVNULL) except subprocess.CalledProcessError as e: return False, False has_ip = False ip_ok = False for line in res.splitlines(): if "inet" in line.decode() and "inet6" not in line.decode(): has_ip = True # Check if IP matches target inet_info = line.decode().split() inet_if = IPv4Interface(inet_info[1]) target_if = IPv4Interface(ip_addr) ip_ok = (inet_if == target_if) break return has_ip, ip_ok
def get_cluster_members(dnac, maglev): print("Getting other cluster members..") with connect(dnac, maglev) as conn: cmd = "etcdctl ls /maglev/config | grep node | sed -e 's#$#/network#' | xargs -n1 etcdctl get | jq -r '" jq = '.[] |.inet | .host_ip + "/" + .netmask' final = "' | grep -v '^[/]$' " full_cmd = cmd + jq + final #print(full_cmd) stdin, stdout, stderr = conn.exec_command(full_cmd) iplist = stdout.readlines() try: dnacip = ip_address(unicode(dnac, "utf-8")) except NameError: dnacip = ip_address(dnac) network = None for ip in iplist: ipa = IPv4Interface(ip.strip()) print(ipa) if dnacip in ipa.network: network = ipa.network if network == None: print("cannot find matching network on DNAC for {}".format(dnac)) targets = [] for ip in iplist: ipa = IPv4Interface(ip.strip()) if ipa.network == network: targets.append(str(ipa.ip)) return targets
def prepare_spgwc_build(): # ====== Install SPGW-C ================================================== # For a documentation of the installation procedure, see: # https://github.com/OPENAIRINTERFACE/openair-cn-cups/wiki/OpenAirSoftwareSupport#install-spgw-c gitRepository = action_get('spgwc-git-repository') gitCommit = action_get('spgwc-git-commit') gitDirectory = 'openair-cn-cups' # Prepare network configurations: spgwcS11_IfName = 'ens5' spgwcSXab_IfName = 'ens4' configurationS11 = configureInterface(spgwcS11_IfName, IPv4Interface('0.0.0.0/0')) configurationSXab = configureInterface(spgwcSXab_IfName, IPv4Interface('0.0.0.0/0')) # S5S8 dummy interfaces: spgwcS5S8_SGW_IfName = 'dummy0:s5c' configurationS5S8_SGW = configureInterface( spgwcS5S8_SGW_IfName, IPv4Interface('172.58.58.102/24')) spgwcS5S8_PGW_IfName = 'dummy0:p5c' configurationS5S8_PGW = configureInterface( spgwcS5S8_PGW_IfName, IPv4Interface('172.58.58.101/24')) # NOTE: # Double escaping is required for \ and " in "command" string! # 1. Python # 2. bash -c "<command>" # That is: $ => \$ ; \ => \\ ; " => \\\" commands = """\ echo \\\"###### Preparing system ###############################################\\\" && \\ echo -e \\\"{configurationS11}\\\" | sudo tee /etc/network/interfaces.d/61-{spgwcS11_IfName} && sudo ifup {spgwcS11_IfName} || true && \\ echo -e \\\"{configurationSXab}\\\" | sudo tee /etc/network/interfaces.d/62-{spgwcSXab_IfName} && sudo ifup {spgwcSXab_IfName} || true && \\ sudo ip link add dummy0 type dummy || true && \\ echo -e \\\"{configurationS5S8_SGW}\\\" | sudo tee /etc/network/interfaces.d/63-{spgwcS5S8_SGW_IfName} && sudo ifup {spgwcS5S8_SGW_IfName} || true && \\ echo -e \\\"{configurationS5S8_PGW}\\\" | sudo tee /etc/network/interfaces.d/64-{spgwcS5S8_PGW_IfName} && sudo ifup {spgwcS5S8_PGW_IfName} || true && \\ echo \\\"###### Preparing sources ##############################################\\\" && \\ cd /home/nornetpp/src && \\ if [ ! -d \\\"{gitDirectory}\\\" ] ; then git clone --quiet {gitRepository} {gitDirectory} && cd {gitDirectory} ; else cd {gitDirectory} && git pull ; fi && \\ git checkout {gitCommit} && \\ cd build/scripts && \\ echo \\\"###### Done! ##########################################################\\\"""".format( gitRepository=gitRepository, gitDirectory=gitDirectory, gitCommit=gitCommit, spgwcS11_IfName=spgwcS11_IfName, spgwcSXab_IfName=spgwcSXab_IfName, spgwcS5S8_SGW_IfName=spgwcS5S8_SGW_IfName, spgwcS5S8_PGW_IfName=spgwcS5S8_PGW_IfName, configurationS11=configurationS11, configurationSXab=configurationSXab, configurationS5S8_SGW=configurationS5S8_SGW, configurationS5S8_PGW=configurationS5S8_PGW) runShellCommands(commands, 'prepare_spgwc_build: preparing SPGW-C build', 'actions.prepare-spgwc-build', 'spgwccharm.prepared-spgwc-build')
def filter_rules_junos(filename, args): parser = JunosFirewallFilterParser() data = parser.parse(filename, expand=True) pp(data) argipaddr = None argsrc = None argdst = None argsrcport = args.src_port argdstport = args.dst_port if args.ipaddress: argipaddr = IPv4Interface(args.ipaddress) if args.src: argsrc = IPv4Interface(args.src) if args.dst: argdst = IPv4Interface(args.dst) def is_subnet_or_not_defined(a, b): if a and b: return IPv4Interface(a).network.subnet_of( IPv4Interface(b).network ) else: return True import itertools for filtername in data.keys(): for termname in data[filtername].keys(): rules = data[filtername][termname] for rule in rules: rulesrc = rule.get('source-address') ruledst = rule.get('destination-address') rulesrcport = rule.get('source-port') ruledstport = rule.get('destination-port') protocol = rule.get('protocol') r = None if args.ipaddress and ( (rulesrc and is_subnet_or_not_defined(args.ipaddress, rulesrc)) or \ (ruledst and is_subnet_or_not_defined(args.ipaddress, ruledst))): r = rule if (argsrc or argdst) and \ is_subnet_or_not_defined(argsrc, rulesrc) and \ is_subnet_or_not_defined(argdst, ruledst): r = rule if r: print( f"{filtername:20s}" f"{termname:20s}" f"{r['source-address']:20s}" f"{str(r['source-port']):16s}" f"{r['destination-address']:20s}" f"{str(r['destination-port']):16s}" f"{r['protocol']:5s}" )
def filter_rules(filename, args): with open(filename, 'r') as f: data = yaml.safe_load(f) dcname = list(data.keys())[0] pgname = list(data[dcname].keys())[0] rules = data[dcname][pgname] argipaddr = None argsrc = None argdst = None argsrcport = args.src_port argdstport = args.dst_port if args.ipaddress: argipaddr = IPv4Interface(args.ipaddress) if args.src: argsrc = IPv4Interface(args.src) if args.dst: argdst = IPv4Interface(args.dst) def is_subnet_or_not_defined(a, b): if a and b: return IPv4Interface(a).network.subnet_of( IPv4Interface(b).network ) else: return True result = [] for rule in rules: rulesrc = rule.get('source-address') ruledst = rule.get('destination-address') rulesrcport = rule.get('source-port') ruledstport = rule.get('destination-port') if args.ipaddress and ( (rulesrc and is_subnet_or_not_defined(args.ipaddress, rulesrc)) or \ (ruledst and is_subnet_or_not_defined(args.ipaddress, ruledst))): result.append(rule) continue if (argsrc or argdst) and \ is_subnet_or_not_defined(argsrc, rulesrc) and \ is_subnet_or_not_defined(argdst, ruledst): result.append(rule) continue dcnamepgname = f"{dcname}-{pgname}" for r in result: print( f"{dcnamepgname:20s}" f"{r['description']:20s}" f"{r['source-address']:20s}" f"{str(r['source-port']):16s}" f"{r['destination-address']:20s}" f"{str(r['destination-port']):16s}" f"{r['protocol']:5s}" )
def test_secret_content(self): psw = 'wertyuiop;kdszxcvbn' ipsec_tunnel = IPsecTunnel(IPv4Interface('192.168.1.1/24'), IPv4Interface('192.168.1.2/24'), 'aes128-sha1', psw) ipsec_secret_obj = IPsecSecretsFile(ipsec_tunnel) expected_output = "%s %s : PSK \"%s\"\n" % ( ipsec_tunnel.left_ip.ip, ipsec_tunnel.right_ip.ip, psw) self.assertEqual(expected_output, ipsec_secret_obj._make_content())
def test_ipv4_only(self): """Test IPv4 only interface.""" t = Interfaces( ucr={ 'interfaces/eth0/address': '1.2.3.4', 'interfaces/eth0/netmask': '255.255.255.0', }) assert ['eth0'] == [s.name for _n, s in t.ipv4_interfaces] assert [] == [s.name for s, _n in t.ipv6_interfaces] assert IPv4Interface(u'1.2.3.4/24') == t.get_default_ip_address() assert IPv4Interface(u'1.2.3.4/24') == t.get_default_ipv4_address() assert t.get_default_ipv6_address() is None
def checkAddressing(self, node: Node, address: IPv4Interface): if address == IPv4Interface('0.0.0.0/0'): return interfaces = ((self.node1, self.address1), (self.node2, self.address2)) for node_, address_ in interfaces: if node_ != node and address_ != IPv4Interface('0.0.0.0/0'): if address_.network != address.network: raise DemoerException( 'Addresses must be in the same network') elif address_.ip == address.ip: raise DemoerException('Addresses must not collide')
def __init__(self, namespace, policy_list): self.namespace = namespace self.uuid = policy_list['uuid'] self.host = str(IPv4Interface(policy_list['host']).network) #要判断段是ip还是fqdn,ip要把子网掩码写上 self.port = str(policy_list['port']) self.url = policy_list['url'] self.cilium_name= policy_list['cilium_name'] self.excute = policy_list['excute'] self.wg_ips = policy_list['wg_ips'] self.valid_ips=[] for ip in self.wg_ips: wg_ip=str(IPv4Interface(ip).network) self.valid_ips.append(wg_ip)
def test_ipinterface_array_param(self): self._test_param_val([ IPv4Interface('192.168.0.1'), IPv4Interface('192.168.0.1/24'), IPv6Interface('2001:db8:85a3:0:0:8a2e:370:7334'), IPv6Interface('2001:db8:85a3:0:0:8a2e:370:7334/64') ]) self._test_param_val([ IPv6Interface('2001:db8:85a3:0:0:8a2e:370:7334'), IPv6Interface('2001:db8:85a3:0:0:8a2e:370:7334/64'), IPv4Interface('192.168.0.1'), IPv4Interface('192.168.0.1/24'), ])
def instantiate(self, scenario_cfg, context_cfg): self._start_server() self._result = { "packets_received": 0, "rtt": 0, } self.setup_helper.setup_vnf_environment() intf = self.vnfd_helper.interfaces[0]["virtual-interface"] self.resource_helper.cmd_kwargs = { 'target_ip': IPv4Interface(intf["dst_ip"]).ip.exploded, 'local_ip': IPv4Interface(intf["local_ip"]).ip.exploded, 'local_if_name': intf["local_iface_name"].split('/')[0], }
def _cni_ipam(host_cidrv4: str, host_gateway: str): """ see: https://github.com/containernetworking/cni/blob/master/SPEC.md#ip-allocation see: https://github.com/containernetworking/plugins/tree/master/plugins/ipam/host-local With the class variables provide a way to generate a static host-local ipam :param host_cidrv4: an host IP with its CIDR prefixlen, eg: '10.0.0.42/8' :param host_gateway: an host IP for the gateway, eg: '10.0.0.1' :return: dict """ interface = IPv4Interface(host_cidrv4) subnet = interface.network try: assert 0 <= ConfigSyncSchedules.sub_ips <= 256 assert (lambda x: x & (x - 1) == 0)(ConfigSyncSchedules.sub_ips) except AssertionError: raise ValueError( 'sub_ips must be a power of two, in [0, 256] interval') if ConfigSyncSchedules.sub_ips > 0: ip_last_decimal_field = int(str(interface.ip).split('.')[-1]) interface = IPv4Interface(interface.network.network_address + ip_last_decimal_field * ConfigSyncSchedules.sub_ips) range_start = interface.ip + ConfigSyncSchedules.skip_ips range_end = range_start + ConfigSyncSchedules.range_nb_ips ipam = { "type": "host-local", "subnet": "%s" % (str(subnet)), "rangeStart": str(range_start), "rangeEnd": str(range_end), "gateway": host_gateway, "routes": [ { "dst": "%s/32" % EC.perennial_local_host_ip, "gw": str(IPv4Interface(host_cidrv4).ip) }, { "dst": "0.0.0.0/0" }, ], "dataDir": "/var/lib/cni/networks" } return ipam
def test_ipv4_multi(self): """Test multiple IPv4 interfaces.""" t = Interfaces( ucr={ 'interfaces/eth0/address': '1.2.3.4', 'interfaces/eth0/netmask': '255.255.255.0', 'interfaces/eth1/address': '2.3.4.5', 'interfaces/eth1/netmask': '255.255.255.0', }) assert ['eth0' == 'eth1'], [s.name for _n, s in t.ipv4_interfaces] assert [] == [s.name for s, _n in t.ipv6_interfaces] assert IPv4Interface(u'1.2.3.4/24') == t.get_default_ip_address() assert IPv4Interface(u'1.2.3.4/24') == t.get_default_ipv4_address() assert t.get_default_ipv6_address() is None
def configureInterface(name, ipv4Interface=IPv4Interface('0.0.0.0/0'), ipv4Gateway=None, ipv6Interface=None, ipv6Gateway=None, metric=1): # NOTE: # Double escaping is required for \ and " in "configuration" string! # 1. Python # 2. bash -c "<command>" configuration = 'auto ' + name + '\\\\n' # ====== IPv4 ============================================================ if ipv4Interface == IPv4Interface('0.0.0.0/0'): configuration = configuration + 'iface ' + name + ' inet dhcp' else: configuration = configuration + \ 'iface ' + name + ' inet static\\\\n' + \ '\\\\taddress ' + str(ipv4Interface.ip) + '\\\\n' + \ '\\\\tnetmask ' + str(ipv4Interface.netmask) + '\\\\n' if ((ipv4Gateway != None) and (ipv4Gateway != IPv4Address('0.0.0.0'))): configuration = configuration + \ '\\\\tgateway ' + str(ipv4Gateway) + '\\\\n' + \ '\\\\tmetric ' + str(metric) + '\\\\n' configuration = configuration + '\\\\n' # ====== IPv6 ============================================================ if ipv6Interface == None: configuration = configuration + \ '\\\\niface ' + name + ' inet6 manual\\\\n' + \ '\\\\tautoconf 0\\\\n' elif ipv6Interface == IPv6Interface('::/0'): configuration = configuration + \ '\\\\niface ' + name + ' inet6 dhcp\\\\n' + \ '\\\\tautoconf 0\\\\n' else: configuration = configuration + \ '\\\\niface ' + name + ' inet6 static\\\\n' + \ '\\\\tautoconf 0\\\\n' + \ '\\\\taddress ' + str(ipv6Interface.ip) + '\\\\n' + \ '\\\\tnetmask ' + str(ipv6Interface.network.prefixlen) + '\\\\n' if ((ipv6Gateway != None) and (ipv6Gateway != IPv6Address('::'))): configuration = configuration + \ '\\\\tgateway ' + str(ipv6Gateway) + '\\\\n' + \ '\\\\tmetric ' + str(metric) + '\\\\n' return configuration
def test_ipv6_disjunct(self): """Test disjunct IPv4 IPv6 interfaces.""" t = Interfaces( ucr={ 'interfaces/eth0/address': '2.3.4.5', 'interfaces/eth0/netmask': '255.255.255.0', 'interfaces/eth1/ipv6/default/address': '1:2:3:4:5:6:7:8', 'interfaces/eth1/ipv6/default/prefix': '64', }) assert ['eth0'] == [s.name for _n, s in t.ipv4_interfaces] assert ['eth1'] == [s.name for s, _n in t.ipv6_interfaces] assert IPv4Interface(u'2.3.4.5/24') == t.get_default_ip_address() assert IPv4Interface(u'2.3.4.5/24') == t.get_default_ipv4_address() assert IPv6Interface( u'1:2:3:4:5:6:7:8/64') == t.get_default_ipv6_address()
def prepare_spgwc_build(): vduHelper.beginBlock('prepare_spgwc_build') try: # ====== Get SPGW-C parameters ======================================== # For a documentation of the installation procedure, see: # https://github.com/OPENAIRINTERFACE/openair-cn-cups/wiki/OpenAirSoftwareSupport#install-spgw-c gitRepository = function_get('spgwc-git-repository') gitCommit = function_get('spgwc-git-commit') gitDirectory = 'openair-spgwc' # Prepare network configurations: spgwcS11_IfName = 'ens5' spgwcSXab_IfName = 'ens4' configurationS11 = vduHelper.makeInterfaceConfiguration(spgwcS11_IfName, IPv4Interface('0.0.0.0/0')) configurationSXab = vduHelper.makeInterfaceConfiguration(spgwcSXab_IfName, IPv4Interface('0.0.0.0/0')) # S5S8 dummy interfaces: spgwcS5S8_SGW_IfName = 'dummy0' configurationS5S8_SGW = vduHelper.makeInterfaceConfiguration(spgwcS5S8_SGW_IfName, IPv4Interface('172.58.58.102/24'), createDummy = True) spgwcS5S8_PGW_IfName = 'dummy1' configurationS5S8_PGW = vduHelper.makeInterfaceConfiguration(spgwcS5S8_PGW_IfName, IPv4Interface('172.58.58.101/24'), createDummy = True) # ====== Prepare system =============================================== vduHelper.beginBlock('Preparing system') vduHelper.configureInterface(spgwcS11_IfName, configurationS11, 61) vduHelper.configureInterface(spgwcSXab_IfName, configurationSXab, 62) vduHelper.configureInterface(spgwcS5S8_SGW_IfName, configurationS5S8_SGW, 63) vduHelper.configureInterface(spgwcS5S8_PGW_IfName, configurationS5S8_PGW, 64) vduHelper.testNetworking() vduHelper.waitForPackageUpdatesToComplete() vduHelper.endBlock() # ====== Prepare sources ============================================== vduHelper.beginBlock('Preparing sources') vduHelper.fetchGitRepository(gitDirectory, gitRepository, gitCommit) vduHelper.endBlock() message = vduHelper.endBlock() function_set( { 'outout': message } ) set_flag('spgwccharm.prepared-spgwc-build') except: message = vduHelper.endBlockInException() function_fail(message) finally: clear_flag('actions.prepare-spgwc-build')
def get_ip_from_qga(self): """ In [26]: v2.interfaceAddresses(source=1) Out[26]: {'eth0': {'addrs': [{'addr': '10.6.36.50', 'prefix': 24, 'type': 0}, {'addr': 'fe80::216:3eff:fee2:c90f', 'prefix': 64, 'type': 1}], 'hwaddr': '00:16:3e:e2:c9:0f'}, 'lo': {'addrs': [{'addr': '127.0.0.1', 'prefix': 8, 'type': 0}, {'addr': '::1', 'prefix': 128, 'type': 1}], 'hwaddr': '00:00:00:00:00:00'}} """ #vm_xml_obj = vm_xml(self.vm_obj.XMLDesc()) #self.vm_macs = vm_xml_obj.get_macs() #vm_mac_addrs = [ vm_mac.get('mac_address') for vm_mac in self.vm_macs ] my_ip_info = [] # 如果vm是运行的 if self.vm_obj.isActive(): try: # 通过 interfaceAddresses() 来获取ip信息 ip_info = self.vm_obj.interfaceAddresses(source=1) except Exception as e: raise else: for key in ip_info: if ip_info[key]['hwaddr'] in self.vm_mac_addrs: for addr in ip_info[key]['addrs']: # type == 0 是ipv4的地址 if addr['type'] == 0: ip_with_prefix = addr['addr'] + '/' + str(addr['prefix']) my_netmask = str(IPv4Interface(ip_with_prefix.decode()).netmask) my_ip_info.append({'addr': addr['addr'], 'prefix': addr['prefix'], 'netmask': str(my_netmask), 'hwaddr': ip_info[key]['hwaddr']}) self.ip_info = my_ip_info return self.ip_info
def get_ip_from_guestfs(self): my_ip_info = [] g = guestfs.GuestFS(python_return_dict=True) g.add_domain(self.vm_name, readonly=True) g.launch() root_dev = guestfs_mount_root(g) if isinstance(root_dev, str): if_files = g.ls('/etc/sysconfig/network-scripts/') # 找到以 ifcfg 开头且不是以 lo 结尾的网卡配置文件 if_confs = filter(lambda x: x.startswith("ifcfg") and not x.endswith("lo"), if_files) for if_conf in if_confs: if_conf_content = g.cat("/etc/sysconfig/network-scripts/%s" % if_conf) # 获取一个ip_conf_file 的对象 if_conf_obj = ip_conf_file(if_conf_content) # 获取mac地址 if_conf_hwaddr = if_conf_obj.get('HWADDR') if if_conf_hwaddr: if_conf_hwaddr = if_conf_hwaddr.lower() # 获取ipaddr if_conf_ipaddr = if_conf_obj.get('IPADDR') # 获取子网掩码 if_conf_netmask = if_conf_obj.get('NETMASK') # 子网掩码的数字表示形式的变量 my_prefix = '' if if_conf_ipaddr and if_conf_netmask: ip_with_netmask = if_conf_ipaddr + '/' + if_conf_netmask my_prefix = IPv4Interface(ip_with_netmask.decode()).with_prefixlen.split('/')[1] if if_conf_hwaddr in self.vm_mac_addrs: my_ip_info.append({'addr': if_conf_ipaddr, 'netmask': if_conf_netmask, 'prefix': my_prefix, 'hwaddr': if_conf_hwaddr}) self.ip_info = my_ip_info return self.ip_info else: raise ValueError("Can't find the root_dev, code:%s" % root_dev)
def handle_cdp_data(self, cdp_packet, server_ip): for cdp_stream in cdp_packet.data_items_by_type.get( CDPStreamInformation.type, []): # Get network information in the CDP Stream Information data item ip = cdp_stream.destination_ip port = cdp_stream.destination_port ifc = cdp_stream.interface_ip netmask = cdp_stream.interface_netmask alias = cdp_stream.name stream = StreamInformation(ip, port, ifc, netmask, alias) # Avoids duplicating of packets caused by listening to the same data on multiple interfaces if stream.interface == ip_address(0): stream.interface = server_ip stream.network_address = IPv4Interface( str(stream.interface) + '/' + str(stream.netmask)).network # Check if there is already information about this CUWB network and update the CDP streams if cdp_packet.serial_number in self.available_networks: self.available_networks[cdp_packet.serial_number].cdp_streams[ stream.alias] = stream # Reset timer since we are still getting data from this CUWB server self.network_timers[cdp_packet.serial_number].reset() else: net_info = CuwbNetworkInformation(source_ip=server_ip) net_info.cdp_streams[stream.alias] = stream self.available_networks[cdp_packet.serial_number] = net_info # Start timer since this is the first time we hear from this CUWB server self.add_timer(cdp_packet.serial_number) for instance_info in cdp_packet.data_items_by_type.get( InstanceAnnounce.type, []): # Check if there is already information about this CUWB network and update the instance name if cdp_packet.serial_number in self.available_networks: self.available_networks[ cdp_packet. serial_number].instance_name = instance_info.instance_name # Reset timer since we are still getting data from this CUWB server self.network_timers[cdp_packet.serial_number].reset() else: net_info = CuwbNetworkInformation(source_ip=server_ip) net_info.instance_name = instance_info.instance_name self.available_networks[cdp_packet.serial_number] = net_info # Start timer since this is the first time we hear from this CUWB server self.add_timer(cdp_packet.serial_number) for hostname_info in cdp_packet.data_items_by_type.get( HostnameAnnounce.type, []): # Check if there is already information about this host and update the hostname if cdp_packet.serial_number in self.available_networks: self.available_networks[ cdp_packet.serial_number].hostname = hostname_info.hostname # Reset timer since we are still getting data from this CUWB server self.network_timers[cdp_packet.serial_number].reset() else: net_info = CuwbNetworkInformation(source_ip=server_ip) net_info.hostname = hostname_info.hostname self.available_networks[cdp_packet.serial_number] = net_info # Start timer since this is the first time we hear from this CUWB server self.add_timer(cdp_packet.serial_number)
def _deserialize(self, value, attr, data, **kwargs): if not value: return None elif isinstance(value, str): return IPv4Interface(value) else: return super()._deserialize(value, attr, data, **kwargs)
def _get_ipv4_addresses(self, host: str) -> Dict[str, List[IPv4Address]]: """ Get IPv4 Addresses for ``host``. Args: host (str): Whether to get IP Addresses for `self` or `peer` device. Returns: dict: The list of ``ip_interface`` objects mapped to their associated interface. Example: >>> dev = ASADevice(**connection_args) >>> dev._get_ipv4_addresses("self") {'outside': [IPv4Interface('10.132.8.6/24')], 'inside': [IPv4Interface('10.1.1.2/23')]} >>> dev._get_ipv4_addresses("peer") {'outside': [IPv4Interface('10.132.8.7')], 'inside': [IPv4Interface('10.1.1.3')]} >>> """ if host == "self": command = "show ip address" elif host == "peer": command = "failover exec mate show ip address" show_ip_address = self.show(command) re_ip_addresses = RE_SHOW_IP_ADDRESS.findall(show_ip_address) return { interface: [IPv4Interface(f"{address}/{netmask}")] for interface, address, netmask in re_ip_addresses }
def is_net_ip4(value): """ Determine if this given value is an IPv4 network value or an IPv4 interface value; as defined by the ipaddress module Parameters ---------- value : str The value to check Returns ------- bool True if the value is any valid IPv4 thing False otherwise """ for test in [lambda x: IPv4Network(x)._prefixlen != 32, lambda x: IPv4Interface(x)._prefixlen != 32]: try: return bool(test(value)) except: pass return False
def _load_interfaces(self): fw_settings = load_configuration('config')['settings'] server_settings = load_configuration('dhcp_server')['dhcp_server'] fw_intf = fw_settings['interfaces'] dhcp_intfs = server_settings['interfaces'] # ident for intf in self.DHCPServer._intfs: # friendly name for _intf, settings in dhcp_intfs.items(): # ensuring the iterfaces match since we cannot guarantee order if (intf != settings['ident']): continue # passing over disabled server interfaces. NOTE: DEF temporary if not dhcp_intfs[_intf]['enabled']: continue # creating ipv4 interface object which will be associated with the ident in the config. # this can then be used by the server to identify itself as well as generate its effective # subnet based on netmask for ip handouts or membership tests. intf_ip = IPv4Interface( str(fw_intf[_intf]['ip']) + '/' + str(fw_intf[_intf]['netmask'])) # initializing server options so the auto loader doesnt have to worry about it. self.DHCPServer.options[intf] = {} # updating general network information for interfaces on server class object. these will never change # while the server is running. for interfaces changes, the server must be restarted. self.DHCPServer.intf_settings[intf] = {'ip': intf_ip}
def test_ipaddress(self): assert dump(IPv4Address('10.10.10.1')) == '10.10.10.1' assert dump(IPv4Network('10.10.10.0/24')) == '10.10.10.0/24' assert dump(IPv4Interface('10.10.10.1/24')) == '10.10.10.1/24' assert dump(IPv6Address('fe80::123')) == 'fe80::123' assert dump(IPv6Network('fe80::/64')) == 'fe80::/64' assert dump(IPv6Interface('fe80::123/64')) == 'fe80::123/64'
def __init__(self, name, alias=None, link=None, device=None, ipv4=None, ipv6=None, type=None, **kwargs): super(Interface, self).__init__(name, alias) # initialize self self.type = type if link: link.connect_interface(self) if device: device.add_interface(self) if ipv4: self.ipv4 = IPv4Interface(ipv4) else: self.ipv4 = None if ipv6: self.ipv6 = IPv6Interface(ipv6) else: self.ipv6 = None # add other Key value pair for name, value in kwargs: setattr(self, name, value)
def _clean_junos_data(self, processed_data, _): drop_indices = [] for i, entry in enumerate(processed_data): if entry['_entryType'] == 'overview': routerId = entry['routerId'] continue if not entry.get('ifname', ''): drop_indices.append(i) continue entry['routerId'] = routerId # Is this right? Don't have a down interface example entry['state'] = 'up' entry['passive'] = entry['passive'] == "Passive" if entry['networkType'] == "LAN": entry['networkType'] = "broadcast" entry['stub'] = not entry['stub'] == 'Not Stub' entry['ipAddress'] = IPv4Interface( f'{entry["ipAddress"]}/{entry["maskLen"]}').with_prefixlen entry['maskLen'] = int(entry['ipAddress'].split('/')[1]) entry['vrf'] = 'default' # Juniper doesn't provide this info entry['authType'] = entry['authType'].lower() entry['networkType'] = entry['networkType'].lower() # Skip the original record as we don't need the overview record processed_data = np.delete(processed_data, drop_indices).tolist() return processed_data[1:]
def _parse_addresses( out: str ) -> Tuple[Optional[str], List[IPv4Interface], List[IPv6Interface]]: """Parse the output of an ip address command :return: mac, [ipv4], [ipv6]""" # 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state ... # link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 # inet 127.0.0.1/8 scope host lo # valid_lft forever preferred_lft forever # inet6 ::1/128 scope host # valid_lft forever preferred_lft forever mac = None v4 = [] v6 = [] for line in out.strip(' \n\t\r').split('\n'): parts = line.strip(' \n\t\r').split(' ') try: t = parts[0] if t == 'inet': v4.append(IPv4Interface(parts[1])) elif t == 'inet6': v6.append(IPv6Interface(parts[1])) elif 'link/' in t: mac = parts[1] except IndexError: log.error('Malformed ip-address line:', line) return mac, v4, v6
def test_basic(self): """Test basic functions.""" i = _Iface({ 'name': 'NAME', 'order': 42, 'type': 'static', 'start': 'yes', 'address': '1.2.3.4', 'netmask': '255.255.255.0', 'network': '1.2.3.0', 'broadcast': '1.2.3.255', 'options/2': '2', 'options/1': '1', 'route/3': 'foo', 'route/2': 'host 192.168.0.240', 'route/1': 'net 192.168.0.0 netmask 255.255.255.128', }) assert 'NAME' == i.name assert 42 == i.order assert 'static' == i.type assert i.start assert IPv4Address(u'1.2.3.0') == i.network assert IPv4Address(u'1.2.3.255') == i.broadcast assert IPv4Interface(u'1.2.3.4/24') == i.ipv4_address() assert i.ipv6_address() is None assert ['1', '2'] == list(i.options) assert [ 'net 192.168.0.0 netmask 255.255.255.128', 'host 192.168.0.240' ] == list(i.routes)