2

Is there away to declare a global variable over ssh so it will be accessible from other ssh connections ? for an example ssh firas@10.0.0.1 "x=10" Can another user x echo the value x=10 by sshing to the machine ssh x@10.0.0.1 "echo $x"

  • 1
    Possible duplicate of [How to export a shell variable to all sessions?](https://stackoverflow.com/q/14991313/608639), [Set a parent shell's variable from a subshell](https://stackoverflow.com/q/15541321/608639), [Export an env variable to be available at all sub shells, and possible to be modified?](https://unix.stackexchange.com/q/8342/56041), [How have both local and remote variable inside an SSH command](https://stackoverflow.com/q/13826149/608639), etc – jww Jun 02 '18 at 04:31

2 Answers2

4

Not directly but it's fairly easy to do if you use OpenSSH. First, enable PermitUserEnvironment in sshd config and restart sshd. Be aware of possible security implications as described in man sshd_config:

 PermitUserEnvironment
         Specifies whether ~/.ssh/environment and environment= options in ~/.ssh/authorized_keys are processed
         by sshd(8).  The default is no.  Enabling environment processing may enable users to bypass access
         restrictions in some configurations using mechanisms such as LD_PRELOAD.

Now you save a new variable to ~/.ssh/environment like that:

ssh localhost 'echo variable=new-value-of-the-var > ~/.ssh/environment'

And another user can read it:

$ ssh localhost 'echo $variable'
new-value-of-the-var

Notice that you need to use single quotes ' instead of " for this to prevent your shell from expanding $variable before passing it to the ssh.

However, it wouldn't work if you use dropbear: http://lists.ucc.gu.uwa.edu.au/pipermail/dropbear/2007q3/000615.html

Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
2

The Short answer is No

When you ssh into a host, your session spawns a subshell (a child process) to operate in. The parent process for the child will be the shell on the remote machine.

A child cannot affect the environment of its parent.

So any subshell spawned to handle your ssh connection cannot set any variable that will remain after the connection is closed.

note: You can however, write to a file on the host machine that will then be available for subsequent connections.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 1
    Firas is asking if one user can set a variable on a remote ssh server, so that when another user connects via ssh then they also inherit the variable. However, the answer is still No unless they want to edit the bashrc or profile. – Robert Seaman Jun 01 '18 at 17:33
  • Ah yes, the answer is still no for much the same reason. The subshell will only provide the environment it has to the ssh connection. You must prepare that environment on the server to provide what is needed for the ssh connections. (which is nothing more than creating a file to store variables in) – David C. Rankin Jun 01 '18 at 17:35