簡體   English   中英

用元組python排序IP地址

[英]Sort IP addresses with tuple python

我正在嘗試糾正一些代碼,這些代碼將從Cisco IOS設備(重定向的VIA tftp)獲取show命令的輸出,並根據IP地址對其進行排序。 最終,我將采用CAM(mac地址表)並將其附加到它。

設備的輸出如下所示:

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

碼:

# 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')

這基本上是按IP地址對所有內容進行排序(而不是對IP地址不起作用的默認排序)。 我真正想做的是拆分,並對ips列1,-3和-1進行切片,並顯示該對和一行。 IE瀏覽器:

161.16.150.201 0cf5.a4e4.d37b Vlan777/n
161.16.150.202 a0ec.f996.94d0 Vlan777/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

我將如何去做呢?

如果這是您的來源,請致電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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM