Home > DeveloperSection > Forums > Subprocess on remote server
lois waisbrooker
lois waisbrooker

Total Post:70

Points:494
Posted on    November-19-2015 6:33 AM

 Python Python 
Ratings:


 1 Reply(s)
 249  View(s)
Rate this:
I am using this code for executing command on remote server.

import subprocess
import sys
COMMAND="ls"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result
When I try to execute this script, I get prompt for password. Is there any way I could avoid it, for example, can I enter password in script somehow? Also, password should be encrypted somehow so that people who have access to the script cannot see it.


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    November-19-2015 6:47 AM

One way is to create a public key, put it on the server, and do ssh -i /path/to/pub/key user@host or use paramiko  like this:

import paramiko
import getpass
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
p = getpass.getpass()
ssh.connect('hostname', username='user', password=p)
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()

Don't want to miss updates? Please click the below button!

Follow MindStick