官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 新源县| 柳河县| 宁武县| 洪泽县| 永年县| 外汇| 玉溪市| 双城市| 札达县| 康保县| 平原县| 西乡县| 寻乌县| 营山县| 温泉县| 阳城县| 阳东县| 威信县| 喀喇| 莎车县| 蓬安县| 兴宁市| 左权县| 延川县| 平凉市| 娱乐| 临沧市| 阳朔县| 望城县| 镇远县| 济源市| 龙泉市| 杭州市| 潜山县| 侯马市| 宁河县| 甘洛县| 永吉县| 当雄县| 股票| 沙洋县|