Python编写整理ip脚本

发布于 2020-08-16  465 次阅读


0x01 代码

import sys
import struct
import socket


def findIPs(start, end):
    ipstruct = struct.Struct('>I')
    start, = ipstruct.unpack(socket.inet_aton(start))
    end, = ipstruct.unpack(socket.inet_aton(end))
    return [socket.inet_ntoa(ipstruct.pack(i)) for i in range(start, end+1)]

def allc(file):
    line = (file.split('.')[:-1])
    print(line)
    for a in range(1,255):
        ipc = ('.'.join(line)+'.'+str(a))
        print(ipc)
        result = open('ip.txt', 'a+')
        with open('ip.txt') as f:
            result.write(ipc)
            result.write('\n')
            result.close()

def allb(file):
    f = open(file,'r')
    for a in f:
        line = (a.rstrip('\n').split()[0])
        line2 = (a.rstrip('\n').split()[1])
        aa = findIPs(line,line2)
        for i in aa:
            ipb = (i.rstrip('\n'))
            print(ipb)
            result = open('ipb.txt', 'a+')
            result.write(ipb)
            result.write('\n')
            result.close()

def ip_c(file):
    f = open(file,'r')
    for i in f:
        line = (i.rstrip('\n').split('.')[:-1])
        ipstart = ('.'.join(line)+'.'+str(1))
        ipend = ('.'.join(line)+'.'+str(254))
        result = open('ip-c.txt', 'a+')
        with open('ip-c.txt') as f:
            if ipstart not in f.read():
                print(f"{ipstart} {ipend}")
                result.write(f"{ipstart} {ipend}")
                result.write('\n')
                result.close()


if len(sys.argv) == 3:
    key = sys.argv[1]
    file = sys.argv[2]
    if key == 'c':
        allc(file)
    elif key == 'b':
        allb(file)
    elif key == '-c':
        ip_c(file)
else:
    print("Tips:python3 ip_c.py c 127.0.0.1")
    print("Tips:python3 ip_c.py b ip.txt")
    print("Tips:python3 ip_c.py -c ip.txt")

一切都是兴趣使然