Ansible按最后一个参数(IP地址)对命令列表进行排序

2024-04-19 12:48:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要发送到Juniper路由器的命令列表。如何按命令末尾的ip地址对列表排序?你知道吗

由此,用set\u fact和\u items生成

"command_list": [
    "show bgp neighbor 1.1.1.1",
    "show bgp neighbor 2.2.2.2",
    "show bgp neighbor 3.3.3.3",
    "show route receive-protocol bgp 1.1.1.1",
    "show route receive-protocol bgp 2.2.2.2",
    "show route receive-protocol bgp 3.3.3.3",
    "show route advertising-protocol bgp 1.1.1.1",
    "show route advertising-protocol bgp 2.2.2.2"
    "show route advertising-protocol bgp 3.3.3.3"
]

对此,由目标IP订购。你知道吗

"command_list": [
    "show bgp neighbor 1.1.1.1",
    "show route receive-protocol bgp 1.1.1.1",
    "show route advertising-protocol bgp 1.1.1.1",
    "show bgp neighbor 2.2.2.2",
    "show route receive-protocol bgp 2.2.2.2",
    "show route advertising-protocol bgp 2.2.2.2"
    "show bgp neighbor 3.3.3.3",   
    "show route receive-protocol bgp 3.3.3.3",        
    "show route advertising-protocol bgp 3.3.3.3"
]

Tags: 命令ip列表show路由器routeprotocolcommand
1条回答
网友
1楼 · 发布于 2024-04-19 12:48:56

list使用sorted操作,并使用其key参数指定在进行比较之前对每个列表元素调用的函数。你知道吗

command_list = [
    "show bgp neighbor 1.1.1.1",
    "show bgp neighbor 2.2.2.2",
    "show bgp neighbor 3.3.3.3",
    "show route receive-protocol bgp 1.1.1.1",
    "show route receive-protocol bgp 2.2.2.2",
    "show route receive-protocol bgp 3.3.3.3",
    "show route advertising-protocol bgp 1.1.1.1",
    "show route advertising-protocol bgp 2.2.2.2",
    "show route advertising-protocol bgp 3.3.3.3"
]
def last(a):
    for i in reversed(a.split()):
        return i
print(sorted(command_list, key=last))

输出

 ['show bgp neighbor 1.1.1.1',
 'show route receive-protocol bgp 1.1.1.1',
 'show route advertising-protocol bgp 1.1.1.1',
 'show bgp neighbor 2.2.2.2', 
 'show route receive-protocol bgp 2.2.2.2', 
 'show route advertising-protocol bgp 2.2.2.2',
 'show bgp neighbor 3.3.3.3',
 'show route receive-protocol bgp 3.3.3.3',
 'show route advertising-protocol bgp 3.3.3.3'] 

相关问题 更多 >