远程SSH和一组命令和变量替换

时间:2016-02-23 14:22:28

标签: linux bash ssh

问题是如何在远程SSH会话中替换本地和远程变量。

我在本地服务器上有一个脚本。以下是它的摘录。

#!/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

脚本无法正常运行。例如,ssh循环中hostname命令的值显示本地主机名。这里失败了什么?

1 个答案:

答案 0 :(得分:2)

考虑以下模式:

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

这是有效的,因为引用用于heredoc(<<'EOF'而非<<EOF)的sigil会阻止任何扩展在本地发生,这样它们都是远程的;然后,在shell解释器启动之前使用env将这些引用的值放在远程环境中,确保它们可以使用。

同时,printf %q以这样的方式格式化内容:执行它的远程shell只会看到确切的值,从而使var1=$'$(rm -rf *)\'$(rm -rf *)\''等值的变量安全。

当我运行给定的代码时(唯一的修改是rmthost的值),输出如下:

Using remote variable: remote value 1
Using local variable: foo
相关问题