使用元组python对IP地址进行排序

时间:2015-08-22 22:00:45

标签: python

我正在尝试修改一些代码,这些代码将从Cisco IOS设备(重定向的VIA tftp)获取show命令的输出,并根据IP地址对其进行排序。最终我会拿CAM(mac-address表)并将其附加到它。

设备的输出如下所示:

listen.owner = www
listen.group = www

代码:

Internet  172.17.150.198         77   000e.b6a9.e36d  ARPA   Vlan731/n
Internet  161.16.150.202         77   a0ec.f996.94d0  ARPA   Vlan777/n
Internet  161.16.152.199          2   0016.3e7c.8a25  ARPA   Vlan152/n
Internet  172.17.150.197         77   000e.b687.ee67  ARPA   Vlan731/n
Internet  161.16.150.201         77   0cf5.a4e4.d37b  ARPA   Vlan777/n
Internet  161.16.154.196          0   0050.56b3.0ac9  ARPA   Vlan154/n
Internet  161.16.152.198          1   0050.56b3.179d  ARPA   Vlan152/n

这基本上通过ip地址对所有内容进行排序(而不是与IP地址不兼容的默认排序)。我真正想做的是拆分,切片ips列1,-3和-1,并显示该对和单行。 IE:

# Format and parse show interface status
for line in fhand:
    line = line.rstrip()
    if not line.startswith('Internet'):
    continue
b = line.split(); c = (b[-3] + b[-1]); b = b[1]
    ips.append(b)
# Sort IP
for i in range(len(ips)):
    ips[i] = "%3s.%3s.%3s.%3s" % tuple(ips[i].split("."))
ips.sort()
for i in range(len(ips)):
    ips[i] = ips[i].replace(" ", "")
for ip in ips:
print ip (would also like 'c')

我将如何做到这一点?

1 个答案:

答案 0 :(得分:0)

如果这是您的来源,请致电fhand

source = '''
Internet  172.17.150.198         77   000e.b6a9.e36d  ARPA   Vlan731/n
Internet  161.16.150.202         77   a0ec.f996.94d0  ARPA   Vlan777/n
Internet  161.16.152.199          2   0016.3e7c.8a25  ARPA   Vlan152/n
Internet  172.17.150.197         77   000e.b687.ee67  ARPA   Vlan731/n
Internet  161.16.150.201         77   0cf5.a4e4.d37b  ARPA   Vlan777/n
Internet  161.16.154.196          0   0050.56b3.0ac9  ARPA   Vlan154/n
Internet  161.16.152.198          1   0050.56b3.179d  ARPA   Vlan152/n'''

fhand = source.splitlines()

然后,此代码将对IP地址进行排序,并将打印每隔一列:

def ip_sort(key):
    """
    Assumes IP address is first element
    Splits the IP address and orders result numerically.
    """
    return [int(x) for x in key[0].split('.')]

keep = (line for line in fhand if line.startswith('Internet'))
keep = (tuple(line.split()[1::2]) for line in keep)
keep = sorted(keep, key=ip_sort)

for info in keep:
    print '%-15s %s %s' % info

这是输出:

161.16.150.201  0cf5.a4e4.d37b Vlan777/n
161.16.150.202  a0ec.f996.94d0 Vlan777/n
161.16.152.198  0050.56b3.179d Vlan152/n
161.16.152.199  0016.3e7c.8a25 Vlan152/n
161.16.154.196  0050.56b3.0ac9 Vlan154/n
172.17.150.197  000e.b687.ee67 Vlan731/n
172.17.150.198  000e.b6a9.e36d Vlan731/n