2

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
  • 119
  • 2
  • 2
  • 5

2 Answers2

6

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

b2Wc0EKKOvLPn
  • 2,054
  • 13
  • 15
  • I will have a look soon and come back to let you know. Sorry for the delay and thank you – sadek Mar 26 '13 at 11:09
  • Paramiko'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 http://stackoverflow.com/questions/30603219/executing-command-using-paramiko-on-brocade-switch – Akshay Kalghatgi Jun 01 '16 at 23:10
0

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

shx2
  • 61,779
  • 13
  • 130
  • 153