问:从netmiko连接的字典中将主机名转换为IP?

时间:2016-11-02 02:41:26

标签: python-2.7

在过去,我能够做这样简单的事情来阅读文件 我会迭代到每个人的SSH的IP地址

# Grab the list of devices from a text file
devices = open('./devices.txt','r').read().split('\n')

# Connect to each router and do a show run command
for device in devices:
    net_connect = ConnectHandler(device_type="cisco_ios", ip=device, username="myusername",
                             password=password)

然而,这一次,我需要做一些更复杂的事情。

我从JSON源中提取一些数据,我可以从中获取“主机名”。 但我无法连接到“主机名”。如果主机名在DNS中 那会更容易,但可悲的是他们不是。

所以..我有一个IP主机列表,我认为我可以使用和拉动 进入字典。

但是现在我不知何故需要匹配派生自的主机名 要与hosts.csv中的switchname匹配的JSON数据,以便我可以 然后基本上将主机名转换为IP,以便我可以遍历每个 设备中的设备可以通过SSH连接到每个设备中。

到目前为止,这就是我所拥有的一切。我陷入了困境。不确定如何匹配 要在我的net_connect语句中使用IP。

# Creat dict mapping hostnames to IP address for devices
with open(r'hosts.csv', 'r') as f:
    for line in f:
        switch = {}
        switch_line = line.split(',')
        switch = {
            'ip': switch_line[1],
            'switchname': str(switch_line[0]).strip('\n')

# Define list of devices to connect to and the config changes to be made
pa = []

# This data is coming from a JSON source
for device in devices:
    if device['switchParent']:
        hostname = device['switchParent']
    else:
        hostname = device['destDevice']
        # hostname technically is the device I need to connect
        # however it needs to resolve to an IP from the switch dict earlier
        net_connect = ConnectHandler(device_type="cisco_ios", ip=hostname,                                                          
                                username="myusername", password=password)

1 个答案:

答案 0 :(得分:1)

假设mutiply(3, 4, 0) int mutiply(int a, int b, int result) { if(a > 0) { for(int i=1;i<=b;i++) result++ mutiply(--a, b, result); } else return (result == 0 && a == 0) ? 0 : result; } 具有唯一的switchname地址,那么您应该以这种方式解析ip文件:

hosts.csv

然后,您将浏览JSON数据源:

# Create dict mapping hostnames to IP address for devices
switch = {}
with open(r'hosts.csv', 'r') as f:
    for line in f:       
        switch_line = line.split(',')
        switch[str(switch_line[0].strip())] = switch_line[1]

如果期望# This data is coming from a JSON source for device in devices: if device['switchParent']: hostname = device['switchParent'] else: hostname = device['destDevice'] # hostname technically is the device I need to connect # however it needs to resolve to an IP from the switch dict earlier net_connect = ConnectHandler(device_type="cisco_ios", ip=switch[hostname], username="myusername", password=password) 成为hostname字典中的密钥之一,则应该有效。