【Python】IP地址解析并生成

IP地址解析并生成

#!python3
# coding=utf-8
import logging
import ipaddress


logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s [%(filename)s:%(lineno)d] %(levelname)s # %(message)s',
                    datefmt='%Y-%m-%d %M:%S')

def parse_ipaddress_user(addrs, flag):
    addr_fields = str.split(addrs, flag)
    if len(addr_fields) != 2:
        return None, None
    try:
        start = ipaddress.ip_address(addr_fields[0])
    except Exception:
        logging.error("addr err: %s" % addrs)
        return None, None
    try:
        end = ipaddress.ip_address(addr_fields[1])
    except Exception:
        try:
            end_tmp = int(addr_fields[1])
        except Exception:
            logging.error("add err: %s", addrs)
            return None, None
        tmp_fields = str.split(addr_fields[0], ".")
        if len(tmp_fields) != 4:
            logging.error("add err: %s", addrs)
            return None, None
        end_str = f"{tmp_fields[0]}.{tmp_fields[1]}.{tmp_fields[2]}.{end_tmp}"
        try:
            end = ipaddress.ip_address(end_str)
        except Exception:
            logging.error("add err: %s", addrs)
            return None, None
    return start, end


def parse_ipaddress(addrs):
    if "-" in addrs:
        start, end = parse_ipaddress_user(addrs, "-")
        if start is None or end is None:
            yield None
        else:
            while start <= end:
                yield start
                start += 1
    elif "~" in addrs:
        start, end = parse_ipaddress_user(addrs, "~")
        if start is None or end is None:
            yield None
        else:
            while start <= end:
                yield start
                start += 1
    elif "/" in addrs:
        try:
            base_net_addr = ipaddress.ip_network(addrs)
        except Exception:
            logging.error("add err: %s", addrs)
            yield None
        else:
            base_addr = base_net_addr.network_address + 1
            index = 0
            while True:
                ipvx_addr = base_addr + index
                index += 1
                if ipvx_addr >= base_net_addr.broadcast_address:
                    break
                yield ipvx_addr
    else:
        yield addrs


if __name__ == "__main__":
    with open("ipaddr", 'r', encoding='utf-8') as fd:
        for check_someone in fd:
            check_someone = check_someone.strip()
            if check_someone == "":
                continue
            gen_addr_obj = parse_ipaddress(check_someone)
            for gen_addr in gen_addr_obj:
                print(gen_addr)

文件内容格式有:

192.168.1.0/24
192.168.2.1-192.168.2.254
192.168.3.1~192.168.3.100
192.168.4.1-254
192.168.5.100

你可能感兴趣的:(python,tcp/ip,网络)