@note所有示例均假设您已使用设置了connectionString
类似的变量connectionString=user@server
。
我如何找到解决方案
使用ssh -T
应该适用于简单的命令。例如,这不会打印任何其他信息:
ssh -T $connectionString "echo 'blah'"
问题是当您尝试使用here-doc运行许多命令时。例如-波纹管将不起作用-它将回显当天的消息(MoTD),并且可能还会显示“ stdin:不是tty”。
somethingLocal='something local'
ssh -T $connectionString <<EOC
echo 'blah'
echo "blah $somethingLocal"
EOC
要变通解决此问题,您需要首先将命令保存到本地变量,然后将其发送到远程服务器。
somethingLocal='something local'
read -r -d '' commands <<EOC
echo 'blah'
echo "blah $somethingLocal"
EOC
ssh -T $connectionString "$commands"
但这很乱...
最终解决方案
创建一个通用函数(请注意,它可以使用字符串或HEREDOC作为命令)。
function silentSsh {
local connectionString="$1"
local commands="$2"
if [ -z "$commands" ]; then
commands=`cat`
fi
ssh -T $connectionString "$commands"
}
例子
这样使用:
somethingLocal='something local'
silentSsh $connectionString <<EOC
echo 'blah'
echo "blah $somethingLocal"
EOC
或者像这样:
silentSsh $connectionString "echo 'blah'"
或者像这样:
silentSsh $connectionString <<'EOC'
echo 'blah'
somethingRemote=`echo 'whatever'`
echo "blah $somethingRemote"
EOC
甚至像这样:
silentSsh $connectionString < getlines.sh