ssh connection to a router with a python script
You can use paramiko
which is a python library that abstracts remote shell connections through ssh with several options allowing users to use authentication with rsa keys, etc. This is a sample code you can reuse to solve your problem:
import paramiko
ssh = paramiko.SSHClient()
ssh.connect( 'hostname', username = 'username', password = 'password' )
ssh.exec_command( 'ls -al' )
By the way paramiko can be easily added to your python environment if you're running your script from a virtual environment (virtualenv).
sadek
Updated on June 17, 2022Comments
-
sadek over 1 year
I wanted to know whether there is a possibility to use a python script in order to connect to a router and control the interface (shut down, restart wireless network etc..) with an ssh connection.
SO far I wrote these lines,but still it does not work. When i look to the terminal I see that everything is blocked at the point when my script should echo the password for the router to finalize the connection. How can I correct this please ?
Here are the lines :
import os, urllib, urllib2, re def InterfaceControl(): #os.system("echo training") os.system("ssh -l root 192.168.2.1") os.system("echo yes") os.system("echo My_ROUTER_PASSWORD") os.system("shutdown -r") def main(): InterfaceControl() if __name__=="__main__": main()
Thank you so much in advance
-
sadek over 10 yearsI will have a look soon and come back to let you know. Sorry for the delay and thank you
-
Akshay Kalghatgi over 7 yearsParamiko's exec_command uses scp and gives "Protocol error, doesn't start with scp" error. Using paramiko's invoke_shell() instead may help. Here's a link stackoverflow.com/questions/30603219/…