Пример #1
0
        def parse_and_group_target_specs(target_specs, nocidr):
            str_targets = set()
            ips_list = list()
            for target_spec in target_specs:
                if (
                    target_spec.startswith(".") or
                    (target_spec[0].isalpha() or target_spec[-1].isalpha()) or
                    (nocidr and "/" in target_spec)
                ):
                    str_targets.add(target_spec)
                else:
                    if "-" in target_spec:
                        start_ip, post_dash_segment = target_spec.split("-")
                        end_ip = start_ip.rsplit(".", maxsplit=1)[0] + "." + \
                            post_dash_segment
                        target_spec = IPRange(start_ip, end_ip)
                    elif "*" in target_spec:
                        target_spec = glob_to_iprange(target_spec)
                    else:  # str IP addresses and str CIDR notations
                        if "/" in target_spec:
                            target_spec = IPSet((target_spec,))
                        else:
                            target_spec = [target_spec]

                    for i in target_spec:
                        ips_list.append(str(i))
            return (str_targets, set(ips_list))
Пример #2
0
def parse_args():
    import argparse
    import itertools
    import sys

    parser = argparse.ArgumentParser(description='Network scanner to test hosts for multipath TCP support. Requires root privileges for scapy.')
    parser.add_argument("--ip", action="store", dest="src_ip", help="use the specified source IP for all traffic")
    parser.add_argument('host', action="store",
                        help='comma-separated IPs or ranges (globs allowed), eg "127.0.0.1,192.168.1-254,203.0.113.*"')
    parser.add_argument('port', action="store",
                        help='comma-separated port(s) or port ranges, eg "22,80,8000-8999"')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    host_entries = (netaddr.glob_to_iprange(host_entry) for host_entry in args.host.split(","))
    hosts = list(itertools.chain(*host_entries))

    port_entries =  (port_entry for port_entry in args.port.split(","))
    ports = []
    for port_entry in port_entries:
        if "-" not in port_entry:
            ports.append(int(port_entry))
        else:
            begin, end = port_entry.split("-")
            ports += range(int(begin), int(end)+1)

    return hosts, ports, args.src_ip
Пример #3
0
def is_ip_range(subnet):
    ips = []
    try:
        ips = glob_to_iprange(subnet)
    except Exception:
        return []
    return ips
Пример #4
0
def interpreter_ip_to_section_ip(ips_list):
    """
        提供一个功能,将CIDR表示的IP转换成 IP段的表示方法如,不连续的段会以#分隔开,注意以CIDR表示的IP,必须表示的是
        一段或多段连续的IP,不可是一段连续的ip,一段独立的ip的形式:
        ['10.33.0.15/32','10.33.0.16/29','10.33.0.24/32']转换为"10.33.0.15-10.33.0.24"
        :param ips_list: list,以CIDR表示的ip
        :return:string  以ip网段表示的一个ip段
        """
    ip_net = []
    ip_string = ""
    int_to_ip = lambda x: '.'.join(
        [str(x / (256**i) % 256) for i in range(3, -1, -1)])
    for ips in ips_list:
        ip_net.append(netaddr.glob_to_iprange(netaddr.cidr_to_glob(ips)))
    ip_start = ip_net[0].key()[1]
    ip_end = ip_net[0].key()[2]
    for index in xrange(len(ip_net)):
        if ip_net[index].key()[1] - 1 <= ip_end:
            ip_end = ip_net[index].key()[2]
            if index == len(ip_net) - 1:
                ip_end = ip_net[index].key()[2]
                ip_string += "%s-%s#" % (int_to_ip(ip_start),
                                         int_to_ip(ip_end))
        else:
            if index == len(ip_net) - 1:
                ip_string += "%s-%s#" % (int_to_ip(ip_start),
                                         int_to_ip(ip_end))
            ip_string += "%s-%s#" % (int_to_ip(ip_start), int_to_ip(ip_end))
            ip_start = ip_net[index].key()[1]
            ip_end = ip_net[index].key()[2]
    ip_string = ip_string[:-1]
    return ip_string
