-1

I am trying to reverse ssh into the pi from my server. I have installed the ssh keys on the server and pi side.

Whenever I type in the following command in the terminal, I can login into my server without a password.

ssh -R 19999:localhost:22 usr@www.example.com

But, whenever I include the above in a bash script and execute it, it asks me for a password. This is weird. Why is that? can anyone help me with this ? Because, I want to run the command from a python script using the subprocess method (running bash script from python).

3 Answers3

1

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

Jim Dennis
  • 17,054
  • 13
  • 68
  • 116
0

At the top of your bash script that is getting called in, source your profile:

source ~/.bash_profile
PhysicalChemist
  • 540
  • 4
  • 14
0

http://www.mtu.net/~engstrom/ssh-agent.php ( Secure, Yet Password-Free SSH )

reference : How to use ssh command in shell script?

Community
  • 1
  • 1
nish
  • 1,008
  • 4
  • 17
  • 34