SUBPROCESS ON REMOTE SERVER

lois waisbrooker

Total Post:70

Points:494
Posted by  lois waisbrooker
Python 
 570  View(s)
Ratings:
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.
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Subprocess on remote server

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!