Python ipaddr.IPv4Network() Examples

The following are 8 code examples of ipaddr.IPv4Network(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipaddr , or try the search function .
Example #1
Source File: site_sacnner.py    From hacker-scripts with MIT License 6 votes vote down vote up
def fetch_url(self, i, fn_on_response):
        item = self.get_next_task()
        while item is not None:
            try:
                if '/' in item:
                    mask = ipaddr.IPv4Network(item)
                    ip_list = [text_type(t) for t in mask.iterhosts()]
                else:
                    ip_list = [item]
            except:
                ip_list = []

            for t in ip_list:
                if t == '':
                    continue

                url_list = ['http://%s:%s' % (t, p) for p in self.port_list]
                url_list.extend(['https://%s:%s' % (t, p) for p in [443, 8443]])
                for u in url_list:
                    yield self.do_request(u, 'GET', fn_on_response)
            item = self.get_next_task() 
Example #2
Source File: site_sacnner.py    From hacker-scripts with MIT License 6 votes vote down vote up
def on_queue_empty(self, queue, max_num=100):
        for _ in range(max_num):
            try:
                item = self.list_data.popleft()
                if '/' in item:
                    mask = ipaddr.IPv4Network(item)
                    ip_list = [text_type(t) for t in mask.iterhosts()]
                else:
                    ip_list = [item]
                queue.extend(ip_list)
            except IndexError:
                break

        try:
            item = queue.popleft()
        except IndexError:
            item = None
        return item 
Example #3
Source File: test_Ccp_Util.py    From ciscoconfparse with GNU General Public License v3.0 6 votes vote down vote up
def testIPv4Obj_attributes():
    ## Ensure that attributes are accessible and pass the smell test
    test_object = IPv4Obj("1.0.0.1 255.255.255.0")
    results_correct = [
        ("ip", IPv4Address("1.0.0.1")),
        ("ip_object", IPv4Address("1.0.0.1")),
        ("netmask", IPv4Address("255.255.255.0")),
        ("prefixlen", 24),
        ("broadcast", IPv4Address("1.0.0.255")),
        ("network", IPv4Network("1.0.0.0/24")),
        ("network_object", IPv4Network("1.0.0.0/24")),
        ("hostmask", IPv4Address("0.0.0.255")),
        ("numhosts", 256),
        ("version", 4),
        ("is_reserved", False),
        ("is_multicast", False),
        ("is_private", False),
        ("as_decimal", 16777217),
        ("as_hex_tuple", ("01", "00", "00", "01")),
        ("as_binary_tuple", ("00000001", "00000000", "00000000", "00000001")),
    ]
    for attribute, result_correct in results_correct:
        assert getattr(test_object, attribute) == result_correct 
Example #4
Source File: common.py    From dnsAutoRebinding with GNU General Public License v3.0 5 votes vote down vote up
def ipListBuild(address):
	print '1. Single IP Covert For En\n2. Build IP List'
	opt_req = raw_input("[+] [1 By Default/2]") or '1'
	if opt_req == '1':
		print numToEnToNum(address)
		exit()

	conf_main = conf_read('maindomain')[:-1]
	seg_len = raw_input("[+] Please Input Segment Length [24 By Default]") or 24
	encode_req = raw_input("[+] Please Input Encoding ['ipv4' By Default]")
	mainDomain = raw_input("[+] Please Input Server Root Address [{} By Default]".format(conf_main)) or conf_main
	segment = eval("ipaddr.IPv4Network('{}/{}').iterhosts()".format(address, int(seg_len)))
	save_file = "{}_{}_{}.txt".format(time.strftime("%Y%m%d%X", time.localtime()).replace(':', ''), mainDomain.replace('.','_'),(encode_req if encode_req else 'ipv4'))
	results = []

	try:

		if encode_req == '': results += ["{}.{}".format(str(i),mainDomain) for i in list(segment)]
		elif encode_req == 'en':
			results += ["{}.{}".format(numToEnToNum(str(i)),mainDomain) for i in list(segment)]
		elif encode_req == 'int':
			results += ["{}.{}".format(int(ipaddr.IPAddress(str(i))),mainDomain) for i in list(segment)]
		elif encode_req == 'hex':
			results += ["{}.{}".format(str(i).encode('hex'),mainDomain) for i in list(segment)]
		else:
			pass

		f = open(save_file,'a')
		[f.write(i+'\n') for i in results]
		f.close()
		print '[+] Stored in the {}'.format(save_file)
	except Exception,e:
		print e
		exit() 
Example #5
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def is_valid_ipv6_addr(input=""):
    """Check if this is a valid IPv6 string"""
    assert input != ""
    if _RGX_IPV6ADDR.search(input):
        return True
    return False


## Emulate the old behavior of ipaddr.IPv4Network in Python2, which can use
##    IPv4Network with a host address.  Google removed that in Python3's
##    ipaddress.py module 
Example #6
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def prefixlen(self, arg):
        """prefixlen setter method"""
        self.network_object = IPv4Network(
            "{0}/{1}".format(str(self.ip_object), arg), strict=False
        ) 
Example #7
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def network(self):
        """Returns an IPv4Network object, which represents this network.
        """
        if sys.version_info[0] < 3:
            return self.network_object.network
        else:
            ## The ipaddress module returns an "IPAddress" object in Python3...
            return IPv4Network("{0}".format(self.network_object.compressed)) 
Example #8
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, arg="127.0.0.1/32", strict=False):

        # RGX_IPV4ADDR = re.compile(r'^(\d+\.\d+\.\d+\.\d+)')
        # RGX_IPV4ADDR_NETMASK = re.compile(r'(\d+\.\d+\.\d+\.\d+)\s+(\d+\.\d+\.\d+\.\d+)')

        self.arg = arg
        self.dna = "IPv4Obj"
        try:
            mm = _RGX_IPV4ADDR_NETMASK.search(arg)
        except TypeError:
            if getattr(arg, "dna", "") == "IPv4Obj":
                ip_str = "{0}/{1}".format(str(arg.ip_object), arg.prefixlen)
                self.network_object = IPv4Network(ip_str, strict=False)
                self.ip_object = IPv4Address(str(arg.ip_object))
                return None
            elif isinstance(arg, IPv4Network):
                self.network_object = arg
                self.ip_object = IPv4Address(str(arg).split("/")[0])
                return None
            elif isinstance(arg, IPv4Address):
                self.network_object = IPv4Network(str(arg) + "/32")
                self.ip_object = IPv4Address(str(arg).split("/")[0])
                return None
            elif isinstance(arg, int):
                self.ip_object = IPv4Address(arg)
                self.network_object = IPv4Network(
                    str(self.ip_object) + "/32", strict=False
                )
                return None
            else:
                raise ValueError(
                    "IPv4Obj doesn't understand how to parse {0}".format(arg)
                )

        ERROR = "IPv4Obj couldn't parse '{0}'".format(arg)
        assert not (mm is None), ERROR

        mm_result = mm.groupdict()
        addr = (
            mm_result["addr0"]
            or mm_result["addr1"]
            or mm_result["addr2"]
            or "127.0.0.1"
        )

        ## Normalize addr if we get zero-padded strings, i.e. 172.001.001.001
        addr = ".".join([str(int(ii)) for ii in addr.split(".")])

        masklen = int(mm_result["masklen"] or 32)
        netmask = mm_result["netmask"]
        if netmask:
            ## ALWAYS check for the netmask first
            self.network_object = IPv4Network(
                "{0}/{1}".format(addr, netmask), strict=strict
            )
            self.ip_object = IPv4Address("{0}".format(addr))
        else:
            self.network_object = IPv4Network(
                "{0}/{1}".format(addr, masklen), strict=strict
            )
            self.ip_object = IPv4Address("{0}".format(addr))