【发布时间】:2021-12-01 19:28:23
【问题描述】:
我正在尝试使用SSH.NET 通过 SFTP 从服务器读取/下载文件。连接工作;我可以枚举感兴趣的目录;但是当我尝试读取文件内容时,出现消息“权限被拒绝”的异常。 (下面的堆栈跟踪;我没有看到任何其他有用的东西——没有内部异常。)
这可能是问题:当我 ssh 进入服务器(使用相同的密钥)时,我必须执行 sudo vim 来查看文件内容,否则它也会给我“没有权限”。请注意,它不会让我输入密码来使用sudo。我只是不确定这如何通知我的代码更改。
using Renci.SshNet;
using System;
using System.IO;
using System.Text;
...
try {
ConnectionInfo connectionInfo;
using (var keyStream = new MemoryStream(Encoding.UTF8.GetBytes(GetSshKey())))
{
connectionInfo = new ConnectionInfo(Domain, Username,
new PrivateKeyAuthenticationMethod(Username, new PrivateKeyFile(keyStream)));
}
// Connect to the server with SFTP
using var client = new SftpClient(connectionInfo);
client.Connect();
if (!client.Exists(RemoteFolder))
{
throw new Exception("The backup folder was not found!");
}
// Save block blobs to local files
foreach (var file in client.ListDirectory(RemoteFolder))
{
if (!file.IsRegularFile) continue; // Skip any directories or links
var readStream = client.OpenRead(file.FullName); // Exception thrown HERE!
var writeStream = File.OpenWrite($"C:\\temp\\{file.Name}");
readStream.CopyTo(writeStream);
writeStream.Dispose();
readStream.Dispose();
}
} catch (Exception e)
{
throw e;
}
堆栈跟踪:
at Renci.SshNet.Sftp.SftpSession.RequestOpen(String path, Flags flags, Boolean nullOnError)
at Renci.SshNet.Sftp.SftpFileStream..ctor(ISftpSession session, String path, FileMode mode, FileAccess access, Int32 bufferSize)
at Renci.SshNet.SftpClient.Open(String path, FileMode mode, FileAccess access)
at Renci.SshNet.SftpClient.OpenRead(String path)
at Playground.Program.Main(String[] args) in C:\...\Program.cs:line 40
我尝试了DownloadFile 和BeginDownloadFile 和EndDownloadFile,但在这些情况下DownloadFile 和EndDownloadFile 分别抛出一个类似的“权限被拒绝”错误。堆栈跟踪:
at Renci.SshNet.Common.AsyncResult.EndInvoke()
at Renci.SshNet.Common.AsyncResult`1.EndInvoke()
at Renci.SshNet.Sftp.SftpSession.EndOpen(SftpOpenAsyncResult asyncResult)
at Renci.SshNet.ServiceFactory.CreateSftpFileReader(String fileName, ISftpSession sftpSession, UInt32 bufferSize)
at Renci.SshNet.SftpClient.InternalDownloadFile(String path, Stream output, SftpDownloadAsyncResult asyncResult, Action`1 downloadCallback)
at Renci.SshNet.SftpClient.DownloadFile(String path, Stream output, Action`1 downloadCallback)
at Playground.Program.Main(String[] args) in C:\...\Program.cs:line 41
【问题讨论】: