0

我正在尝试通过python自动化分别在Router1/2/3中配置loopback1/2/3,下面是我的代码。

from netmiko import ConnectHandler

i = 0
for n in range (177,180):
    i += 1
    HOST = "192.168.122." + str(n)
    ROUTER = {
    'device_type': 'cisco_ios',
    'ip': HOST,
    'username': 'cisco',
    'password': 'cisco',
    }
    device = [ROUTER]
    for devices in device:
        net_connect = ConnectHandler(**devices)
        output = net_connect.send_config_set("int lo" + str(i) + "\n" + "ip address " + str(i) + "." + str(i) + "." + str(i) + "." + str(i) + " 255.255.255.255")
    print (i)

运行代码时出现错误,请参见下文。

root@NetworkAutomation-1:~# python3 netmikoconfigmultiplerouters-2.py
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/paramiko/channel.py", line 699, in recv
    out = self.in_buffer.read(nbytes, self.timeout)
  File "/usr/local/lib/python3.8/dist-packages/paramiko/buffered_pipe.py", line 164, in read
    raise PipeTimeout()
paramiko.buffered_pipe.PipeTimeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/netmiko/base_connection.py", line 569, in _read_channel_expect
    new_data = self.remote_conn.recv(MAX_BUFFER)
  File "/usr/local/lib/python3.8/dist-packages/paramiko/channel.py", line 701, in recv
    raise socket.timeout()
socket.timeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "netmikoconfigmultiplerouters-2.py", line 18, in <module>
    output = net_connect.send_config_set("int lo" + str(i) + "\n" + "ip address " + str(i) + "." + str(i) + "." + str(i) + "." + str(i) + " 255.255.255.255")
  File "/usr/local/lib/python3.8/dist-packages/netmiko/base_connection.py", line 1875, in send_config_set
    new_output = self.read_until_pattern(pattern=re.escape(cmd.strip()))
  File "/usr/local/lib/python3.8/dist-packages/netmiko/base_connection.py", line 651, in read_until_pattern
    return self._read_channel_expect(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/netmiko/base_connection.py", line 579, in _read_channel_expect
    raise NetmikoTimeoutException(
netmiko.ssh_exception.NetmikoTimeoutException: Timed-out reading channel, data not available.
root@NetworkAutomation-1:~#

有人可以帮帮我吗?

在此先感谢 Nagsheshu。

4

1 回答 1

2

Netmiko 的 send_config_set 需要一个命令列表,所以我不会尝试构造多行字符串。相反,我会做类似的事情:

# Do you really just want it to be i.i.i.i for the IP?
cmd_list = [
    f"interface Loopback{i}",
    f"ip address {i}.{i}.{i}.{i} 255.255.255.255"
]
output = net_connect.send_config_set(cmd_list)
于 2021-06-11T17:22:21.203 回答