简体   繁体   中英

How do I ssh into a server and run a bash script that requires bash variables and sshes into another server?

I've tried the most popular solution to this, namely using the -t parameter on ssh and running a command before bash initializes. Sadly, the script I am trying to run requires bash variables so this is not an option for me. These are the approaches I've tried:

Approach 1:

Just to show what I was trying above:

ssh -A me@proxy -t 'echo 0 | /usr/local/bin/hop-server.sh <parameters> && bash -l'

It sshes into the proxy but then it spits out a number of missing environment variables from the script.

Approach 2:

Added the script into ~/.bashrc:

if [ "$HOP" = "dev1" ]; then
    /usr/local/bin/hop-server.sh <parameters>
fi

And to connect:

ssh -A me@proxy -t 'HOP=dev1 bash -l'

This does not spit out environment variables as missing, but the hop does not succeed and I am stuck in the proxy:

me@proxy:~$  ~/proxytodev1
Setting environment variables...
Setting project...
Resolving 'dev1'...
Connecting to 123.123.123.123...
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-63-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

17 packages can be updated.
9 updates are security updates.

me@proxy:~$ 

You can use ssh config option SendEnv

ssh -o 'SendEnv HOP' ...

Note that ssh server must be configured to accept it ( AcceptEnv in sshd).


Alternatively, you can use the .ssh/environment file on the server side to set variables you want to be present on the ssh connection:

HOP=<destination>

For the server to accept it, you must set to true the PermitUserEnvironment sshd config option.

You can pass environment variables to a process with this syntax:

foo=bar ./script.sh

will set foo to the value bar and pass it to the script. You can have as many of those name=value pairs as you want.

Just be careful with variable expansion; depending on which quotes you use, variables are expanded locally and then sent to the remote side or they are sent as is and then expanded remotely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM