命令行嵌套ssh中bash shell脚本中的参数

时间:2016-05-16 19:56:48

标签: bash shell ssh

我正在尝试使用$ 1,$ 2变量,我已通过命令行传递给bash shell脚本。我在ssh调用中使用的这些变量。但似乎ssh中的变量没有被替换,外部变量正在被替换。任何解决方法?这是代码

#!/bin/bash

ssh -t "StrictHostKeyChecking=no" -i  $1 user@ip<<'EOF1'

ssh -t -i $1 user2@ip2 <<'EOF2'

exit
EOF2

exit
EOF1

这里第一个$ 1被替换,但第二个没有。它基本上是密码减少认证的关键名称

2 个答案:

答案 0 :(得分:5)

使用printf %q生成参数列表的eval - 安全字符串版本:

# generate a string which evals to list of command-line parameters
printf -v cmd_str '%q ' "$@"

# pass that list of parameters on the remote shell's command line
ssh "$host" "bash -s $cmd_str" <<'EOF'
  echo "This is running on the remote host."
  echo "Got arguments:"
  printf '- %q\n' "$@"
EOF

对于您真正做的事情,最佳做法可能是使用ProxyCommand - 请参阅the relevant documentation - 并通过代理转发公开您的私钥,而不是让它坐在磁盘上的弹跳主机上。也就是说,直接采用上面给出的答案来拟合问题中的代码:

#!/bin/bash
printf -v args '%q ' "$@"
echo "Arguments on original host are:"
printf '- %q\n' "$@"
ssh -t "StrictHostKeyChecking=no" -i "$1" user@ip "bash -s $args" <<'EOF1'
  printf -v args '%q ' "$@" 
  echo "Arguments on ip1 are:"
  printf '- %q\n' "$@"
  ssh -t -i "$1" user2@ip2 "bash -s $args" <<'EOF2'
    echo "Arguments on ip2 are:"
    printf '- %q\n' "$@"
EOF2
EOF1

答案 1 :(得分:1)

更简单的是让ssh为你处理隧道。

ssh -o ProxyCommand="ssh user1@ip1 nc -w 10 %h %p" user2@ip2

(此示例位于http://undeadly.org/cgi?action=article&sid=20070925181947)。