如果 SSH 提示输入密码,则退出脚本

如果 SSH 提示输入密码,则退出脚本

我正在尝试实现一个需要从 XYZ 服务器 SSH 到 ABC 服务器的场景。公钥将已设置以平滑无密码登录。现在,如果发现 SSH 命令提示输入密码,我只想退出脚本。这意味着公钥没有设置。

ssh -o ConnectTimeout=10 user@ABC <<HERE
----- doing some stuff here----
HERE

输出-

Password:

脚本驻留在 XYZ 上。我从 XYZ 运行它并尝试 SSH ABC。如果提示输入密码,则通过打印消息退出脚本。

答案1

尝试

ssh -o BatchMode=yes

根据man 5 ssh_config

批处理模式

       If set to “yes”, passphrase/password querying will be disabled.
         In addition, the ServerAliveInterval option will be set to 300
         seconds by default.  This option is useful in scripts and other
         batch jobs where no user is present to supply the password, and
         where it is desirable to detect a broken network swiftly.  The
         argument must be “yes” or “no”.  The default is “no”.

答案2

将选项添加PreferredAuthentications=publickey到您的连接字符串:

ssh -o PreferredAuthentications=publickey -o ConnectTimeout=10 user@ABC

退出代码将为 255,您将获得以下信息:

user@ABC: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

答案3

将 PasswordAuthentication=no 添加到您的 ssh 选项

$ ssh -o PasswordAuthentication=no host
user@host: : Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
$ echo $?
255

相关内容