循环嵌套列表?

时间:2019-08-07 04:00:51

标签: python

因此,我正在尝试构建一个验证脚本,该脚本可访问主设备下的设备列表,并且每个设备都应使用命令集。

我想问问我是否可以使用最佳方法来循环此操作,例如,如果将主设备连接到Internet设备,然后使用指定的命令检查Internet下的设备。

List Main device:
   1. Internet Device
      a. 1.1.1.1
    - List of command [show con, show 1.1.1.1]
      b. 1.1.1.2
    - list of command [show con, show 1.1.1.2]
   2. Private Device
      a. 1.1.1.3
    - List of command [show con, show 1.1.1.3]
      b. 1.1.1.4
    - List of command [show con, show 1.1.1.4]

我应该为此创建一个txt文件还是像字典样式一样?例如主要设备,设备,命令的列表?

是否应该使用嵌套列表以及for循环嵌套来实现此目的?或创建多功能功能?

我将命令列表分开以供其他使用。但是,举例来说,我确实拥有5台以上的设备,那么我的代码是否可以进行此设置?

# sample code: #

internetdev = [1.1.1.1,1.1.1.2]
internetcommd = [[show con, show 1.1.1.1],[show con, show 1.1.1.2]]
privatedev = [1.1.1.1,1.1.1.2]
privcommd = [[show con, show 1.1.1.4]]

for intdev,intcmd in zip(internetdev,internetcommd[0:]):
    print 'Connecting to ',intdev ,'\nSending command ',intcmd
    child = begin_rmt(intdev,intcmd,uname,tpass)

for privdev,privcmd in zip(privatedev,privcommd[0:]):
    print 'Connecting to ',privdev ,'\nSending command ',privcmd
    child = begin_rmt(privdev,privcmd,uname,tpass)

有什么建议吗?如果您能提供示例代码或参考,以便我进行审核,那也更好。谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用嵌套词典。像

devices = {
    "public": [
        {
            "name": "1.1.1.1",
            "command": ["show con", "show 1.1.1.1"]
        },
        {
            "name": "1.1.1.2",
            "command": ["show con", "show 1.1.1.2"]
        }
    ],
    "private": [
        {
            "name": "1.1.1.3",
            "command": ["show con", "show 1.1.1.3"]
        },
        {
            "name": "1.1.1.4",
            "command": ["show con", "show 1.1.1.4"]
        }
    ]
}