Question

I am running a python script on a windows machine to invoke another python script on a remote linux machine. I am using subprocess.call with ssh to do this, like below: subprocess.call('ssh -i <identify file> username@hostname python <script_on_linux_machine>') and this works fine.

However, if I want to set some environment variables, like below: subprocess.call('ssh -i <identify file> username@hostname python <script_on_linux_machine>', env={key1:value1}) it fails. I get the following error: ssh_connect: getnameinfo failed ssh: connect to host <hostname> port 22: Operation not permitted 255

I've tried splitting the ssh commands into list and passing. Didn't help. I've tried to run other 'local'(windows) commands thru subprocess.call() and tried setting the env. It works fine. I've tried to run other commands(such as ls) on the remote linux machine. Again, subprocess.call() works fine, as long as I don't try to set the environment.

What am I doing wrong? Would I be able to set the environment for a python script on a remote machine? Any help will be appreciated.

Was it helpful?

Solution

To set the environment on the remote side, you will need to do calls on the remote side. Try writing and uploading a wrapper script which does this env setting, e.g.

import subprocess
import sys


args = sys.argv[1:]
env = dict(zip(args[::2], args[1::2]))

subprocess.call(['python', 'script.py'], env=env)

Now you just have to pass this information in your original call, e.g.

subprocess.call('ssh -i <identify file> username@hostname '
                'python <script_on_linux_machine> %s %s' % (key, value))

Or some more extensible method of converting a dict to the required format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top