用python批量生成有效的IP地址

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time

time_start = time.time()   #设置运行开始时间
#批量生成IP地址
def get_ip(number=10, start='1.1.1.1'):
    file = open('ip_list.txt','w')
    starts = start.split('.')
    A = int(starts[0])
    B = int(starts[1])
    C = int(starts[2])
    D = int(starts[3])
    for A in range(A, 256):
        for B in range(B, 256):
           for C in range(256):
              for D in range(D, 256):
                  ip = "%d.%d.%d.%d" % (A, B, C, D)

                  if number>1:
                      file.write(ip + '\n')
                      number -= 1
                  elif number == 1:  # 解决最后多一行回车问题
                       file.write(ip)
                       number -= 1
                  else:
                    file.close()
                    print(ip)
                    return
              D = 0
           C = 0
        B = 0
#从生成的IP文件中读取url,将其保存为字典格式,并通过dict[i]来获取该ip地址
def readIp():
    ipfile = 'ip_list.txt'
    global  iplist
    iplist={}

    with open(ipfile, 'r') as file_to_read:
        for i in range(0,1000):
            lines = file_to_read.readline()  # 整行读取数据
            if not lines:
                break
            ip=lines.replace('\n',' ')
            iplist[i]=ip

    print(iplist[1])
#-*-*-另一种生成url的方式
def getip(ip, count):
    count = int(count)
    ip2 = int(ip.split('.')[-2])
    ip1 = int(ip.split('.')[-1])
    ip_before = '%s.%s' % (ip.split('.')[0], ip.split('.')[1])

    #开始批量生成IP地址
    for i in range(0, count):
        new_ip1 = ip1 + i
        if 11 <= new_ip1 <= 254:
            print('%s.%s.%s' % (ip_before, str(ip2), str(new_ip1)))
        else:
            new_ip2 = ip2 + int(new_ip1 / 254)
            new_ip1 = new_ip1 % 254 + 10
            print('%s.%s.%s' % (ip_before, str(new_ip2), str(new_ip1)))


#执行改命令
if __name__ == '__main__':

    #运行该生成IP地址文件
    get_ip(10000, '101.23.228.102') 
    time_end = time.time() 
    time = time_end - time_start 
    print('耗时%s秒' % time)
    time.sleep(2)

    #执行读取Ip文件命令 
    readIp() 
    print('读取结束')

    #执行产生getIP地址命令
    getip('10.0.1.111', 1610)

文章来源:https://blog.csdn.net/apache0554/article/details/43672927

发布了84 篇原创文章 · 获赞 46 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/gufenchen/article/details/100165735