创建一个子网中IP的.txt列表

0 投票
3 回答
2174 浏览
提问于 2025-04-16 01:51

我想制作一个非常简单的文本文件(.txt)。这个Python程序需要生成一个包含多个IP地址范围的列表,每个范围占一行。

举个例子:

10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.51
10.10.27.52
10.10.27.53
10.10.27.54

子网掩码基本上总是 /24,所以不需要输入掩码。这个程序甚至可以默认只支持标准的C类地址。

另外,我还想支持我们常用的设备范围。比如,问到“打印机?”时,会包含 .26 到 .30 的范围。“服务器?”会包含 .5 到 .7。“DHCP?”的范围总是 .51 到 .100。“异常?”则会包含 .100 到 .254。

Subnet?  10.10.27.1
Servers?  Y
Printers?  Y
DHCP?  Y
Abnormal?  N

输出结果是:

10.10.27.1
10.10.27.5
10.10.27.6
10.10.27.7
10.10.27.26
10.10.27.27
10.10.27.28
10.10.27.29
10.10.27.30
10.10.27.51 (all the way to .100)

有什么好的方法来编写这个程序吗?

3 个回答

0

我会让这个脚本保持简单,只需按需输出所有地址就可以了 :)

def yesno(question):
    output = input(question).lower()

    if output == 'y':
        return True
    elif output == 'n':
        return False
    else:
        print '%r is not a valid response, only "y" and "n" are allowed.' % output
        return yesno(question)

addresses = []

subnet = input('Subnet? ')
# Remove the last digit and replace it with a %d for formatting later
subnet, address = subnet.rsplit('.', 1)
subnet += '%d'
addresses.append(int(address))

if yesno('Servers? '):
    addresses += range(5, 8)

if yesno('Printers? '):
    addresses += range(26, 31)

if yesno('DHCP? '):
    addresses += range(51, 101)

if yesno('Abnormal? '):
    addresses += range(100, 255)

for address in addresses:
    print subnet % address
0

这是我随便写的一个小脚本...

import socket
import sys


ranges = {'servers':(5, 8), 'printers':(26, 31), 'dhcp':(51, 101), 'abnormal':(101, 256)}

subnet = raw_input("Subnet? ")

try:
    socket.inet_aton(subnet)
except socket.error:
    print "Not a valid subnet"
    sys.exit(1)

ip_parts = subnet.split(".")
if len(ip_parts) < 3:
    print "Need at least three octets"
    sys.exit(1)
ip_parts = ip_parts[:3]
ip = ".".join(ip_parts)

include_groups = []
last_octets = []

servers = raw_input("Servers? ")
printers = raw_input("Printers? ")
dhcp = raw_input("DHCP? ")
abnormal = raw_input("Abnormal? ")

if servers == "Y":
    include_groups.append('servers')
if printers == "Y":
    include_groups.append('printers')
if dhcp == "Y":
    include_groups.append('dhcp')
if abnormal == "Y":
    include_groups.append('abnormal')

for group in include_groups:
    last_octets.extend([x for x in xrange(ranges[group][0], ranges[group][1])])

print "%s.1" %(ip)
for octet in last_octets:
    print "%s.%s" %(ip, octet)
1

看起来你只需要几个 for 循环就可以了:

network = '10.10.27'

for host in xrange(100, 255):
   print("{network}.{host}".format(**locals()))

撰写回答