我正在编写一个包装器脚本,将无密码ssh设置为其他服务器以供其他脚本使用。
问题是内部脚本无法接受用户输入。例如,每当收到
无法建立主机'hostname.server(XXX.XXX.XX.XX)'的真实性。
RSA密钥指纹为RS:A-:FI:NG:ER:PR:IN:T - 。
您确定要继续连接(是/否)吗?
并且用户输入任何内容(不,是或否,然后按回车键),内部脚本失败,因为他们没有期待输入。 我对内部脚本没有任何控制权,也无法编辑它们。
我的包装器脚本实际上设置了ssh,并且还在其他脚本运行之前将ssh测试到服务器中。
我希望包装器脚本在需要用户输入的任何ssh响应(如上所述)以及任何类型的ssh错误时出错,因此在包装器脚本中很快就会知道失败,而不是在以后的内部脚本。
这样做的好方法是什么?
答案 0 :(得分:1)
在调用ssh
之前,将主机指纹添加到known_hosts文件中ssh-keyscan -H your_hostname >> ~/.ssh/known_hosts
在将指纹添加到known_hosts之前,请确保您信任服务器以避免安全问题。
答案 1 :(得分:0)
您正在寻找的SSH选项是BatchMode
。
从手册页:
BatchMode
If set to ``yes'', passphrase/password querying will be disabled.
This option is useful in scripts and other batch jobs where no
user is present to supply the password. The argument must be
``yes'' or ``no''. The default is ``no''.
为您的连接设置超时可能也很有价值,因此网络问题不会导致您的ssh客户端永远挂起:
ConnectTimeout
Specifies the timeout (in seconds) used when connecting to the
SSH server, instead of using the default system TCP timeout.
This value is used only when the target is down or really
unreachable, not when it refuses the connection.
ConnectTimeout的默认值可能为0,这会导致ssh永远等待。
您可以将其放在命令行中:
ssh -o BatchMode=yes -o ConnectTimeout=15 me@host.example.com
或在~/.ssh/config
之类的配置文件中:
host example host.example.com
hostname host.example.com
user me
BatchMode yes
ConnectTimeout 15
请注意,如果连接失败,SSH将在其退出值中返回状态,因此您可以使用以下shell构造:
if ! ssh example bin/do_something; then
echo "ERROR: bailing out of $0." >&2
exit 1
fi
ssh命令也会产生标准错误,解释失败的原因。