Rayne
Rayne

Reputation: 14997

Cannot ssh to run a remote script using Python

I have the script below (test.py on 1.1.1.1) to run another remote script on another server (script.py on 2.2.2.2). I have set up the ssh keys so I don't get prompted for password.

import subprocess

USER="user"
SERVER_IP="2.2.2.2"
SCRIPT_PATH="/home/abc/script.py"

print ("ssh {0}@{1} '/usr/bin/python {2} aaa bbb'".format(USER, SERVER_IP, SCRIPT_PATH))

rc = subprocess.check_output("ssh {0}@{1} '/usr/bin/python {2} aaa bbb'".format(USER, SERVER_IP, SCRIPT_PATH))

script.py itself is on 1.2.3.4, and takes in 2 arguments.

If I copy the command that is printed out in the script, I can execute script.py successfully on 1.1.1.1. But running test.py on 1.1.1.1 gives me an error:

OSError: [Errno 2] No such file or directory

I don't understand why the script didn't work but the exact same command works on its own.

Upvotes: 2

Views: 245

Answers (2)

Dinesh
Dinesh

Reputation: 1565

Use the additional argument:

shell=True

Your command will be:

rc = subprocess.check_output("ssh {0}@{1} '/usr/bin/python {2} aaa bbb'".format(USER, SERVER_IP, SCRIPT_PATH),shell=True)

I assume you need a shell to run a python script.

Upvotes: 1

trust512
trust512

Reputation: 2254

If your question is to address the need of executing a remote command and not making your script working - then if I could introduce Paramiko:

import paramiko

ssh_handle = paramiko.SSHClient()
ssh_handle.load_system_host_keys()
ssh_handle.connect(
    hostname=address,
    port=int(port),
    username=login)

stdin, stdout, stderr = ssh_handle.exec_command("whoami")

IMO it's currently the most "usable" SSH library and works just fine in my projects.

Upvotes: 1

Related Questions