4

I'm trying to execute a script in SSH, and pass some params to that script. I've tried the following which didn't work - the value is not passed:

$ LC_FOO=x ssh -o SendEnv=LC_FOO $HOST < myLongScript.sh

The target hosts are sometimes very strict and recreated regularly so changing SSH settings on them is futile.

So I'm trying to resort to a trick and pass the value within the script itself. In other words, I want to append the variables to the script.

I've also tried these other approaches:

# doesn't work - 'ambiguous redirect'
$ ssh ... < $(...)

# doesn't work - 'LC_FOO=x: command not found'
$ $(echo "FOO=x"; cat myLongScript.sh) | ssh ...

How can I prepend the line on ssh's input?

  • LC_FOO=x ssh -o SendEnv=LC_FOO should have worked I think - provided the server side's AcceptEnv is set appropriately of course. Did you try something simple like LC_FOO=x ssh -o SendEnv=LC_FOO user@remotehost 'printenv LC_FOO'? – steeldriver Jul 10 '18 at 01:36
  • @slm on my Ubuntu/OpenSSH boxes, the (default) /etc/ssh/ssh_config and /etc/ssh/sshd_config have SendEnv LC_* and AcceptEnv LC_* respectively so actually for me it wasn't even necessary to add the -o SendEnv=LC_FOO – steeldriver Jul 10 '18 at 02:34
  • @steeldriver - interesting, this was on CentOS 6/7 systems, confirmed like you said on a Ubuntu 16.04 box I have here. – slm Jul 10 '18 at 02:39
  • The script connects to different systems and are very strict. "hardened" CentOS mostly. Edited. – Ondra Žižka Jul 10 '18 at 12:53

2 Answers2

4

You want a process substitution such as ssh ... < <(...). ssh ... < $(my_command) is a command substitution creates a redirect with each word from the result of my_command as the redirect target.

l0b0
  • 51,350
1

The first example will work if you enable the variable LC_FOO so that it's on the AcceptEnv list on the server side's /etc/ssh/sshd_config file.

$ grep AcceptEnv /etc/ssh/sshd_config
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
AcceptEnv LC_FOO

Now it works:

$ LC_FOO=x ssh -o SendEnv=LC_FOO root@host.mydom.com 'printenv LC_FOO'
x

Alternatives

redirect method

I've shown this in another U&L Q&A titled: How can I execute local script on remote machine and include arguments?, and for your example I'd recommend doing it like this:

$ ssh serverA "bash -s" -- < ./ex.bash "arg1" "arg2"

heredoc method

You could also do a heredoc style as well which I highlighted in this other U&L Q&A titled: View remote value of $PATH inside shell script:

[root@skinner ~]# ssh mulder 'bash -s <<EOL
>   echo $HOSTNAME
>   hostname
> EOL'
mulder.bubba.net
mulder.bubba.net

References

slm
  • 369,824