def ipaddr(self, value): if isinstance(value, (str,IPAddr)): self.__ipaddr = ip_interface(value) elif value is None: self.__ipaddr = ip_interface('0.0.0.0') else: raise Exception("Invalid type assignment to IP address (must be string or existing IP address)")
def test_create_network_interface(self): network_interface = NetworkInterface(0, "eth0") assert isinstance(network_interface, NetworkInterface) self.assertEqual(Status.unknown, network_interface.status) network_interface.mac = "d8:31:26:45:56:2f" network_interface.add_ip_address("192.168.1.1", 24) network_interface.add_ip_address("fe80::a11:96ff:fe05:3024", 64) network_interface.status = Status.up network_interface.wifi_information = self._get_wifi_informations() self.assertEqual("eth0", network_interface.name) self.assertEqual("d8:31:26:45:56:2f", network_interface.mac) self.assertEqual(Status.up, network_interface.status) self.assertEqual(ipaddress.ip_interface("192.168.1.1/24"), network_interface.ipaddress_lst[0]) self.assertEqual(ipaddress.ip_interface("fe80::a11:96ff:fe05:3024/64"), network_interface.ipaddress_lst[1]) self.assertEqual("0x1", network_interface.wifi_information.wdev) self.assertEqual(WlanType.managed, network_interface.wifi_information.type) self.assertEqual(1, network_interface.wifi_information.channel) self.assertEqual(20, network_interface.wifi_information.channel_width) self.assertEqual(2412, network_interface.wifi_information.channel_center1)
def build_ospf(self, router): cfg = super(MininetRouterConfig, self).build_ospf(router) networks = [] for itf in router.ospf_interfaces(): c = itf.params.get('cost', FIBBING_MIN_COST) if c > 0: cfg.interfaces.append( ConfigDict(name=itf.name, description=str(itf.link), ospf=ConfigDict( cost=c, priority=10, dead_int=router.dead_interval, hello_int=router.hello_interval))) area = itf.params.get('area', FIBBING_DEFAULT_AREA) networks.append((ip_interface('%s/%s' % (itf.ip, itf.prefixLen)) .network, area)) # TODO figure out the private config knob so that the private # addresses dont create redundant OSPF session over the same # interface ... try: networks.extend((ip_interface(net).network, area) for net in itf.params[PRIVATE_IP_KEY]) except KeyError: pass # No private ip on that interface else: cfg.passive_interfaces.append(itf) for net, area in networks: cfg.networks.append(ConfigDict(domain=net.with_prefixlen, area=area)) return cfg
def netmask(self, value): if isinstance(value, (IPAddr,str,int)): self.__ipaddr = ip_interface("{}/{}".format(self.__ipaddr.ip, str(value))) elif value is None: self.__ipaddr = ip_interface("{}/32".format(self.__ipaddr.ip)) else: raise Exception("Invalid type assignment to netmask (must be IPAddr, string, or int)")
def get_ipv4_addr(): def hex_to_cidr(num): cidr = 0 while num: cidr += (num & 0x01) num >>= 1 return cidr gc = GlobalConfiguration.objects.all()[0] ipv4gateway = gc.gc_ipv4gateway if not ipv4gateway: return ipv4gateway_obj = ipaddress.ip_interface(ipv4gateway) _n = notifier() iface = _n.get_default_interface() ii = _n.get_interface_info(iface) if 'ipv4' in ii: ipv4_info = ii['ipv4'] for i in ipv4_info: ipv4addr = str(i['inet']) netmask = str(hex_to_cidr(int(i['netmask'], 0))) ipv4_obj = ipaddress.ip_interface('%s/%s' % (ipv4addr, netmask)) ipv4_network = ipv4_obj.network if ipv4gateway_obj in ipv4_network: return ipv4addr
def _check_network(self, compute): """ Check that the VM is in the same subnet as the local server """ try: vm_interfaces = yield from compute.interfaces() vm_interface_netmask = None for interface in vm_interfaces: if interface["ip_address"] == self.ip_address: vm_interface_netmask = interface["netmask"] break if vm_interface_netmask: vm_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, vm_interface_netmask)).network for compute_id in self._controller.computes: if compute_id == "local": compute = self._controller.get_compute(compute_id) interfaces = yield from compute.interfaces() netmask = None for interface in interfaces: if interface["ip_address"] == compute.host_ip: netmask = interface["netmask"] break if netmask: compute_network = ipaddress.ip_interface("{}/{}".format(compute.host_ip, netmask)).network if vm_network.compare_networks(compute_network) != 0: msg = "The GNS3 VM ({}) is not on the same network as the {} server ({}), please make sure the local server binding is in the same network as the GNS3 VM".format( vm_network, compute_id, compute_network) self._controller.notification.emit("log.warning", {"message": msg}) except ComputeError as e: log.warning("Could not check the VM is in the same subnet as the local server: {}".format(e))
def getNameFromIP(self, x): """ Returns the name of the host or the router given the ip of the router or the ip of the router's interface towards that subnet. """ if x.find("/") == -1: # it means x is a router id ip_router = ipaddress.ip_address(x) name = [ name for name, values in self.network.iteritems() if values["type"] == "router" and ipaddress.ip_address(values["routerid"]) == ip_router ][0] return name elif "C" not in x: # it means x is an interface ip and not the # weird C_0 ip_iface = ipaddress.ip_interface(x) hosts = [(n, v) for n, v in self.network.iteritems() if v["type"] == "host"] for (n, v) in hosts: for key, val in v.iteritems(): if isinstance(val, dict): ip_iface2 = ipaddress.ip_interface(val["ip"]) if ip_iface.ip == ip_iface2.ip: return n else: return None
def gen_physical_ports(port_list): """ Find all enabled physical interfaces of this :param port_list: The list of all physical ports that should be analyzed :return: A list of Tuple (interface name, ip address) for each active physical interface """ ports = [] for port_name in port_list: try: ip = ip_interface(CFG.get(port_name, 'ip')) ports.append((port_name, ip)) except ConfigError: try: out = subprocess.check_output(['ip', 'a', 'show', port_name]) for line in out.splitlines(): if 'inet ' in line: line = line.strip(' \t\n') port_addr = ip_interface(line.split(' ')[1]) log.debug('Added physical port %s@%s', port_name, port_addr) ports.append((port_name, port_addr)) break # TODO support multiple IP/interface? except subprocess.CalledProcessError as e: log.exception(e) return ports
def ip_statement(ip): """Return the zebra ip statement for a given ip prefix :type ip: ip_interface, ip_network, ip_address, int, str""" if not isinstance(ip, int): ip = (ip_interface(ip) if not isinstance(ip, basestring) else ip_interface(unicode(ip))).version return 'ipv6' if ip == 6 else 'ip'
def _mask_ip(ipaddr): ipaddr_s = ipaddress.ip_address(ipaddr) if ipaddr_s.version == 4: ipaddr_s = ipaddress.ip_interface(ipaddr + '/24') return str(ipaddr_s.network).replace('0/24', 'xxx') if ipaddr_s.version == 6: ipaddr_s = ipaddress.ip_interface(ipaddr + '/64') return str(ipaddr_s.network).replace(':/64', 'xxxx::') return None
def testAttachIPWithGW(self): container = "c" c = self.__manager.create(container) bridge = "br1" ip = ip_interface(u"192.168.0.1/24") dev = "eth0" gw = ip_interface(u"192.168.0.254/24") c.attachIP(bridge, dev, ip, gw) self.assertEqual(self.__manager.get(), [{"name": container, "options": {}, "segment": bridge, "dev": dev, "IP": ip, "gw": gw}])
def test_inet_adapt(self): cur = self.conn.cursor() psycopg2.extras.register_ipaddress(cur) cur.execute("select %s", [ip.ip_interface('127.0.0.1/24')]) self.assertEquals(cur.fetchone()[0], '127.0.0.1/24') cur.execute("select %s", [ip.ip_interface('::ffff:102:300/128')]) self.assertEquals(cur.fetchone()[0], '::ffff:102:300/128')
def same_subnet(address1, address2, netmask): 'Return True if both addresses are on the same subnet.' if address1 == 'localhost': return same_subnet('127.0.0.1', address2, netmask) if address2 == 'localhost': return same_subnet(address1, '127.0.0.1', netmask) subnet1 = ipaddress.ip_interface(u'%s/%s' % (address1, netmask)) subnet2 = ipaddress.ip_interface(u'%s/%s' % (address2, netmask)) return subnet1 == subnet2
def validate_params(addr, interface, mask, dot1q, tag, allow_secondary, version, state, intf_type, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if state == "present": if addr is None or mask is None: module.fail_json(msg="An IP address AND a mask must be provided " "when state=present.") elif state == "absent" and version == "v6": if addr is None or mask is None: module.fail_json(msg="IPv6 address and mask must be provided when " "state=absent.") if intf_type != "ethernet" and network_api == 'cliconf': if is_default(interface, module) == "DNE": module.fail_json(msg="That interface does not exist yet. Create " "it first.", interface=interface) if mask is not None: try: if (int(mask) < 1 or int(mask) > 32) and version == "v4": raise ValueError elif int(mask) < 1 or int(mask) > 128: raise ValueError except ValueError: module.fail_json(msg="Warning! 'mask' must be an integer between" " 1 and 32 when version v4 and up to 128 " "when version v6.", version=version, mask=mask) if addr is not None and mask is not None: try: ipaddress.ip_interface(u'%s/%s' % (addr, mask)) except ValueError: module.fail_json(msg="Warning! Invalid ip address or mask set.", addr=addr, mask=mask) if dot1q is not None: try: if 2 > dot1q > 4093: raise ValueError except ValueError: module.fail_json(msg="Warning! 'dot1q' must be an integer between" " 2 and 4093", dot1q=dot1q) if tag is not None: try: if 0 > tag > 4294967295: raise ValueError except ValueError: module.fail_json(msg="Warning! 'tag' must be an integer between" " 0 (default) and 4294967295." "To use tag you must set 'addr' and 'mask' params.", tag=tag) if allow_secondary is not None: try: if addr is None or mask is None: raise ValueError except ValueError: module.fail_json(msg="Warning! 'secondary' can be used only when 'addr' and 'mask' set.", allow_secondary=allow_secondary)
def test_inet_array_cast(self): cur = self.conn.cursor() psycopg2.extras.register_ipaddress(cur) cur.execute("select '{NULL,127.0.0.1,::ffff:102:300/128}'::inet[]") l = cur.fetchone()[0] self.assert_(l[0] is None) self.assertEquals(l[1], ip.ip_interface('127.0.0.1')) self.assertEquals(l[2], ip.ip_interface('::ffff:102:300/128')) self.assert_(isinstance(l[1], ip.IPv4Interface), l) self.assert_(isinstance(l[2], ip.IPv6Interface), l)
def testCreateBridgeDifferentIPs(self): ip1 = ip_interface(u"192.168.30.10/24") ip2 = ip_interface(u"192.168.33.10/24") b1 = self.__manager.createBridge(ip1.network) b2 = self.__manager.createBridge(ip2.network) self.assertEqual(self.__manager.get(), [ip1.network, ip2.network]) del b1 self.assertEqual(self.__manager.get(), [ip2.network]) del b2 self.assertEqual(self.__manager.get(), [])
def __call__(self, container_manager, host_manager, parameter): servers = {} for p in parameter: server = Server(container_manager, p["name"], source=p["image"]) for n in p.get("IPs", []): if "gw" in n: server.attachIP(host_manager, n["dev"], ip_interface(unicode(n["IP"])), ip_interface(unicode(n["gw"]))) else: server.attachIP(host_manager, n["dev"], ip_interface(unicode(n["IP"]))) servers[server.getName()] = server return servers
def to_python(self, value): if not value: return value try: if self.store_prefix_length: return ip_interface(value) else: return ip_interface(value).ip except ValueError as e: raise ValidationError(e)
def get_ips_from_interfaces(): res = [] ifs = get_host_subnets() for interface in ifs: ipint = ipaddress.ip_interface(u"%s/%s" % interface) # limit subnet scans to class C only if ipint.network.num_addresses > 255: ipint = ipaddress.ip_interface(u"%s/24" % interface[0]) for addr in ipint.network.hosts(): if str(addr) == interface[0]: continue res.append(str(addr)) return res
def to_python(self, value): if not value: return value if isinstance(value, bytes): value = value.decode('ascii') try: if self.store_prefix_length: return ip_interface(value) else: return ip_interface(value).ip except ValueError as e: raise ValidationError(e)
def validate_whitelist(self, data): for address in data: try: ipaddress.ip_address(address) except: try: ipaddress.ip_network(address) except: try: ipaddress.ip_interface(address) except: raise serializers.ValidationError( "The address {} is not valid".format(address)) return data
def remove_ip(enode, portlbl, addr, shell=None): """ Remove an IP address from an interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to remove from the interface: - IPv4 address to remove from the interface in the form ``'192.168.20.20'`` or ``'192.168.20.20/24'``. - IPv6 address to remove from the interface in the form ``'2001::1'`` or ``'2001::1/120'``. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert portlbl assert ip_interface(addr) port = enode.ports[portlbl] cmd = 'ip addr del {addr} dev {port}'.format(addr=addr, port=port) response = enode(cmd, shell=shell) assert not response
def nmap_scanning(): """ Nmap Scan """ # SCAN all hypervisor interfaces ipv4_found = commands.getstatusoutput("sudo ifconfig -a | grep \'inet addr:\'")[1].split('\n') networks_scaneed = list() for ipv4 in ipv4_found: data = ipv4.split() if_cfg_data = dict() if_cfg_data['ip'] = data[1][data[1].find(':')+1:] if if_cfg_data['ip'] == '127.0.0.1': continue if_cfg_data['bcast'] = data[2][data[2].find(':')+1:] if_cfg_data['mask'] = data[3][data[3].find(':')+1:] if '255.255.255.255' in if_cfg_data['mask']: continue mask = get_mask_slash_notation(if_cfg_data['mask'])[1:] interface = if_cfg_data['ip'] + '/' + mask host4 = ipaddress.ip_interface(u'%s' % interface) network_ip = host4 if int(mask) <= 16: continue commands.getstatusoutput("sudo nmap -sP %s --send-ip" % network_ip) #commands.getstatusoutput("sudo nmap -sP --max-rtt-timeout 500ms %s -T4 --send-ip" % network_ip) networks_scaneed.append(network_ip) return networks_scaneed """
def init_mgmt(self): self.mgmt = ManagementNetwork(self, MGMT_INTERFACE, MGMT_ADDR) self.mgmt.up() self.mgmt.bridge_if.add_address(netif.InterfaceAddress( netif.AddressFamily.INET, ipaddress.ip_interface('169.254.169.254/32') ))
def init_subnet(subnet): _interface = ipaddress.ip_interface(subnet.subnet_address + "/" + subnet.mask) _networks = _interface.network subnet.mask = str(_networks.netmask) subnet.subnet_address = str(_networks.network_address) try: subnet.save() except IntegrityError: subnet.delete() return _host_ip_str_list = [] for _host_ip in list(_networks.hosts()): _host_ip_str_list.append(str(_host_ip)) for exist_host in subnet.hosts.all(): if str(exist_host.ip_address) in _host_ip_str_list: if not exist_host.mask == subnet.mask: exist_host.mask = subnet.mask exist_host.save() _host_ip_str_list.remove(str(exist_host.ip_address)) else: exist_host.delete() need_create_host = [] for _host_ip_str in _host_ip_str_list: host = Host(ip_address=_host_ip_str, mask=subnet.mask, subnet=subnet) need_create_host.append(host) Host.objects.bulk_create(need_create_host) subnet.been_init = True subnet.save() return subnet
def conf_new_iface(system_ip,iface,ipaddr,netmask,gateway,gw_paths=[]): # Generate the correct network and broadcast information iface_info = ipaddress.ip_interface(unicode(ipaddr + "/" + netmask)) cmd = "set /files/etc/network/interfaces/auto[last()+1]/1 %s " % iface cmd = cmd + "set /files/etc/network/interfaces/iface[last()+1] %s " % iface cmd = cmd + "set /files/etc/network/interfaces/iface[.=\\\"%s\\\"]/family inet " % iface cmd = cmd + "set /files/etc/network/interfaces/iface[.=\\\"%s\\\"]/method static " % iface cmd = cmd + "set /files/etc/network/interfaces/iface[.=\\\"%s\\\"]/address %s " % (iface,ipaddr) cmd = cmd + "set /files/etc/network/interfaces/iface[.=\\\"%s\\\"]/netmask %s " % (iface,netmask) cmd = cmd + "set /files/etc/network/interfaces/iface[.=\\\"%s\\\"]/broadcast %s " % (iface, str(iface_info.network.broadcast_address)) cmd = cmd + "set /files/etc/network/interfaces/iface[.=\\\"%s\\\"]/network %s " % (iface, str(iface_info.network.network_address)) if gateway is not None: cmd = cmd + "set /files/etc/network/interfaces/iface[.=\\\"%s\\\"]/gateway %s " %(iface,gateway) # I want this op atomic. I'm going to make the "rm" for (k,v) in gw_paths: if k != iface: cmd = cmd + " rm %s/gateway " % v response = ansible.run_module(host_list=[system_ip], module="av_augeas",args="commands='%s' validate_filepath=no" % cmd) if system_ip in response['dark'] or response['contacted'][system_ip].get('failed',False) == True: return (False, response['dark'][system_ip]) else: return (True,'')
def findClients(self, ipv4): net4 = ipaddress.ip_interface(ipv4.split()[0]) port = 9999 for host in net4.network.hosts(): t = threading.Thread(target=self.checkConnection, args=(str(host), port), daemon=True) t.start() """ try: # print ('trying ', str(host)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.1) s.connect((str(host), port)) print('find active host:', str(host), '!!!!!!!!!!!!!!!!!!') tm = s.recv(1000) # Receive no more than 1024 bytes # why receive nothing here? nick = tm.decode('utf-8') print("The mesg got from the server is %s" % tm.decode('utf-8')) if str(host) not in [c.IP for c in self.clients]: self.clients.append(Client(str(host), nick)) s.close() except: continue """ print("clients found: ", [c.IP for c in self.clients])
def interface(enode, portlbl, addr=None, up=None, shell=None): """ Configure a interface. All parameters left as ``None`` are ignored and thus no configuration action is taken for that parameter (left "as-is"). :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str portlbl: Port label to configure. Port label will be mapped to real port automatically. :param str addr: IPv4 or IPv6 address to add to the interface: - IPv4 address and netmask to assign to the interface in the form ``'192.168.20.20/24'``. - IPv6 address and subnets to assign to the interface in the form ``'2001::1/120'``. :param bool up: Bring up or down the interface. :param str shell: Shell name to execute commands. If ``None``, use the Engine Node default shell. """ assert portlbl port = enode.ports[portlbl] if addr is not None: assert ip_interface(addr) cmd = 'ip addr add {addr} dev {port}'.format(addr=addr, port=port) response = enode(cmd, shell=shell) assert not response if up is not None: cmd = 'ip link set dev {port} {state}'.format( port=port, state='up' if up else 'down' ) response = enode(cmd, shell=shell) assert not response
def filter_routes(routes): """ Filter out routes for loopback addresses and local subnets :param routes: routes list :return: filtered routes list """ aliases = [i.addresses for i in list(netif.list_interfaces().values())] aliases = reduce(lambda x, y: x+y, aliases) aliases = [a for a in aliases if a.af == netif.AddressFamily.INET] aliases = [ipaddress.ip_interface('{0}/{1}'.format(a.address, a.netmask)) for a in aliases] for i in routes: if type(i.gateway) is str: continue if i.af != netif.AddressFamily.INET: continue found = True for a in aliases: if i.network in a.network: found = False break if found: yield i
def test_inet_cast(self): cur = self.conn.cursor() psycopg2.extras.register_ipaddress(cur) cur.execute("select null::inet") self.assert_(cur.fetchone()[0] is None) cur.execute("select '127.0.0.1/24'::inet") obj = cur.fetchone()[0] self.assert_(isinstance(obj, ip.IPv4Interface), repr(obj)) self.assertEquals(obj, ip.ip_interface('127.0.0.1/24')) cur.execute("select '::ffff:102:300/128'::inet") obj = cur.fetchone()[0] self.assert_(isinstance(obj, ip.IPv6Interface), repr(obj)) self.assertEquals(obj, ip.ip_interface('::ffff:102:300/128'))
def _network(self, address, netmask): """ Return CIDR network """ return ipaddress.ip_interface(u'{}/{}'.format(address, netmask)).network
def is_ipv6(self): return isinstance(IPv6Interface, ip_interface(self.ip.encode('utf8')))
import json from ipaddress import ip_interface from unittest import mock from reactive import kubernetes_master from charms.layer import kubernetes_common from charms.layer.kubernetes_common import get_version, kubectl from charms.reactive import endpoint_from_flag, set_flag, is_flag_set, clear_flag from charmhelpers.core import hookenv, unitdata kubernetes_common.get_networks = lambda cidrs: [ ip_interface(cidr.strip()).network for cidr in cidrs.split(",") ] def test_send_default_cni(): hookenv.config.return_value = "test-default-cni" kubernetes_master.send_default_cni() kube_control = endpoint_from_flag("kube-control.connected") kube_control.set_default_cni.assert_called_once_with("test-default-cni") def test_default_cni_changed(): set_flag("kubernetes-master.components.started") kubernetes_master.default_cni_changed() assert not is_flag_set("kubernetes-master.components.started") def test_series_upgrade(): assert kubernetes_master.service_pause.call_count == 0 assert kubernetes_master.service_resume.call_count == 0 kubernetes_master.pre_series_upgrade()
def ip(self): result = ip_interface(self.destination_ip) return str(result.ip)
def calc_total_num_addresses(network_data): (ip_address, _, _) = network_data interface = ipaddress.ip_interface(ip_address) network = interface.network total_num_addresses = ipaddress.ip_network(network).num_addresses return total_num_addresses
def calc_network_address(network_data): (ip_address, _, _) = network_data interface = ipaddress.ip_interface(ip_address) network = interface.network network_address = ipaddress.ip_network(network).network_address return network_address
def _parse_network(self, ipaddr, mask): if not ipaddr or not mask: return None return str(ipaddress.ip_interface(f'{ipaddr}/{mask}').network)
import ipaddress import time my_ip_interface = ipaddress.ip_interface("138.191.0.0/25") my_ip_network = my_ip_interface.network classrooms = list(ipaddress.ip_network( my_ip_network).subnets(prefixlen_diff=2)) small_class_1 = list(ipaddress.ip_network(classrooms[2]).subnets()) small_class_2 = list(ipaddress.ip_network(classrooms[3]).subnets()) offices = list(ipaddress.ip_network(small_class_2[1]).subnets()) print("Routing table:") print("==============") print() for i in range(0, 2): print("Lab " + str(i + 1) + ":") print("------\n") print("Network address: {}".format(offices[i].network_address)) print("Broadcast address: {}".format(offices[i].broadcast_address)) print("Number of hosts: {}".format(len(list(offices[i].hosts())))) print("Valid host range: {} - {}".format( offices[i].network_address + 1, offices[i].broadcast_address - 1)) print() for i in range(3, 5): print("Classroom " + str(i) + ":") print("------------\n") print("Network address: {}".format(small_class_1[i - 3].network_address)) print("Broadcast address: {}".format(
def test_split_ipv6_w_prefixlen(self): interface = ipaddress.ip_interface('a1:b2:c3:d4::/110') self.assertListEqual(split_if(interface), [ 6, 110, '00a1', '00b2', '00c3', '00d4', '0000', '0000', '0000', '0000' ], 'incorrect output')
def _host_ip_to_host_int(host_ip): return ipaddress.ip_interface(ipaddress.ip_network(host_ip))
def parse_topo_defintion(self, topo_definition, po_map, dut_num, neigh_type='VMs'): vmconfig = dict() if topo_definition['topology'][neigh_type] is None: return vmconfig for vm in topo_definition['topology'][neigh_type]: vmconfig[vm] = dict() vmconfig[vm]['intfs'] = [[] for i in range(dut_num)] if 'properties' in vmconfig[vm]: # expand properties list into properties dictinary property_lst = topo_definition['configuration'][vm][ 'properties'] vmconfig[vm]['properties'] = {} for p in property_lst: if p in topo_definition['configuration_properties']: vmconfig[vm]['properties'].update( topo_definition['configuration_properties'][p]) if neigh_type == 'VMs': vmconfig[vm]['interface_indexes'] = [[] for i in range(dut_num)] for vlan in topo_definition['topology'][neigh_type][vm][ 'vlans']: (dut_index, vlan_index, _) = parse_vm_vlan_port(vlan) vmconfig[vm]['interface_indexes'][dut_index].append( vlan_index) if neigh_type == 'NEIGH_ASIC': vmconfig[vm]['asic_intfs'] = [[] for i in range(dut_num)] dut_index = 0 for asic_intf in topo_definition['topology'][neigh_type][vm][ 'asic_intfs']: vmconfig[vm]['asic_intfs'][dut_index].append(asic_intf) # physical interface if 'configuration' in topo_definition: if 'interfaces' in topo_definition['configuration'][vm]: for intf in topo_definition['configuration'][vm][ 'interfaces']: dut_index = 0 if neigh_type == 'NEIGH_ASIC' and re.match( "Eth(\d+)-", intf): vmconfig[vm]['intfs'][dut_index].append(intf) elif 'Ethernet' in intf: if 'dut_index' in topo_definition['configuration'][ vm]['interfaces'][intf]: dut_index = topo_definition['configuration'][ vm]['interfaces'][intf]['dut_index'] if 'lacp' in topo_definition['configuration'][vm][ 'interfaces'][intf]: po_map[topo_definition['configuration'][vm][ 'interfaces'][intf]['lacp']] = dut_index vmconfig[vm]['intfs'][dut_index].append(intf) # ip interface vmconfig[vm]['ip_intf'] = [None] * dut_num vmconfig[vm]['peer_ipv4'] = [None] * dut_num vmconfig[vm]['ipv4mask'] = [None] * dut_num vmconfig[vm]['peer_ipv6'] = [None] * dut_num vmconfig[vm]['ipv6mask'] = [None] * dut_num vmconfig[vm]['bgp_ipv4'] = [None] * dut_num vmconfig[vm]['bgp_ipv6'] = [None] * dut_num vmconfig[vm]['bgp_asn'] = None if 'configuration' in topo_definition: if 'interfaces' in topo_definition['configuration'][vm]: for intf in topo_definition['configuration'][vm][ 'interfaces']: dut_index = 0 if neigh_type == 'NEIGH_ASIC': pass elif 'Ethernet' in intf: if 'dut_index' in topo_definition['configuration'][ vm]['interfaces'][intf]: dut_index = topo_definition['configuration'][ vm]['interfaces'][intf]['dut_index'] elif 'Port-Channel' in intf: m = re.search("(\d+)", intf) dut_index = po_map[int(m.group(1))] if isinstance( topo_definition['configuration'][vm] ['interfaces'], dict ) and 'ipv4' in topo_definition['configuration'][vm][ 'interfaces'][intf] and ('loopback' not in intf.lower()): (peer_ipv4, ipv4_mask) = topo_definition['configuration'][vm][ 'interfaces'][intf]['ipv4'].split('/') vmconfig[vm]['peer_ipv4'][dut_index] = peer_ipv4 vmconfig[vm]['ipv4mask'][dut_index] = ipv4_mask vmconfig[vm]['ip_intf'][dut_index] = intf if isinstance( topo_definition['configuration'][vm] ['interfaces'], dict ) and 'ipv6' in topo_definition['configuration'][vm][ 'interfaces'][intf] and ('loopback' not in intf.lower()): (ipv6_addr, ipv6_mask) = topo_definition['configuration'][vm][ 'interfaces'][intf]['ipv6'].split('/') vmconfig[vm]['peer_ipv6'][ dut_index] = ipv6_addr.upper() vmconfig[vm]['ipv6mask'][dut_index] = ipv6_mask vmconfig[vm]['ip_intf'][dut_index] = intf # bgp vmconfig[vm]['bgp_asn'] = topo_definition['configuration'][vm][ 'bgp']['asn'] dut_asn = topo_definition['configuration_properties'][ 'common']['dut_asn'] for ipstr in topo_definition['configuration'][vm]['bgp'][ 'peers'][dut_asn]: ip_mask = None if '/' in ipstr: (ipstr, ip_mask) = ipstr.split('/') if sys.version_info < (3, 0): ip = ipaddress.ip_address(ipstr.decode('utf8')) else: ip = ipaddress.ip_address(ipstr) for dut_index in range(0, dut_num): if ip.version == 4: # Each VM might not be connected to all the DUT's, so check if this VM is a peer to DUT at dut_index if vmconfig[vm]['peer_ipv4'][dut_index]: ipsubnet_str = vmconfig[vm]['peer_ipv4'][ dut_index] + '/' + vmconfig[vm][ 'ipv4mask'][dut_index] if sys.version_info < (3, 0): ipsubnet = ipaddress.ip_interface( ipsubnet_str.decode('utf8')) else: ipsubnet = ipaddress.ip_interface( ipsubnet_str) if ip in ipsubnet.network: vmconfig[vm]['bgp_ipv4'][ dut_index] = ipstr.upper() elif neigh_type == "NEIGH_ASIC": vmconfig[vm]['bgp_ipv4'][ dut_index] = ipstr.upper() vmconfig[vm]['ipv4mask'][ dut_index] = ip_mask if ip_mask else '32' elif ip.version == 6: # Each VM might not be connected to all the DUT's, so check if this VM is a peer to DUT at dut_index if vmconfig[vm]['peer_ipv6'][dut_index]: ipsubnet_str = vmconfig[vm]['peer_ipv6'][ dut_index] + '/' + vmconfig[vm][ 'ipv6mask'][dut_index] if sys.version_info < (3, 0): ipsubnet = ipaddress.ip_interface( ipsubnet_str.decode('utf8')) else: ipsubnet = ipaddress.ip_interface( ipsubnet_str) if ip in ipsubnet.network: vmconfig[vm]['bgp_ipv6'][ dut_index] = ipstr.upper() elif neigh_type == "NEIGH_ASIC": vmconfig[vm]['bgp_ipv6'][ dut_index] = ipstr.upper() vmconfig[vm]['ipv6mask'][ dut_index] = ip_mask if ip_mask else '128' return vmconfig
def ip_version(ip): return ipaddress.ip_interface(ip).version
def calc_broadcast_address(network_data): (ip_address, _, _) = network_data interface = ipaddress.ip_interface(ip_address) network = interface.network broadcast_address = ipaddress.ip_network(network).broadcast_address return broadcast_address
def parse_unstructured_data(body, interface_name, version, module): interface = {} interface['addresses'] = [] interface['prefixes'] = [] vrf = None body = body[0] splitted_body = body.split('\n') if version == "v6": if "ipv6 is disabled" not in body.lower(): address_list = [] # We can have multiple IPv6 on the same interface. # We need to parse them manually from raw output. for index in range(0, len(splitted_body) - 1): if "IPv6 address:" in splitted_body[index]: first_reference_point = index + 1 elif "IPv6 subnet:" in splitted_body[index]: last_reference_point = index break interface_list_table = splitted_body[ first_reference_point:last_reference_point] for each_line in interface_list_table: address = each_line.strip().split(' ')[0] if address not in address_list: address_list.append(address) interface['prefixes'].append( str(ipaddress.ip_interface(u"%s" % address).network)) if address_list: for ipv6 in address_list: address = {} splitted_address = ipv6.split('/') address['addr'] = splitted_address[0] address['mask'] = splitted_address[1] interface['addresses'].append(address) else: for index in range(0, len(splitted_body) - 1): if "IP address" in splitted_body[index]: regex = '.*IP\saddress:\s(?P<addr>\d{1,3}(?:\.\d{1,3}){3}),\sIP\ssubnet:' + \ '\s\d{1,3}(?:\.\d{1,3}){3}\/(?P<mask>\d+)(?:\s(?P<secondary>secondary)\s)?' + \ '(.+?tag:\s(?P<tag>\d+).*)?' match = re.match(regex, splitted_body[index]) if match: match_dict = match.groupdict() if match_dict['secondary'] is None: match_dict['secondary'] = False else: match_dict['secondary'] = True if match_dict['tag'] is None: match_dict['tag'] = 0 else: match_dict['tag'] = int(match_dict['tag']) interface['addresses'].append(match_dict) prefix = str( ipaddress.ip_interface(u"%(addr)s/%(mask)s" % match_dict).network) interface['prefixes'].append(prefix) try: vrf_regex = '.+?VRF\s+(?P<vrf>\S+?)\s' match_vrf = re.match(vrf_regex, body, re.DOTALL) vrf = match_vrf.groupdict()['vrf'] except AttributeError: vrf = None interface['interface'] = interface_name interface['type'] = get_interface_type(interface_name) interface['vrf'] = vrf return interface
def netmask(self): ip = ip_interface(self.destination_ip) return int(ip.network.prefixlen)
def get_wg_hub(ip, mask): interface_ip = ipaddress.ip_interface(ip + "/" + mask) first_ip = str(interface_ip.network[1]) print(first_ip) return first_ip
def _is_valid(self, value): try: ip = ipaddress.ip_interface(to_unicode(value)) except ValueError: return False return self.version == ip.version
def validate_params(addr, interface, mask, dot1q, tag, allow_secondary, version, state, intf_type, module): if state == "present": if addr is None or mask is None: module.fail_json(msg="An IP address AND a mask must be provided " "when state=present.") elif state == "absent" and version == "v6": if addr is None or mask is None: module.fail_json(msg="IPv6 address and mask must be provided when " "state=absent.") if intf_type != "ethernet" and module.params["provider"][ "transport"] == "cli": if is_default(interface, module) == "DNE": module.fail_json(msg="That interface does not exist yet. Create " "it first.", interface=interface) if mask is not None: try: if (int(mask) < 1 or int(mask) > 32) and version == "v4": raise ValueError elif int(mask) < 1 or int(mask) > 128: raise ValueError except ValueError: module.fail_json(msg="Warning! 'mask' must be an integer between" " 1 and 32 when version v4 and up to 128 " "when version v6.", version=version, mask=mask) if addr is not None and mask is not None: try: ipaddress.ip_interface(u'%s/%s' % (addr, mask)) except ValueError: module.fail_json(msg="Warning! Invalid ip address or mask set.", addr=addr, mask=mask) if dot1q is not None: try: if 2 > dot1q > 4093: raise ValueError except ValueError: module.fail_json(msg="Warning! 'dot1q' must be an integer between" " 2 and 4093", dot1q=dot1q) if tag is not None: try: if 0 > tag > 4294967295: raise ValueError except ValueError: module.fail_json( msg="Warning! 'tag' must be an integer between" " 0 (default) and 4294967295." "To use tag you must set 'addr' and 'mask' params.", tag=tag) if allow_secondary is not None: try: if addr is None or mask is None: raise ValueError except ValueError: module.fail_json( msg= "Warning! 'secondary' can be used only when 'addr' and 'mask' set.", allow_secondary=allow_secondary)
def host_netmask(self): return ipaddress.ip_interface(self.config["net"]["host_ip_mask"]).netmask
def ipv6_default_net(self): return ipaddress.ip_interface(self.server_ipv6 + '/' + str(self.ipv6_prefix)).network
def test_hostmask(self): qs = InetTestModel.objects.annotate(hostmask=Hostmask(F('field'))) self.assertEqual(qs[0].hostmask, ip_interface('0.0.255.255')) self.assertEqual(qs[1].hostmask, ip_interface('::ffff:ffff:ffff:ffff'))
""" import ipaddress # 可以使用 ipaddress 模块很容易的实现这样的计算。例如: if __name__ == '__main__': net = ipaddress.ip_network('123.45.67.64/27') print(net) for a in net: print(a) net6 = ipaddress.ip_network('12:3456:78:90ab:cd:ef01:23:30/125') print(net6) for a in net6: print(a) print(net.num_addresses) print(net[0]) a = ipaddress.ip_address('123.45.67.69') print(a in net) b = ipaddress.ip_address('123.45.67.123') print(b in net) inet = ipaddress.ip_interface('123.45.67.73/27') print(inet.network) print(inet.ip)
def __init__(self, args, spicerack): """Initiliaze the provision runner.""" ensure_shell_is_durable() self.args = args self.netbox = spicerack.netbox() self.netbox_server = spicerack.netbox_server(self.args.host) self.netbox_data = self.netbox_server.as_dict() self.fqdn = self.netbox_server.mgmt_fqdn self.ipmi = spicerack.ipmi(self.fqdn) self.remote = spicerack.remote() if self.netbox_server.virtual: raise RuntimeError( f'Host {self.args.host} is a virtual machine. VMs are not supported.' ) if self.netbox_data['device_type']['manufacturer']['slug'] != 'dell': vendor = self.netbox_data['device_type']['manufacturer']['name'] raise RuntimeError( f'Host {self.args.host} manufacturer is {vendor}. Only Dell is supported.' ) if self.netbox_server.status == 'active' and (not self.args.no_dhcp or not self.args.no_users): raise RuntimeError( f'Host {self.args.host} has active status in Netbox but --no-dhcp and --no-users were not set.' ) # DHCP automation try: self.dhcp_hosts = self.remote.query( f'A:installserver-light and A:{self.netbox_data["site"]["slug"]}' ) except RemoteError: # Fallback to eqiad's install server if the above fails, i.e. for a new DC self.dhcp_hosts = self.remote.query( 'A:installserver-light and A:eqiad') self.dhcp = spicerack.dhcp(self.dhcp_hosts) address = self.netbox.api.ipam.ip_addresses.get( dns_name=self.fqdn).address self.interface = ipaddress.ip_interface(address) self.dhcp_config = DHCPConfMgmt( datacenter=self.netbox_data['site']['slug'], serial=self.netbox_data['serial'], fqdn=self.fqdn, ipv4=self.interface.ip, ) if self.args.no_users: password = '' # nosec else: password = DELL_DEFAULT if self.netbox_server.status in ('active', 'staged'): self.reboot_policy = DellSCPRebootPolicy.GRACEFUL else: self.reboot_policy = DellSCPRebootPolicy.FORCED self.redfish = spicerack.redfish(self.fqdn, 'root', password) self.mgmt_password = spicerack.management_password # Testing that the management password is correct connecting to the current cumin host localhost = gethostname() netbox_localhost = spicerack.netbox_server(localhost) try: spicerack.redfish(netbox_localhost.mgmt_fqdn, 'root').check_connection() except RedfishError: raise RuntimeError( f'The management password provided seems incorrect, it does not work on {localhost}.' ) from None self.config_changes = { 'BIOS.Setup.1-1': { 'BootMode': 'Bios', 'CpuInterconnectBusLinkPower': 'Enabled', 'EnergyPerformanceBias': 'BalancedPerformance', 'InternalUsb': 'Off', 'PcieAspmL1': 'Enabled', 'ProcC1E': 'Enabled', 'ProcCStates': 'Enabled', 'ProcPwrPerf': 'OsDbpm', 'ProcVirtualization': 'Enabled' if self.args.enable_virtualization else 'Disabled', 'ProcX2Apic': 'Disabled', 'SerialComm': 'OnConRedirCom2', 'SerialPortAddress': 'Serial1Com1Serial2Com2', 'SysProfile': 'PerfPerWattOptimizedOs', 'UncoreFrequency': 'DynamicUFS', 'UsbPorts': 'OnlyBackPortsOn', }, 'iDRAC.Embedded.1': { 'IPMILan.1#Enable': 'Enabled', 'IPv4.1#DHCPEnable': 'Disabled', 'IPv4Static.1#Address': str(self.interface.ip), 'IPv4Static.1#DNS1': DNS_ADDRESS, 'IPv4Static.1#Gateway': str(next(self.interface.network.hosts())), 'IPv4Static.1#Netmask': str(self.interface.netmask), 'NICStatic.1#DNSDomainFromDHCP': 'Disabled', }, 'System.Embedded.1': { 'ServerPwr.1#PSRapidOn': 'Disabled', } } netbox_host = self.netbox.api.dcim.devices.get(name=self.args.host) self.multi_gigabit = False if 'gbase-' in netbox_host.primary_ip.assigned_object.type.value: logger.info( 'Detected multi-gigabit interface, will add specific settings.' ) self.multi_gigabit = True ask_confirmation( f'Are you sure to proceed to apply BIOS/iDRAC settings {self.runtime_description}?' )
def ipv4_default_net(self): return ipaddress.ip_interface(self.server_ipv4 + '/' + self.ipv4_netmask).network
def test_netmask(self): qs = InetTestModel.objects.annotate(netmask=Netmask(F('field'))) self.assertEqual(qs[0].netmask, ip_interface('255.255.0.0')) self.assertEqual(qs[1].netmask, ip_interface('ffff:ffff:ffff:ffff::'))
def generatePeeringAddresses(): network = ip_network(u'192.168.%s.0/24' % AutonomousSystem.psIdx) AutonomousSystem.psIdx += 1 return ip_interface('%s/%s' % (network[1], network.prefixlen)), \ ip_interface('%s/%s' % (network[2], network.prefixlen))
def cast_interface(s, cur=None): if s is None: return None # Py2 version force the use of unicode. meh. return ipaddress.ip_interface(text_type(s))
def test_split_ipv4_w_prefixlen(self): interface = ipaddress.ip_interface('1.2.3.4/24') self.assertListEqual(split_if(interface), [4, 24, '1', '2', '3', '4'], 'incorrect output')
def is_valid_ip_interface(address): try: ip_interface(u'{0}'.format(address)) return True except ValueError: return False
import ipaddress print('\n', '*' * 50, '\n') v_ip1 = ipaddress.ip_address('8.8.8.8') print(v_ip1) print('is the ip {} ='.format(v_ip1), v_ip1.is_multicast) print('\n', '*' * 50, '\n') v_network1 = ipaddress.ip_network('10.0.0.0/28') print(v_network1) print(v_network1.broadcast_address) print(v_network1.prefixlen) print(v_network1.num_addresses) for v_ip in v_network1: print(v_ip) print(list(v_network1)) print('\n', '*' * 50, '\n') v_new_network = ipaddress.ip_network(v_network1).subnets(new_prefix=30) print(list(v_new_network)) print('\n', '*' * 50, '\n') v_ip2 = ipaddress.ip_interface('8.8.8.8') print(v_ip1) print(v_ip2.network) print('\n', '*' * 50, '\n')