'Sending Cisco commands from a text file using Netmiko fails. send_config_set works but send_config_from_file doesn't

  • I have been using this link as guide.

https://pyneng.readthedocs.io/en/latest/book/18_ssh_telnet/netmiko.html#:~:text=Netmiko%20is%20a%20module%20that,pip%20install%20netmiko

XXXXXX:/Test # cat test2.py
from netmiko import ConnectHandler

with open('commands_ios') as f:
    commands_list = f.read().splitlines()

cisco_D = {
    'device_type': 'cisco_ios',
    'host':   '10.1.1.1',
    'username': 'username',
    'password': 'password',
}

net_connect = ConnectHandler(**cisco_D)
output = net_connect.send_config_from_file('commands_ios.txt')
print(output)

XXXXXX:/Test # python3 test2.py

Traceback (most recent call last):
  File "test2.py", line 14, in <module>
    output = net_connect.send_config_from_file('commands_ios.txt')
  File "/usr/lib/python3.6/site-packages/netmiko/base_connection.py", line 1808, in send_config_from_file
    with io.open(config_file, "rt", encoding="utf-8") as cfg_file:
FileNotFoundError: [Errno 2] No such file or directory: 'commands_ios.txt'
AL108564:/Test #


Solution 1:[1]

You can use readlines instead of splitlines as follows. And if ypu have a .txt > you should change it like this => 'commands_ios.txt'

with open('commands_ios.txt') as f:
    commands_list = f.readlines() #(or commands_list = f.splitlines())
    
    #commands_list = "".join(commands_list ) => If you need convert string
    #commands_list = lines.strip() => If you need remove spaces
    #print(commands_list)

Solution 2:[2]

The script works alright; commands_ios.txt file consisted of Cisco show commands which is usually entered in enable mode, send_config_from_file only enters commands in Global Config mode only hence it was throwing an error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mert Kulac
Solution 2 richardec