1

我正在使用 SSH.NET 将 SFTP 文件从一台服务器传输到另一台服务器。我正在使用 C# .NET 4.5 MVC 4。它工作得很好,除非有多个请求尝试上传文件,此时我收到一个错误,即 SSH 私钥当前正在被另一个进程使用。我假设一个请求设置了从私钥文件读取的 ConnectionInfo 对象,而另一个请求在第一个请求完成从该文件读取之前尝试做同样的事情。

有什么帮助吗?

请注意,在下面的代码中,我已将“test”添加到所有字符串 obj 值。在生产中,情况并非如此。

谢谢!

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();
    }
  }
}
4

1 回答 1

0

简而言之:您的假设是正确的。问题在于锁定和访问共享资源。

new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)

您可以继续lock使用共享资源以最少的代码更改来解决此问题。一个潜在的起点是 SftpService()

继续在父类上创建锁,并用锁包装共享资源的内容:

 private static object _lock = new object();


 public SftpService()
    {

     lock (_lock)
                {
                   // shared resources
                }
    }
于 2016-05-05T18:23:32.727 回答