Remote SSH and set of commands and variable substi

2019-09-10 02:10发布

The question is how to substitute local and remote variables in a Remote SSH session.

I have a script on local Server. And following is the extract from it.

#!/bin/bash
Date=`/bin/date`
Schedule="2016-02-01 14:30:00"

Startup_loop()
{

#ssh connection to remote host $1 and start of loop of statements to be executed remotely
ssh root@$1  << EOF

#To display the Remote Hostname
hostname

#Check if the following local variables are available remotely as well
echo $Date
echo $Schedule

#Check and set the variable sysconf_clock_var on remote host
clock_var=`/usr/bin/grep BLAH /etc/Command | /usr/bin/awk -F\" '{ print $2}'`
echo $clock_var

#Modify the proc based on $startup_schedule
echo $clock_var >> /proc/Schedule

#Change the paramter on the remote file /etc/Command
sed -i -e 's/BLAH="yes"/BLAH="no"/' /etc/Command

echo "The remote ssh is completed"  >> /tmp/File_$Schedule_$Date.log

EOF

}

#Main Loop
##Accept the system IP from the User
echo Hello Please enter the system IP
read systemIP

#Call the procedure by passing the system IP
Startup_loop $systemIP

The script does not function as expected. E.g the value of hostname command inside ssh loop shows local hostname. What is failing here?

标签: linux bash ssh
1条回答
Lonely孤独者°
2楼-- · 2019-09-10 02:28

Consider the following pattern:

rmthost=hostname
var1="remote value 1"; var2="remote value 2"
printf -v env_str '%q ' remote_var1="$var1" remote_var2="$var2"
ssh "$rmthost" "env $env_str bash -s" <<'EOF'
   echo "Using remote variable: $remote_var1"
   var2=foo; echo "Using local variable: $var2"
EOF

This works because quoting the sigil used for a heredoc (<<'EOF', not <<EOF) prevents any expansions from taking place locally, such that they're all remote; then, using env to put these quoted values in the remote environment before the shell interpreter starts ensures that they're available for use.

At the same time, printf %q formats content in such a way that a remote shell executing it will only see the exact values, making variables with values such as var1=$'$(rm -rf *)\'$(rm -rf *)\'' safe.


When I run the code given (with the only modification being the value of rmthost), the output is as follows:

Using remote variable: remote value 1
Using local variable: foo
查看更多
登录 后发表回答