def _parse_ip(self, directive: str): parts = directive.split('-') if len(parts) > 1: return IPRange(IP(parts[0]), IP(parts[1])) if '/' in parts[0]: return Network(parts[0]) return IP(parts[0])
def add_network_cidr_mapping(self, network_config): """ Method calculates and adds a CloudFormation mapping that is used to set VPC and Subnet CIDR blocks. Calculated based on CIDR block sizes and additionally checks to ensure all network segments fit inside of the specified overall VPC CIDR @param network_config [dict] dictionary of values containing data for creating """ az_count = int(network_config.get('az_count', '2')) network_cidr_base = str( network_config.get('network_cidr_base', '172.16.0.0')) network_cidr_size = str(network_config.get('network_cidr_size', '20')) first_network_address_block = str( network_config.get('first_network_address_block', network_cidr_base)) ret_val = {} cidr_info = Network(network_cidr_base + '/' + network_cidr_size) base_cidr = cidr_info.network().to_tuple()[0] + '/' + str( cidr_info.to_tuple()[1]) ret_val['vpcBase'] = {'cidr': base_cidr} current_base_address = first_network_address_block subnet_types = network_config.get('subnet_types', ['public', 'private']) for index in range(0, len(subnet_types)): subnet_type = subnet_types[index] subnet_size = network_config.get(subnet_type + '_subnet_size', '22') if index != 0: range_reset = Network(current_base_address + '/' + str(subnet_size)) current_base_address = IP( int(range_reset.host_last().hex(), 16) + 2).to_tuple()[0] for subnet_id in range(0, az_count): if not cidr_info.check_collision(current_base_address): raise RuntimeError( 'Cannot continue creating network--current base address is outside the range of the master Cidr block. Found on pass ' + str(index + 1) + ' when creating ' + subnet_type + ' subnet cidrs') ip_info = Network(current_base_address + '/' + str(subnet_size)) range_info = ip_info.network().to_tuple() if 'subnet' + str(subnet_id) not in ret_val: ret_val['subnet' + str(subnet_id)] = dict() ret_val['subnet' + str(subnet_id)][subnet_type] = ip_info.network( ).to_tuple()[0] + '/' + str(ip_info.to_tuple()[1]) current_base_address = IP( int(ip_info.host_last().hex(), 16) + 2).to_tuple()[0] return self.template.add_mapping('networkAddresses', ret_val)
def command_show(args): fields = [ 'address', 'netmask', 'network', 'min', 'max', 'broadcast', 'hosts', 'info', 'ipv4', 'ipv6', 'reverse', 'ipversion' ] n = get_network(args.netaddr) short = any(args.__dict__.get(x, False) for x in fields) filters = [ ('Address', n, IP(str(n)), 0), ('Netmask', "%s = %s" % (n.netmask(), n.mask), n.netmask(), 0), ('Network', "%s/%s" % (n.network(), n.mask), n.network(), 0), ('HostMin', n.host_first(), True, 0), ('HostMax', n.host_last(), True, 0), ('Broadcast', n.broadcast(), True, 4), ('Hosts/Net', n.size() if short else "%s %s" % (n.size(), n.info()), False, 0), ('', n.info(), False, 0), ('IPv4 repr', n.to_ipv4(), True, 6), ('IPv6 repr', n.to_ipv6(args.type), True, 4), ('PTR RR name', n.to_reverse(), False, 0), ('IP version', n.version(), False, 0) ] for idx, f in enumerate(fields): d = filters[idx] o = _(d[0], d[1], args, short, d[2]) if o and ((n.version() == d[3]) or not d[3]) and (args.__dict__.get(f, False) and short or not short): print o
def configure(self, args: str): interface, ip = args.split(" ") if interface in self.interfaces: ip = IP(ip) self.interfaces[interface]['ip'] = ip print("Interface ip successfully assigned to " + interface) else: print("This is not a valid interface name")
def test_ip(method, ip): my_ip = IP(ip) network = Network("10.0.0.0/12") net_list = list(network) if method == "bin": return bin_search(net_list, my_ip) else: return lin_search(net_list, my_ip)
def __init__(self, hostname, ip): self.hostname = hostname self.ip = IP(ip) self.interfaces = {'eth0': {'ip': self.ip, 'connected': None}} # add a functionality to stop instantiating in case this IP was already created if ip in self.registered: raise Exception(f'This device ({ip}) is already registered!') else: self.registered.add(ip)
def __init__(self, hostname, configs): self.interfaces = {} self.hostname = hostname for config in configs: ip = IP(config['ip']) self.interfaces[config['interface']] = {'ip': ip, 'connected': None} if ip in self.registered: raise Exception(f'This device ({ip}) is already registered!') else: self.registered.add(ip)
def get_ffrl_bgp_config(ifaces, proto): from ipcalc import IP _generate_ffrl_gre_tunnels(ifaces) sessions = {} for iface in sorted(ifaces): # We only care for GRE tunnels to the FFRL Backbone if not iface.startswith('gre_ffrl_'): continue iface_config = ifaces.get(iface) # Search for IPv4/IPv6 prefix as defined by proto parameter local = None neighbor = None for prefix in iface_config.get('prefixes', []): if (proto == 'v4' and '.' in prefix) or (proto == 'v6' and ':' in prefix): local = prefix.split('/')[0] # Calculate neighbor IP as <local IP> - 1 if proto == 'v4': neighbor = str(IP(int(IP(local)) - 1, version=4)) else: neighbor = str(IP(int(IP(local)) - 1, version=6)) break # Strip gre_ prefix iface name and use it as identifier for the eBGP session. name = re.sub('gre_ffrl_', 'ffrl_', iface) sessions[name] = { 'local': local, 'neighbor': neighbor, 'bgp_local_pref': iface_config.get('bgp_local_pref', None), } return sessions
def test(self, request: SquidRequest) -> bool: """ Test if this source matches the source (IP or user) of the given request Logic is OR, so return on first match """ # IP test src_ip = IP(request.source_ip) for i in self._ips: if type(i) is IP and i == src_ip: return True if src_ip in i: return True # User test return request.user in self._users
def __call__(self, context, request): url = request.params.get("url") if url is None: return False parts = urlsplit(url) try: ip = IP(gethostbyname(parts.netloc)) except gaierror as e: log.info("Unable to get host name for {0!s}: {1!s}".format(url, e)) return False for net in self.private_networks: if ip in net: return False return True
def echo(self, ip: str) -> None: """ Send ping echo request to destination :param ip: destination IP :return: None """ ip_count = 5 args = ip.split(" ") if len(args) == 3: if args[0] == "-c": ip_count = (int)(args[1]) ip = args[2] elif len(args) == 1: ip = args[0] # convert str to IP address object ip = IP(ip) # iterate over all interfaces on device to find connected route #print(self.interfaces) for name, data in self.interfaces.items(): # print(name) # find connected interface by checking if destination IP is included in our interface subnets if ip in Network(data['ip']): # so I convert IP/nm to a Network to be able to use 'in' for checking # no link (connected device) if data['connected'] is None: print(f'Error - interface link down on {name}') return # there is link, try to ping if 'device' in data['connected']: print(f'Pinging {ip}...') for n in range(ip_count): # Pinging ourselves... is fast :) if data['ip'] == ip: print('!', end='') continue reply = data['connected']['device'].echo_reply(ip) # call echo-reply with destination IP if reply == "!": # the other end sent back '!' which means destination IP is there print("!", end='') sleep(0.100) # simulate network response time else: # the other end did not send '!' so there is a problem over there print(".", end='') sleep(1) # simulate timeout :) print() return print(f'Error - no route to {ip}')
def generate_random_ips(quantity: hug.types.number = 5): """ Return a listo random IP addresses. Params: quantity (int): amount of IP to generate Returns: list: list of addresses and network information ["IP", "Network", "Netmask Decimal", "Netmask Bits", "Broadcast", "Host min", "Host max"] """ ips = [ # Headers ["IP", "Network", "Netmask Decimal", "Netmask Bits", "Broadcast", "Host min", "Host max"] ] for _ in range(quantity): # Random IP raw_ip = IPv4Address(getrandbits(32)) # Random MASK raw_mask = randint(1, 32) # Build IP Network and store the related information ipv4 = IP(f"{raw_ip}/{raw_mask}") network = ipv4.guess_network() ips.append([ ipv4, network.network(), network.netmask(), network.subnet(), network.broadcast(), network.host_first(), network.host_last() ]) return ips