两个py文件,showprocess作用是展示进度条。(进度条忘记是参照哪个大佬的代码了,这里白嫖一下^-^)

python 生成指定两个ip间的所有ip_ipad

 

 

  1. 脚本内容 

   printip.py  ↓↓↓

import ipaddress
import re
from showprocess import ShowProcess

def cut_text(text,lenth):    #//固定长度切割字符串
    textArr = re.findall('.{'+str(lenth)+'}', text)
    if len(text)%lenth > 0:
        textArr.append(text[(len(textArr)*lenth):])
    return textArr

def to_two(lists):    #//list转2进制
    str_ = ""
    for i in lists:
        str_ += f'{bin(int(i))[2:]:0>8}'
    return str_

while True:    #//输入判断
    addr = input("请输入起始ip==>")
    addr_ = input("请输入终止ip==>")
    try:
        ipaddress.ip_address(addr)
        ipaddress.ip_address(addr_)
    except Exception as e:
        print("格式有误")
    int_addr = [int(i) for i in addr.split(".")]
    int_addr_ = [int(i) for i in addr_.split(".")]
    if int_addr_ < int_addr:
        print("起始大小有误")
    else:
        temp1 = addr.split(".")
        temp2 = addr_.split(".")
        small = to_two(temp1)
        big = to_two(temp2)
        number = int(big,2) - int(small,2) + 1
        print("即将生成指定的 {} 个ip,请稍后".format(number))
        break

if __name__ == "__main__":
    f = open ("ip.txt","w")
    process_bar = ShowProcess(number, 'OK')

    while small <= big:
        bin_list = cut_text(small,8)
        intstr_list = [str(int(i,2)) for i in bin_list]
        f.write(".".join(intstr_list)+"\n")
        process_bar.show_process()
        small = f'{bin(int(small,2) + 1)[2:]:0>32}'       

    f.close()

  showprocess.py ↓↓↓

# -*- coding: UTF-8 -*-

import sys, time

class ShowProcess():
    """
    显示处理进度的类
    调用该类相关函数即可实现处理进度的显示
    """
    i = 0 # 当前的处理进度
    max_steps = 0 # 总共需要处理的次数
    max_arrow = 50 #进度条的长度
    infoDone = 'done'

    # 初始化函数,需要知道总共的处理次数
    def __init__(self, max_steps, infoDone = 'Done'):
        self.max_steps = max_steps
        self.i = 0
        self.infoDone = infoDone

    # 显示函数,根据当前的处理进度i显示进度
    # 效果为[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]100.00%
    def show_process(self, i=None):
        if i is not None:
            self.i = i
        else:
            self.i += 1
        num_arrow = int(self.i * self.max_arrow / self.max_steps) #计算显示多少个'>'
        num_line = self.max_arrow - num_arrow #计算显示多少个'-'
        percent = self.i * 100.0 / self.max_steps #计算完成进度,格式为xx.xx%
        process_bar = '[' + '>' * num_arrow + '-' * num_line + ']'\
                      + '%.2f' % percent + '%' + '\r' #带输出的字符串,'\r'表示不换行回到最左边
        sys.stdout.write(process_bar) #这两句打印字符到终端
        sys.stdout.flush()
        if self.i >= self.max_steps:
            self.close()

    def close(self):
        print('')
        print(self.infoDone)
        self.i = 0
  1. 运行效果:

python 生成指定两个ip间的所有ip_进制_02

 

 

 python 生成指定两个ip间的所有ip_字符串_03