Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit environment variable in ssh session?

Tags:

linux

ssh

I need to deal with a lot of remote machines, and each machine shares a global environment variable ( like CONTROLLER_IP). When I try to ssh to the remote machine, I would like to set the CONTROLLER_IP according to current localhost setting. is there any way to make it happen?

Example:

In localhost host, I set ofc1=192.168.0.1, and ofc2=192.168.1.1 and I need to ssh to ofs1, ofs2. I would like to do something like:

CONTROLLER_IP=$ofc1 ssh root@ofs1; CONTROLLER_IP=$ofc2 ssh root@ofs2

then I will get the CONTROLLER_IP setting in each ssh session. (the code shown above does not work...)

like image 470
alexzzp Avatar asked Feb 02 '26 01:02

alexzzp


1 Answers

In /etc/sshd_config on the server you can define the list of accepted environment variables using the AcceptEnv setting, and then you can send environment variables like this:

CONTROLLER_IP=$ofc1 ssh -o SendEnv=CONTROLLER_IP root@ofs1

But this seems a bit overkill for your purposes.

The alternative is to pass the variables in the remote command, like this:

ssh root@ofs1 "CONTROLLER_IP=$ofc1 somecmd"

Or if you run multiple remote commands then like this:

ssh root@ofs1 "export CONTROLLER_IP=$ofc1; cmd1; cmd2; cmd3; ..."

If you need to quote the value of the variable, you can do like this:

ssh root@ofs1 "CONTROLLER_IP='$ofc1' somecmd"
like image 125
janos Avatar answered Feb 03 '26 23:02

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!