Reputation: 449
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...)
Upvotes: 3
Views: 5013
Reputation: 1
Try
ssh root@ofs1 "env CONTROLLER_IP=$ofc1 somescript"
(assuming $ofc1
is evaluated to some IP address like 12.234.56.178
without spaces or naughty characters)
or perhaps
ssh root@ofs1 "env CONTROLLER_IP='$ofc1' somescript"
if $ofc1
could contain spaces or naughty characters
where somescript
is a script on the remote machine ofs1
; if you want an interactive shell try
ssh root@ofs1 "env CONTROLLER_IP='$ofc1' /bin/bash"
At last, ssh
is usually setting some environment variables (on the remote machine), notably the SSH_CONNECTION
one. You could use it on the remote machine. Its third field is the IP address of the origin host (the one on which you do the ssh
...). So perhaps the .bashrc
on the remote host might contain
if [ -n "$SSH_CONNECTION" ]; then
export CONTROLLER_IP=$(echo $SSH_CONNECTION|cut -f3 -d' ')
fi
better yet, replace the CONTROLLER_IP
occurrences in your remote scripts with something using SSH_CONNECTION
Upvotes: 0
Reputation: 124656
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"
Upvotes: 3