经过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);
}
为了完整起见,函数使用溶液来this question提示输入密码短语用户。