2015-06-05 84 views
1

试图通过用户名和私钥仅使用当前的ssh.net库进行身份验证。我无法从用户那里获得密码,所以这是不可能的。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(); 

}

现在,如果i。从AuthenticationMethod[]阵列I得到一个异常用于发现合适的认证方法除去PasswordAuthenticationMethod。如果我试图通过(主机名,端口,用户名,密钥文件2)这样的

var keyFile = new PrivateKeyFile(privateKeyLocation); 
var keyFile2 = new[] {keyFile}; 

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

看来我必须使用ConnectionInfo对象,因为我上面列出,但似乎它评估PasswordAuthenticationMethod和无法登陆(因为我不提供密码),从来没有评估PrivateKeyAuthMethod ...这是案子?有没有其他的方法来验证只有用户名或主机名和私钥使用ssh.net lib?

回答

0

这里你的问题是你仍然在使用密码,即使它是空白的。删除这一行:

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

啊,是的,这对我有效,谢谢! –

0

要执行私钥验证,您还需要密码,它与私钥一起允许验证。
真正需要的是RenciSSH与时俱进并写出一种公认的认证方法。

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; 
    } 
相关问题