首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从CSV文件创建字典,然后连接到主机名,并根据字典键运行特定的命令

从CSV文件创建字典,然后连接到主机名,并根据字典键运行特定的命令
EN

Stack Overflow用户
提问于 2022-03-23 14:08:06
回答 1查看 89关注 0票数 0

我正在尝试编写一个脚本,它将连接到从CSV文件中提取的多个设备。基于我有限的python知识,我认为从CSV文件创建字典是最好的方法。

CSV将有一个包含三个标题的标题行,即hostnamedevice_platformdevice_role。设备平台可以是一些类似于cisco_ios & broadcom_icos的东西。

因此,现在我想使用这样的方法连接到每个主机名:

代码语言:javascript
复制
device_info = {
  'ip': hostname,
  'port': 22,
  'username': 'admin',
  'password': 'cisco123',
  'device_type': device_platform,
  'fast_cli': False
}
        
ssh_connection = ConnectHandler(**device_info)

其中,对于表中的每个主机名,它对设备类型使用device_platform

现在,让事情进一步复杂化,我想运行特定的命令在每个设备上,基于它的设备平台和设备角色。

因此,例如,设备角色命令应该如下所示:

代码语言:javascript
复制
VERIFCIATION_COMMANDS = {
  'cisco_ios':
    {
      'co-agg-r':
        [
          'term len 0', 'show processes cpu history', 'show processes cpu | i Core *', 'sh processes memory sorted',
          'sh process cpu sort 5sec | ex 0.00 +0.00 +0.00', 'show int | i line|packets/sec',
          'show int status | exclude disabled|notconnect', 'show etherchannel summary', 'show cdp neighbors',
          'show standby brief', 'show ip ospf neighbor', 'show ip bgp all summary', 'show int status | include err',
          'sh int desc | e admin down', 'sh int desc | i acc-sw', 'sh int desc | i dis-sw'
        ],
      'co-wlc':
        [
          'term len 0', 'show ap summary', 'show wlan summary', 'show wireless mobility sum',
          'show ip int bri | i Te|Gi', 'show cdp neighbors'
        ],
    },
  'cisco_asa':
    {
      'co-ics-fw':
        [
          'term pager 0', 'show failover state', 'show interface ip brief', 'show conn all', 'show arp'
        ]
    },
  'broadcom_icos':
    {
      'co-acc-rsw':
        [
          'terminal length 0', 'show port all', 'show ip interface brief', 'show ip ospf neighbor',
          'show lldp remote-device all', 'show isdp neighbors', 'show fiber-ports optical-transceiver all',
          'show udld all | include Enable'
        ]
    }
}

实现这一目标的最佳方法是什么?

EN

回答 1

Stack Overflow用户

发布于 2022-04-06 09:20:03

如果需要运行的命令需要根据节点的名称进行区分,则可以选择ssh每个设备的IP并获取名称信息。

如果您已经掌握了名称和IP信息,您可以创建一个字典作为{{'name': 'IP'}},并使用名称信息到达您想要连接的IP。

例如:(需要使用For循环。)

代码语言:javascript
复制
device_info= {
    'device_type': 'cisco',
    'ip': di['name'], # Which gives the IP information of the name. 
    'username': 'admin',
    'password': 'admin',
    'port': port
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71588637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档