SSH.NET仅通过私钥进行身份验证(公钥身份验证)

18

尝试仅使用当前SSH.NET库通过用户名和私钥进行身份验证。我无法从用户获取密码,因此这是行不通的。

这是我现在正在做的事情。

Renci.SshNet.ConnectionInfo conn = 
    new ConnectionInfo(hostName, port, username, new AuthenticationMethod[]
        {
            new PasswordAuthenticationMethod(username, ""), 
            new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile[] 
                   { new PrivateKeyFile(privateKeyLocation, "") }),
        });

using (var sshClient = new SshClient(conn))
{
    sshClient.Connect();
} 
现在,如果我从AuthenticationMethod[]数组中删除PasswordAuthenticationMethod,我会得到一个异常,说明没有找到合适的身份验证方法。如果我尝试以以下方式传递(主机名、端口、用户名、keyfile2),则会出现异常。
var keyFile = new PrivateKeyFile(privateKeyLocation);
var keyFile2 = new[] {keyFile};

再次出现了,没有找到合适的方法。

看起来我必须按照上面所述使用ConnectionInfo对象,但它似乎会评估PasswordAuthenticationMethod并且无法登录(因为我没有提供密码),而且从未评估过PrivateKeyAuthMethod...这是真的吗?是否有其他方法可以使用SSH.NET库仅使用用户名或主机名和私钥进行身份验证?


4
您间接地帮助了我,展示了如何将密码和私钥认证结合起来,以供那些需要双重验证的非常安全的服务器使用。 - Timo
3个回答

19
您的问题在于仍在使用密码,即使它为空。请删除此行:

Your problem here is that you're still using a password, even though it is blank. Remove this line:

new PasswordAuthenticationMethod(username, ""), 

这对我来说完美地运作:

var pk = new PrivateKeyFile(yourkey);
var keyFiles = new[] { pk };

var methods = new List<AuthenticationMethod>();
methods.Add(new PrivateKeyAuthenticationMethod(UserName, keyFiles));

var con = new ConnectionInfo(HostName, Port, UserName, methods.ToArray());

0
你需要像这样的东西,对我来说它很好用。 在创建新的ConnectionInfo对象时,请注意我只传递了主机、端口、用户和认证方法(不需要密码); 第二个区别是我传递了单个PrivateKeyFile,而没有为“Phrase”参数留空引号;
public ConnectionInfo GetCertificateBasedConnection()
    {
        ConnectionInfo connection;
        Debug.WriteLine("Trying to create certification based connection...");
        using (var stream = new FileStream(ConfigurationHelper.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
        {
            var file = new PrivateKeyFile(stream);
            var authMethod = new PrivateKeyAuthenticationMethod(ConfigurationHelper.User, file);

            connection = new ConnectionInfo(ConfigurationHelper.HostName, ConfigurationHelper.Port, ConfigurationHelper.User, authMethod);
        }
        Debug.WriteLine("Certification based connection created successfully");
        return connection;
    }

-5

为了执行私钥身份验证,您还需要口令,这与私钥一起将允许进行身份验证。
真正需要的是RenciSSH跟上时代,编写一个publickeyauthentication方法。


1
似乎公钥认证使用了私钥和公钥。这里有更详细的解释:https://stackoverflow.com/a/53406885/3103633 - Window

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接