Blog

03/06/2019

SSH: Use Remote Bash / KSH source Command Set Variable Locally From a Remote Server



I have setup a master / local server combination using OpenSSH. My local server depends upon master server for a remote sourcing. The remote sourcing should set a large number of variables locally in a bash shell script. The code is:

user@slave $ source ssh user@master "/service/dyn.master.setenv.sh --mode=slave"
echo “$var”

The var is not setting and I am getting various errors. How can I do a remote “source” of a bash script file (from master.example.com) and set a shell variable locally at slave.example.com?


You need to use eval or source command as follows to fix your problem:

source <(ssh user@server cat /path/to/varfile)

OR

eval $(ssh user@master cat /path/to/varfile)

Examples

Create a file called /tmp/foo on master server called master.example.com as follows:

JAIL=/lighttpd
PHP=/opt/bin/php5-cgi
MINIMAIL=/opt/bin/chroot-sendmail

Type the following command on server/workstation called slave.example.com (please note that [user@slave ~]$ is your prompt):

[user@slave ~]$ source <(ssh user@master.example.com  cat /tmp/foo)
[user@slave ~]$ echo "$JAIL $PHP $MINIMAIL"

OR

[user@slave ~]$ eval $(ssh user@master.example.com cat /tmp/foo)
[user@slave ~]$ echo "$JAIL $PHP $MINIMAIL"

Sample session

Following sample session uses localhost computer as a master and slave. However, the concept remains same for master.example.com and slave.example.com Server.

Fig.01: Bash remote source or eval command to set variables locally (click to enlarge)

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...