简体   繁体   中英

ssh connection to a router with a python script

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

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 ).

plumbum is what you're looking for. ( remote commands )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM