简体   繁体   中英

SSH.NET SSH Private Key File Lock issue with Multiple Threads

I am using SSH.NET to SFTP files from one server to another. I'm using C# .NET 4.5 MVC 4. It works great except in the case where there are multiple requests trying to upload files, at which point I get an error that the SSH private key is currently being used by another process. I would assume that one request sets up the ConnectionInfo object which reads from the private key file, while another request is trying to do the same thing before the first request is done reading from that file.

Any help?

Notice in the code below that I've added "test" to all string obj values. In production this is not the case.

Thanks!

public class SftpService : ISftpService
{
  private static ConnectionInfo _sftpConnectionInfo { get; set; }
  private static readonly string _mediaServerHost = "test";
  private static readonly string _mediaServerUsername = "test";
  private static readonly int _mediaServerPort = 22;
  private static readonly string _privateSshKeyLocation = "test";
  private static readonly string _privateSshKeyPhrase = "test";
  private static readonly string _mediaServerUploadRootLocation = "test";

    public SftpService()
    {

        var authenticationMethod =  new PrivateKeyAuthenticationMethod(_mediaServerUsername, new PrivateKeyFile[]{ 
                new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)
        });


    // Setup Credentials and Server Information
    _sftpConnectionInfo = new ConnectionInfo(_mediaServerHost, _mediaServerPort, _mediaServerUsername,
        authenticationMethod
    );  

  }

  public void UploadResource(Stream fileStream)
  {
    using (var sftp = new SftpClient(_sftpConnectionInfo))
    {
        sftp.Connect();

        //this is not the real path, just showing example
        var path = "abc.txt";

        sftp.UploadFile(fileStream, path, true);

        sftp.Disconnect();
    }
  }
}

In short: Your assumptions are correct. Problem is in lock and access to the shared resource.

new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)

You may go ahead and lock the shared resource to resolve this issue with minimal code change. A potential start point would be SftpService() .

Go ahead and create lock on a parent class and wrap content of shared resources with the lock:

 private static object _lock = new object();


 public SftpService()
    {

     lock (_lock)
                {
                   // shared resources
                }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM