【问题标题】:Remote SSH and set of commands and variable substitution远程 SSH 和一组命令和变量替换
【发布时间】:2016-02-23 14:22:27
【问题描述】:

问题是如何在远程 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 命令的值显示本地主机名。这里有什么问题?

【问题讨论】:

  • @Kenster 修复了您的代码格式。怎么又破了?
  • 顺便说一句,我忽略了很多 shellcheck.net 会自动找到并识别修复程序的错误 - 一般而言,请在此处提问之前运行您的代码。
  • 我只是按照 Shelter 给出的说明进行操作。那它坏了吗?
  • 我会在 shellcheck 上检查脚本并还原。谢谢顺便说一句。
  • @SachinH,缺少引号并不是次要的。

标签: linux bash ssh


【解决方案1】:

考虑以下模式:

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 的印记(&lt;&lt;'EOF',而不是&lt;&lt;EOF)可以防止任何 扩展在本地发生,因此它们都是远程的;然后,在 shell 解释器启动之前使用env 将这些引用的值放入远程环境中,确保它们可供使用。

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


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

Using remote variable: remote value 1
Using local variable: foo

【讨论】:

  • 抱歉,这段代码不起作用。我试过了,它代替了一些奇怪的值。就像 printf 命令将 var1 值设置为整行一样。
  • 这就是 printf supposed 要做的事情:生成一个带有整行赋值的单个字符串;在env 之后替换,它们可以远程运行。没有什么“奇怪”的。
  • 无论如何——这绝对有效;我可以自己运行它(唯一的变化是远程主机名的值不同),它完全按照它所宣传的那样运行。如果它对你不起作用,你需要展示你是如何使用它的。
  • @SachinH, ...实际上,备份:printf 根本没有修改 var1,它设置了 env_str
猜你喜欢
  • 2011-03-19
  • 2010-12-25
  • 2017-04-16
  • 2021-11-20
  • 1970-01-01
  • 2021-05-11
  • 2021-10-13
  • 2016-10-13
  • 1970-01-01
相关资源
最近更新 更多