- Hands-On Enterprise Automation with Python.
- Bassem Aly
- 348字
- 2021-06-18 19:22:32
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.
- 大學計算機基礎(第二版)
- OpenCV 3和Qt5計算機視覺應用開發
- 新編Premiere Pro CC從入門到精通
- 數據結構(C語言)
- 碼上行動:用ChatGPT學會Python編程
- UML 基礎與 Rose 建模案例(第3版)
- PHP從入門到精通(第4版)(軟件開發視頻大講堂)
- PHP與MySQL權威指南
- Instant Zurb Foundation 4
- AutoCAD基礎教程
- Spring Data JPA從入門到精通
- Google Adsense優化實戰
- Python應用開發技術
- 一步一步學Spring Boot:微服務項目實戰(第2版)
- SQL Server 2014 Development Essentials