def reload(self): self._nameservers = [] ns = self._service.nameserversConfig() for n in ns: ip = IPAddress(n) if ip.version == 4: cfg = ConfigIP( default=toIP4List(ip.format())) self._nameservers.append(cfg) elif ip.version == 6: cfg = ConfigIP6(default=ip.format()) self._nameservers.append(cfg)
def reload(self): self._nameservers = [] ns = self._service.nameserversConfig() for n in ns: ip = IPAddress(n) if ip.version == 4: cfg = ConfigIP(default=toIP4List(ip.format())) self._nameservers.append(cfg) elif ip.version == 6: cfg = ConfigIP6(default=ip.format()) self._nameservers.append(cfg)
def mod_network(ip_addr, unmod_nets, ip_map): ip_addr = IPAddress(ip_addr) # Looping through the list of unmod_nets and checking if IP is in network, if True then break for net in unmod_nets: in_network = ip_addr in net if in_network: break # in_network would be False here if IP address wasn't in any of the unmod_networks if not in_network: return ip_addr.format() # Mapping current IP to mod IP net = ip_map[net] # Converting IPs to binary, only keeping the host and network bits respectively ip_addr = ip_addr.bits().replace('.', '')[net.prefixlen:] net = net.network.bits().replace('.', '')[:net.prefixlen] # Modified IP address ip_addr = net + ip_addr octet = 8 ip_addr = '.'.join([str(int(ip_addr[i:i + octet], 2)) for i in range(0, len(ip_addr), octet)]) return ip_addr
def ping_check(self): bip_selfips = SCMD.tmsh.list("net self", ifc=self.sshifc) self_ips = [ x['address'].split('/')[0] for x in list(bip_selfips.values()) ] for self_ip in self_ips: self_ip = IPAddress(self_ip) if self_ip.version == 4: COMMAND = "ping -c 1 %s" % self_ip.format(ipv6_full) elif self_ip.version == 6: COMMAND = "ping6 -c 1 %s" % self_ip.format(ipv6_full) # TODO: Find out why we can't ping using ipv6 address on Lowell's BIG-IQs continue else: LOG.info( "You got some weird IP address that isn't ipv4 or ipv6") LOG.info("Ping %s from %s" % (self_ip, self.options.device_biq if self.options.device_biq else self.address_biq)) resp = SCMD.ssh.generic(COMMAND, ifc=self.sshifc_biq) if '100% packet loss' in resp.stdout: LOG.info("device: %s not reachable" % self.device) LOG.debug("device: %s - %s" % (self.device, resp)) raise Exception("device: %s not reachable" % self.device) if self.device: self_ip = IPAddress(self.device.get_discover_address()) LOG.info("Verify given %s from yaml matches one on BIG-IP" % self_ip) for a in list(bip_selfips.values()): bip_ip = IPAddress(a['address'].split('/')[0]) if a['vlan'] == 'internal' and \ self_ip.version == bip_ip.version: internal_ip = bip_ip break if self_ip.format(ipv6_full) != internal_ip.format(ipv6_full): LOG.info("Internal mismatch: %s. %s != %s." % (self.device, self_ip, internal_ip)) else: LOG.info( "This isn't ran as stages so skipping internal selfip check")
def test_ipaddress_v4(): ip = IPAddress('192.0.2.1') assert ip.version == 4 assert repr(ip) == "IPAddress('192.0.2.1')" assert str(ip) == '192.0.2.1' assert ip.format() == '192.0.2.1' assert int(ip) == 3221225985 assert hex(ip) == '0xc0000201' assert ip.bin == '0b11000000000000000000001000000001' assert ip.bits() == '11000000.00000000.00000010.00000001' assert ip.words == (192, 0, 2, 1)
def test_ipaddress_v6(): ip = IPAddress('fe80::dead:beef') assert ip.version == 6 assert repr(ip) == "IPAddress('fe80::dead:beef')" assert str(ip) == 'fe80::dead:beef' assert ip.format() == 'fe80::dead:beef' assert int(ip) == 338288524927261089654018896845083623151 assert hex(ip) == '0xfe8000000000000000000000deadbeef' assert ip.bin == '0b11111110100000000000000000000000000000000000000000000000000000000000000000000000000000000000000011011110101011011011111011101111' assert ip.bits() == '1111111010000000:0000000000000000:0000000000000000:0000000000000000:0000000000000000:0000000000000000:1101111010101101:1011111011101111' assert ip.words == (65152, 0, 0, 0, 0, 0, 57005, 48879)
def get_version(request): func = request.GET.get('func', '') remote_addr = IPAddress(request.remote_addr) data = { 'address': remote_addr.format(), 'version': remote_addr.version, 'ipv4_mapped': remote_addr.is_ipv4_mapped(), } return Response( body='%s(%s);' % (func, json.dumps(data)), content_type='text/javascript')
def test_ipaddress_v6(): ip = IPAddress('fe80::dead:beef') assert ip.version == 6 assert repr(ip) == "IPAddress('fe80::dead:beef')" assert str(ip) == 'fe80::dead:beef' assert ip.format() == 'fe80::dead:beef' assert int(ip) == 338288524927261089654018896845083623151 assert hex(ip) == '0xfe8000000000000000000000deadbeef' assert ip.bin == '0b11111110100000000000000000000000000000000000000000000000000000000000000000000000000000000000000011011110101011011011111011101111' assert ip.bits( ) == '1111111010000000:0000000000000000:0000000000000000:0000000000000000:0000000000000000:0000000000000000:1101111010101101:1011111011101111' assert ip.words == (65152, 0, 0, 0, 0, 0, 57005, 48879)
def reset_all(self): group = RCMD.device.DEFAULT_ALLBIGIQS_GROUP for device in [self.default] + self.peers: with SSHInterface(device=device) as sshifc: LOG.info('Wiping storage on {0}'.format(device)) SCMD.ssh.generic(SCMD.bigiq.ha.HA_WIPE_COMMAND, ifc=sshifc) with EmapiInterface(device=device, auth=AUTH.BASIC) as rstifc: RCMD.system.wait_restjavad([self.default] + self.peers, ifc=rstifc) # For IPv6 runs where localhost will get reset to IPv4. for device in [self.default] + self.peers: with EmapiInterface(device=device, auth=AUTH.BASIC) as rstifc: resp = rstifc.api.get(DeviceResolver.DEVICES_URI % group) selfip_expect = device.get_discover_address() selfips_actual = [x.address for x in resp['items']] if selfip_expect not in selfips_actual: LOG.info( "selfip mismatch. Setting {0}".format(selfip_expect)) self_addr = IPAddress(selfip_expect) payload = NetworkDiscover() payload.discoveryAddress = self_addr.format(ipv6_full) rstifc.api.put(NetworkDiscover.URI, payload=payload) DeviceResolver.wait(rstifc.api, group) # For BZ workarounds.. bigips = [] context = ContextHelper() default_bigiq = context.get_icontrol(device=self.default).version session = context.get_config().get_session().name for device in context.get_config().get_devices(): v = context.get_icontrol(device=device).version if v.product.is_bigip and v >= 'bigip 11.3.0': bigips.append(device) if default_bigiq > 'bigiq 4.3.0' and default_bigiq < 'bigiq 4.5.0': with EmapiInterface(device=self.default, auth=AUTH.BASIC) as rstifc: RCMD.device.clean_dg_certs(bigips, ifc=rstifc) with EmapiInterface(device=self.default, auth=AUTH.BASIC) as rstifc: RCMD.system.bz_help1([self.default] + self.peers, ifc=rstifc) if default_bigiq > 'bigiq 4.3.0' and default_bigiq < 'bigiq 4.5.0': with SSHInterface(device=self.default) as sshifc: SCMD.bigiq.ha.wait_ha_peer(self.peers, session=session, ifc=sshifc)
class IpAddress(DatabaseObject): ''' Wraps the netaddr IPAddress class ''' uuid = Column(String(36), unique=True, nullable=False, default=lambda: str(uuid4())) box_id = Column(Integer, ForeignKey('box.id'), nullable=False) _address = Column(String(40), unique=True) _ip_address = None @classmethod def all(cls): ''' Returns a list of all objects in the database ''' return dbsession.query(cls).all() @classmethod def by_id(cls, _id): ''' Returns a the object with id of _id ''' return dbsession.query(cls).filter_by(id=_id).first() @classmethod def by_uuid(cls, _uuid): ''' Return and object based on a _uuid ''' return dbsession.query(cls).filter_by(uuid=_uuid).first() @classmethod def by_address(cls, addr): ''' Return and object based on an address ''' return dbsession.query(cls).filter_by(address=addr).first() @property def address(self): if self._ip_address is None: self._ip_address = IPAddress(self._address) return self._ip_address.format() @address.setter def address(self, value): ip = IPAddress(value) if ip.is_loopback(): raise ValueError("You cannot use a loopback address") if ip.is_multicast(): raise ValueError("You cannot use a multicast address") self._address = value @property def version(self): if self._ip_address is None: self._ip_address = IPAddress(self._address) return self._ip_address.version @property def is_private(self): if self._ip_address is None: self._ip_address = IPAddress(self._address) return self._ip_address.is_private() def to_xml(self, parent): ip_elem = ET.SubElement(parent, "ip") ip_elem.set("version", str(self.version)) ET.SubElement(ip_elem, "address").text = self.address def __repr__(self): return "<IpAddress - %s>" % self.address def __str__(self): return self._address def __eq__(self, other): return self._address == other._address def __ne__(self, other): return not self == other
def formatIp(ipAddress): ip = IPAddress(ipAddress) if ip.version == 6: return '[%s]' % ip.format() return ip.format()
class IpAddress(DatabaseObject): ''' Wraps the netaddr IPAddress class ''' uuid = Column(String(36), unique=True, nullable=False, default=lambda: str(uuid4()) ) box_id = Column(Integer, ForeignKey('box.id'), nullable=False) _address = Column(String(40), unique=True) _ip_address = None visable = Column(Boolean, default=True) @classmethod def all(cls): ''' Returns a list of all objects in the database ''' return dbsession.query(cls).all() @classmethod def by_id(cls, _id): ''' Returns a the object with id of _id ''' return dbsession.query(cls).filter_by(id=_id).first() @classmethod def by_uuid(cls, _uuid): ''' Return and object based on a _uuid ''' return dbsession.query(cls).filter_by(uuid=_uuid).first() @classmethod def by_address(cls, address): ''' Return and object based on an address ''' return dbsession.query(cls).filter_by(_address=address).first() @property def address(self): if self._ip_address is None: self._ip_address = IPAddress(self._address) return self._ip_address.format() @address.setter def address(self, value): ip = IPAddress(value) if ip.is_loopback(): raise ValidationError("You cannot use a loopback address") if ip.is_multicast(): raise ValidationError("You cannot use a multicast address") self._address = value @property def version(self): if self._ip_address is None: self._ip_address = IPAddress(self._address) return self._ip_address.version @property def is_private(self): if self._ip_address is None: self._ip_address = IPAddress(self._address) return self._ip_address.is_private() def to_xml(self, parent): ip_elem = ET.SubElement(parent, "ip") ip_elem.set("version", str(self.version)) ET.SubElement(ip_elem, "address").text = self.address def __repr__(self): return "<IpAddress - %s>" % self.address def __str__(self): return self._address def __eq__(self, other): return self._address == other._address def __ne__(self, other): return not self == other
#!/usr/bin/env python from netaddr import IPAddress, IPNetwork import pprint #single address ip = IPAddress("192.168.1.31") print "ip.format(): {}".format(ip.format()) print "str(ip): {}".format(str(ip)) #netblocks netblock = IPNetwork("192.168.1.0/24") print "Netmask: {}".format(netblock.netmask) print "CIDR: {}".format(netblock.cidr) print "Broadcast: {}".format(netblock.broadcast) #you can use list() to generate a list of ips belonging to a netblock ip_list = list(netblock) #and get subnets too! list_31 = list(netblock.subnet(31)) print "list_31[:3]: {}".format(list_31[:3]) #And we can work through the list of subnets for subnet in list_31[:10]: addresses = [ str(x) for x in list(subnet) ] print "Addresses belonging to {}: {}".format(subnet,addresses)