我想捕获ssh会话的输出。但是,我首先需要ssh两次(从本地计算机到远程门户,再到远程服务器),然后运行命令并捕获输出。
逐行执行此操作,我将执行以下操作:
ssh [email protected]
ssh remote.server.com
remote.command.sh
我尝试了以下方法:
server=remote.server.com ##define in the script, since it varies
sshoutput=$(ssh -tt [email protected] exec "ssh -tt ${server} echo \"test\"")
echo $sshoutput
我希望上面的脚本在最终命令后回显“测试”。但是,外部ssh提示仅在我输入命令后挂起,一旦我按Ctrl + c或输入密码失败,内部ssh会话就会失败(我相信,因为不再将stdout打印到屏幕上,并且我也不再获取密码迅速的)。
如果我只运行内部命令(即,不使用“ sshoutput = $(”将其另存为变量),则可以运行,但(显然)不能捕获输出。我也尝试了不使用“ exec”的情况。
我也尝试过将内部ssh保存为像这样的变量
sshoutput=$(ssh -tt name@portal myvar=$(ssh -tt ${server} echo \"test\"") && echo $myvar)
但这失败了,因为BASH尝试先执行内部ssh,然后再将其发送到外部ssh会话(我相信),并且服务器名称无法识别。
(我看过https://unix.stackexchange.com/questions/89428/ssh-twice-in-bash-alias-function,但他们只是说“如果使用交互式密码,则需要更多标志”,并且不解决捕获输出问题)
在此先感谢您的协助!
此处的最佳实践方法是让ssh自己完成弹跳主机的工作。
result=$(ssh \
-o 'ProxyCommand=ssh [email protected] nc -w 120 %h %p' \
[email protected] \
"remote.command.sh")
您可以在中将其自动化~/.ssh/config
,如下所示:
Host remote.server.com
ProxyCommand ssh [email protected] nc -w 120 %h %p
...之后,任何ssh remote.server.com
命令都会自动跳过remote.portal.com
。(更改nc
为netcat
或类似,以适合于bouncehost上安装的工具)。
就是说,如果您真的想自己做,可以:
printf -v inner_cmd '%q ' "remote.command.sh"
printf -v outer_cmd '%q ' ssh [email protected] "$inner_cmd"
ssh [email protected] bash -s <<EOF
$outer_cmd
EOF
...其中的最后一部分可以在命令替换中运行,如下所示:
result=$(ssh [email protected] bash -s <<EOF
$outer_cmd
EOF
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句