在 RTFM 并进行一些测试之后,我发现这libssh2_userauth_publickey_fromfile
将返回不同的错误代码,具体取决于服务器不接受密钥还是密码不正确。
所以,这是一个非常低效的解决方案(因为它调用libssh2_userauth_publickey_fromfile
协议的所有密钥交换部分至少两次)。
int nAttempts = 3; // number of attempts the user gets at entering the passphrase
// Try authenticating with an empty passphrase
int err = libssh2_userauth_publickey_fromfile(session, user, pub, priv,"");
if (err == 0)
{
fprintf(stderr, "You shouldn't use keys with an empty passphrase!\n");
}
else if (err == LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED)
{
// if we get here it means the public key was initially accepted
// but the private key has a non-empty passphrase
char p[BUFSIZ];
for (int i = 0; i < nAttempts; ++i)
{
get_passphrase(p); // assume this gets the passphrase
err = libssh2_userauth_publickey_fromfile(session, user, pub, priv,p);
if (err != LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED) break;
}
}
if (err != 0)
{
fprintf(stderr, "Authentication using key %s failed!\n", priv);
}
为了完整起见,该get_passphrase
函数使用此问题的解决方案来提示用户输入密码。