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

pet*_*y m 6 .net c# ssh ssh.net private-key

仅尝试使用当前的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();
} 
Run Code Online (Sandbox Code Playgroud)

现在,如果我PasswordAuthenticationMethodAuthenticationMethod[]阵列中删除,则会因找不到合适的身份验证方法而获得异常。如果我尝试这样传递(主机名,端口,用户名,密钥文件2)

var keyFile = new PrivateKeyFile(privateKeyLocation);
var keyFile2 = new[] {keyFile};
Run Code Online (Sandbox Code Playgroud)

再次,找不到合适的方法。

似乎我必须使用ConnectionInfo上面概述的对象,但是它似乎评估了PasswordAuthenticationMethod并且无法登录(因为我没有提供密码)并且从不评估PrivateKeyAuthMethod...是这种情况吗?是否有其他方法可以使用SSH.NET库仅使用用户名或主机名以及私钥进行身份验证?

sci*_*ino 6

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

new PasswordAuthenticationMethod(username, ""), 
Run Code Online (Sandbox Code Playgroud)

这对我来说非常合适:

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());
Run Code Online (Sandbox Code Playgroud)