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

SSH to the network device

As usual, in every Python module, we first need to import it into our Python script, then we will create an SSH client by inheriting from SSHClient(). After that, we will configure the Paramiko to automatically add any unknown host-key and trust the connection between you and the server. Then, we will use the connect function and provide the remote host credentials:

#!/usr/bin/python
__author__ = "Bassim Aly"
__EMAIL__ = "basim.alyy@gmail.com"

import paramiko
import time
Channel = paramiko.SSHClient()
Channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Channel.connect(hostname="10.10.88.112", username='admin', password='access123', look_for_keys=False,allow_agent=False)

shell = Channel.invoke_shell()

AutoAddPolicy() is one of the policies that can be used inside the set_missing_host_key_policy() function. It's preferred and acceptable in a lab environment. However, we should use a more restrictive policy in a production environment, such as WarningPolicy() or RejectPolicy().

Finally, the invoke_shell() will start the interactive shell session towards our SSH server. You can provide additional parameters to it such as the terminal type, width, and height.

Paramiko connect parameters:

  •  Look_For_Keys: By default, it's True, and it will force the Paramiko to use the key-pair authentication where the user is using both private and public keys to authenticate against the network device. In our case, we will set it to False as we will use password authentication.
  • allow_agent paramiko: It can connect to a local SSH agent OS. This is necessary when working with keys; in this case, since authentication is performed using a login/password, we will disable it.

The final step is to send a series of commands such as show ip int b and show arp to the device terminal and get the output back to our Python shell:

shell.send("enable\n")
shell.send("access123\n")
shell.send("terminal length 0\n")
shell.send("show ip int b\n")
shell.send("show arp \n")
time.sleep(2)
print shell.recv(5000)
Channel.close()

The script output is:

It's preferable to use time.sleep() when you need to execute commands that will take a long time on a remote device to force Python to wait some time till the device generates output and sends it back to python. Otherwise, python may return blank output to the user.

主站蜘蛛池模板: 浪卡子县| 沁阳市| 荆门市| 开鲁县| 清远市| 商城县| 灵丘县| 玉田县| 扎赉特旗| 平江县| 闽侯县| 东丰县| 波密县| 元阳县| 红原县| 工布江达县| 清镇市| 远安县| 秭归县| 航空| 西城区| 通化县| 宜章县| 新乐市| 宁津县| 河间市| 恩施市| 阿合奇县| 鄂托克前旗| 青神县| 巩留县| 安达市| 天峻县| 沭阳县| 丹棱县| 从江县| 招远市| 汶川县| 明溪县| 唐河县| 海门市|