Пример #5
0
 def getIPv4LocalAddressList(self):
   """Returns currently configured local IPv4 addresses which are in ipv4_local_network"""
   if not socket.AF_INET in netifaces.ifaddresses(self.name):
     return []
   return [dict(addr=q['addr'], netmask=q['netmask']) for q in
     netifaces.ifaddresses(self.name)[socket.AF_INET] if netaddr.IPAddress(
       q['addr'], 4) in netaddr.glob_to_iprange(
         netaddr.cidr_to_glob(self.ipv4_local_network))]
Пример #6
0
  def _generateRandomIPv4Address(self, netmask):
    # no addresses found, generate new one
    # Try 10 times to add address, raise in case if not possible
    try_num = 10
    while try_num > 0:
      addr = random.choice([q for q in netaddr.glob_to_iprange(
        netaddr.cidr_to_glob(self.ipv4_local_network))]).format()
      if dict(addr=addr, netmask=netmask) not in self.getIPv4LocalAddressList():
        # Checking the validity of the IPv6 address
        if self._addSystemAddress(addr, netmask, False):
          return dict(addr=addr, netmask=netmask)
        try_num -= 1

    raise AddressGenerationError(addr)
Пример #7
0
def parse_args():
    import argparse
    import itertools
    import sys

    parser = argparse.ArgumentParser(
        description=
        'Network scanner to test hosts for multipath TCP support. Requires root privileges for scapy.'
    )
    parser.add_argument("--ip",
                        action="store",
                        dest="src_ip",
                        help="use the specified source IP for all traffic")
    parser.add_argument(
        'host',
        action="store",
        help=
        'comma-separated IPs or ranges (globs allowed), eg "127.0.0.1,192.168.1-254,203.0.113.*"'
    )
    parser.add_argument(
        'port',
        action="store",
        help='comma-separated port(s) or port ranges, eg "22,80,8000-8999"')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    host_entries = (netaddr.glob_to_iprange(host_entry)
                    for host_entry in args.host.split(","))
    hosts = list(itertools.chain(*host_entries))

    port_entries = (port_entry for port_entry in args.port.split(","))
    ports = []
    for port_entry in port_entries:
        if "-" not in port_entry:
            ports.append(int(port_entry))
        else:
            begin, end = port_entry.split("-")
            ports += range(int(begin), int(end) + 1)

    return hosts, ports, args.src_ip
Пример #8
0
 def parse_and_group_target_specs(target_specs, nocidr):
     str_targets = set()
     ipset_targets = IPSet()
     for target_spec in target_specs:
         if (target_spec.startswith(".") or
             ((target_spec[0].isalpha() or target_spec[-1].isalpha())
              and "." in target_spec)
                 or (nocidr and "/" in target_spec)):
             str_targets.add(target_spec)
         else:
             if "-" in target_spec:
                 start_ip, post_dash_segment = target_spec.split("-")
                 end_ip = start_ip.rsplit(".", maxsplit=1)[0] + "." + \
                     post_dash_segment
                 target_spec = IPRange(start_ip, end_ip)
             elif "*" in target_spec:
                 target_spec = glob_to_iprange(target_spec)
             else:  # str IP addresses and str CIDR notations
                 target_spec = (target_spec, )
             ipset_targets.update(IPSet(target_spec))
     return (str_targets, ipset_targets)
Пример #9
0
def test_glob_to_iprange():
    assert glob_to_iprange('192.0.2.*') == IPRange('192.0.2.0', '192.0.2.255')
    assert glob_to_iprange('192.0.2.1-15') == IPRange('192.0.2.1',
                                                      '192.0.2.15')
    assert glob_to_iprange('192.0.1-3.*') == IPRange('192.0.1.0',
                                                     '192.0.3.255')
Пример #10
0
def range_ips(range):
    ips = []
    if is_ip_range(range):
        ips = [str(ip) for ip in glob_to_iprange(range)]
    return ips