我使用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();
}
}
}
答案 0 :(得分:0)
简而言之:您的假设是正确的。问题在于锁定和访问共享资源。
new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)
您可以继续lock
共享资源,以最少的代码更改来解决此问题。潜在的起点是SftpService()
。
继续并在父类上创建锁,并使用锁包装共享资源的内容:
private static object _lock = new object();
public SftpService()
{
lock (_lock)
{
// shared resources
}
}