Execute commands in remote machine using python Paramiko

Execute linux commands in remote machine by passing commands over network and retriever Executed command's output..
All you need to do is install python paramiko package

sudo apt-get install python-paramiko
or download from here
http://www.lag.net/paramiko/download/paramiko-1.7.6.tar.gz

Execute below code to send commands to remote linux machine
only thing is ssh server should be running in remote machine
(Dont worry if not running  try this command  sudo /etc/init.d/ssh start )

Paramiko provides the basic interface to instantiate server connections.
  1. connect  --> connects to server
  2. AutoAddPolicy -->  auto-accept unknown keys
  3. stdin    -->  input channel to send commands
  4. stdout   -->  output channel to read output
  5. stderr   --> returns errors


 #!/usr/bin/python
 import paramiko
 ssh = paramiko.SSHClient()
 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 ssh.connect('<ip / hostname>', username='<username>', password='<password>')
 stdin, stdout, stderr = ssh.exec_command('ls')
 print 'This is output =',stdout.readlines()
 print 'This is error =',stderr.readlines()
 ssh.close()


If you want to give inputs to the terminal / shell

Read more : http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

Example showing how to execute "sudo" commands
#!/usr/bin/python
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('<ip / hostname>', username='<username>', password='<password>')
stdin, stdout, stderr = ssh.exec_command('sudo ls')
stdin.write(passwd + '\n')
stdin.flush()
print stdout.readlines()
ssh.close()


If you use paramiko.SSHClient() you will not get output until executed command exits.

So, If you want to read the output simultaniously when the executing command throws output ?

Use  paramiko.Transport() method
Here is he example

import paramiko,sys

 trans = paramiko.Transport((host, 22))
 trans.connect(username=user, password=passwd)
 session = trans.open_channel("session")
 session.exec_command('ls')
 session.recv_exit_status()
 while session.recv_ready():
     temp += session.recv(1024)
     print temp 

Read this thread for more options available...

http://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko