嵌套ssh中bash shell脚本中的命令行参数 [英] Command line Parameters in bash shell script in nested ssh
问题描述
我试图使用$ 1,$ 2变量,这些变量是通过命令行传递给bash shell脚本的.我在ssh调用中使用的这些变量.但是似乎ssh中的变量没有被替换,外部的变量被替换了.任何解决方法?这是代码
I am trying to use $1, $2 variables which I have passed through command line to a bash shell script. These variables I am using within a ssh call. But its seems the variables within ssh are not getting replaced, the outer ones are getting replaced. Any workaround? Here's the code
#!/bin/bash
ssh -t "StrictHostKeyChecking=no" -i $1 user@ip<<'EOF1'
ssh -t -i $1 user2@ip2 <<'EOF2'
exit
EOF2
exit
EOF1
这里第一个$ 1被替换了,但是第二个没有被替换.它的基本密钥名称用于少密码验证
Here the first $1 gets replaced but the second one doesn't. Its basically key name for password less authentication
推荐答案
使用printf %q
生成参数列表的eval
安全字符串版本:
Use printf %q
to generate an eval
-safe string version of your argument list:
# 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-请参阅
For what you're really doing, the best practice is probably to use a ProxyCommand -- see the relevant documentation -- and to have your private key exposed via agent forwarding, rather than having it sitting on your bounce host on-disk. That said, it's straightforward enough to adopt the answer given above to fit the code in the question:
#!/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
这篇关于嵌套ssh中bash shell脚本中的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!