切片或数组中的动态范围

时间:2017-08-15 14:34:53

标签: arrays python-2.7 slice

我有python脚本从netaddr生成IP子网信息。

from netaddr import *
ipnetwork = raw_input("Enter IP address: ")
ip = IPNetwork(ipnetwork)
print "Network ID:", ip.network
print "Network Broadcast:", ip.broadcast
print "Subnet Mask:", ip.netmask
print "Prefix Length:", ip.prefixlen
print "Wildcard Mask:", ip.hostmask
print "Network Size:", ip.size

print "Host range is:", ip[1], "-", ip[-2]
for ip in IPNetwork(ipnetwork).iter_hosts():
    print '%s' % ip

这很有效。我遇到麻烦的地方是我想“预留”第一个和最后三个地址。这是我当前输出的一个例子:

Enter IP address: 192.168.100.17/28
Network ID: 192.168.100.16
Network Broadcast: 192.168.100.31
Subnet Mask: 255.255.255.240
Prefix Length: 28
Wildcard Mask: 0.0.0.15
Network Size: 16
Host range is: 192.168.100.17 - 192.168.100.30
192.168.100.17
192.168.100.18
192.168.100.19
192.168.100.20
192.168.100.21
192.168.100.22
192.168.100.23
192.168.100.24
192.168.100.25
192.168.100.26
192.168.100.27
192.168.100.28
192.168.100.29
192.168.100.30

我希望得到的结果是

192.168.100.17 Reserved
192.168.100.18 Reserved
192.168.100.19 Reserved
192.168.100.20
192.168.100.21
192.168.100.22
192.168.100.23
192.168.100.24
192.168.100.25
192.168.100.26
192.168.100.27
192.168.100.28 SW2-VLAN 100
192.168.100.29 SW1-VLAN 100
192.168.100.30 HSRP VLAN 100

我认为切片会起作用,直到我选择不同的子网长度。我无法找到如何动态切片地址四(第一个非保留)到最后一个地址减三。我无法找到任何解决方案(切片,数组,索引),它将是动态的,具体取决于子网大小减去第一个和最后三个地址。任何指针都将非常感激。

1 个答案:

答案 0 :(得分:0)

我对这个问题感到有些困惑。如果您想要管理IPNetwork(ipnetwork).iter_hosts(),您可能只想简单一点,列表理解它们。

def handle(i, data):
    # Each ip, or 'data', can be returned as a
    # new value to fill that list or we could return
    # The objects themselves.
    if i < 3:
        return str(data) + " Reverse"
    elif i > (total - 3):
        return str(data)
    else:
        return str(data) + " SW1-VLAN 100"

ips_to_manage = [handle(i, addr) for i, addr in \
                 enumerate(IPNetwork(ipnetwork).iter_hosts())]
for ip in ips_to_manage:
    print '%s' % ip

你必须自己找出总数。 len(IPNetwork(ipnetwork).iter_hosts())应该做的伎俩。 这样,您可以随意处理它们。

这只是打印它们,但是如果你想做别的事情,就像回归对象本身一样,那么欢迎你来。