Anytime that you find a command working when issued from the shell prompt and failing when launched from some script there are only a very limited number of reasons why this can occur under Unix (and Linux).
The most likely is that your script is missing something from your interactive environment. One way to ensure that the environment you run a command in under Python's subprocess.Popen()
matches the environment under which you started Python is to explicitly pass a dictionary like environment to the Popen()
call like so:
#!/usr/local/bin/python
proc = subprocess.Popen(cmd, [args], env=os.environ)
... where os.environ
would be your Python process' environment. You could, naturally, create your own copy of it and selectively modify or remove key/value pairs from that and pass it to the Popen()
instead.
If your command includes any variables to be expanded then you may want to use the Popen()
option to set shell=True
; this will force Python to start a copy of your shell to interpret the command line contents. That, of course, is NOT TO BE TRUSTED WITH POTENTIALLY HOSTILE INPUTS. (In other words don't blindly take strings from an untrusted source and try to run them through your shell).
In this case, while trying to use ssh
I would suggest you look for any SSH_AGENT and SSH_AUTHSOCK environment settings in particular. It's pretty common for people to have ssh-agent
configured and to forget all about it until it bites them when trying to automate their use of tunnels, ssh proxies and VPN services.
In my own ssh-agent
handling I use printenv | ssh 'SSH_A[UG]' > ~/.ssh/env; echo "export SSH_AUTH_SOCK SSH_AGENT_PID >> ~/.ssh/env
to save the appropriate environment settings after starting a new ssh-agent
session (which, of course, I do only rarely -- my workstations and laptops rarely end up rebooted). Then my ~/.bash_profile
sources that file. (Actually it also does a kill -0 "$SSH_AGENT_PID" || ~/bin/start_ssh_agent.sh
as well, and re-sources the env file if necessary; that's just to auto-restart the agent).