我试图使用$ 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
Run Code Online (Sandbox Code Playgroud)
这里第一个$ 1被替换,但第二个没有.它基本上是密码减少认证的关键名称
使用printf %q
生成eval
的参数列表的-safe的字符串形式:
# 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
Run Code Online (Sandbox Code Playgroud)
对于您真正在做的事情,最佳做法可能是使用ProxyCommand - 请参阅相关文档 - 并通过代理转发公开您的私钥,而不是将其置于磁盘上的退回主机上.也就是说,直接采用上面给出的答案来拟合问题中的代码:
#!/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
Run Code Online (Sandbox Code Playgroud)