Hands-On Enterprise Automation with Python.
上QQ阅读APP看书,第一时间看更新

Using netmiko for SSH

Now it's time to utilize netmiko and see its power for SSHing to network devices and executing commands. By default, netmiko handles many operations in the background during session establishment, such as adding unknown SSH key hosts, setting the terminal type, width, and height, and accessing enable mode when required, then disabling paging by running a vendor-specific command. You will need to define the devices first in dictionary format and provide five mandatory keys:

R1 = {
'device_type': 'cisco_ios',
'ip': '10.10.88.110',
'username': 'admin',
'password': 'access123',
'secret': 'access123',
}

The first parameter is device_type, and it is used to define the platform vendor in order to execute the correct commands. Then, we need the ip address for SSH. This parameter could be the device hostname if it's already been resolved by your DNS, or just the IP address. Then we provide the username, password, and enable-mode password in secret. Notice you can use the getpass() module to hide the passwords and only prompt them during the script execution.

While the keys order inside the variable is not important, the key's name should be exactly the same as provided in the previous example in order for netmiko to correctly parse the dictionary and to start to establish a connection to the device.

Next, we will import the ConnectHandler function from the netmiko module and give it the defined dictionary to start the connection. Since all our devices are configured with an enable-mode password, we need to access the enable mode by providing .enable() to the created connection. We will execute the command on the router terminal by using .send_command(), which will execute the command and return the device output to the variable:

from netmiko import ConnectHandler
connection = ConnectHandler(**R1)
connection.enable()
output = connection.send_command("show ip int b")
print output

The script output is:

Notice how the output is already cleaned from the device prompt and the command that we executed on the device. By default, Netmiko replaces them and generates a cleaned output, which could be processed by regular expressions, as we will see in the next chapter.

If you need to disable this behavior and want to see the device prompt and executed command in the returned output, then you need to provide additional flags to .send_command() functions:

output = connection.send_command("show ip int b",strip_command=False,strip_prompt=False)

The strip_command=False and strip_prompt=False flags tell netmiko to keep both the prompt and command and not to replace them. They're True by default and you can toggle them if you want: