如何解决使用SSH.NET SFTP进行sudo访问文件
我正在尝试使用SSH.NET通过SFTP从服务器读取/下载文件。连接工程;我可以列举感兴趣的目录;但是当我尝试读取文件内容时,出现消息“权限被拒绝”的异常。 (下面的堆栈跟踪;我没有看到其他有用的东西了,没有内部异常。)
这可能是问题:当我with cte as (
select row_number() over(
partition by name,school,graduationyear,degree
order by major
) rn
from mytable
)
delete from cte where rn > 1
(使用相同的密钥)进入服务器时,我必须做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,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
解决方法
您用于通过SSH.NET登录的帐户没有对该文件的读取权限。
SFTP协议中没有与sudo
等效的功能。
尽管要连接到OpenSSH服务器,也可以使用以下命令指示它以提升的特权运行SFTP子系统/服务器:
sudo /bin/sftp-server
但是您不能直接通过SSH.NET执行此操作。但是,通过对其代码进行一些修改,它可能是可行的。毕竟SSH.NET是开源的。
有关更多背景信息,请参见WinSCP常见问题解答How do I change user after login (e.g. su root)?
甚至在开始破解之前,请先在WinSCP GUI中尝试进行操作,以确保可行。
另一种选择是在外壳(sudo
)中使用SshClient.RunCommand
来制作文件的副本,该文件可由您的SFTP帐户访问。但这取决于您的sudo
特权是什么。
或者您也可以尝试使用类似以下代码的WinSCP .NET assembly:
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,HostName = "example.com",UserName = "username",Password = "password",SshHostKeyFingerprint = "...",};
sessionOptions.AddRawSettings("SftpServer","sudo /bin/sftp-server");
using (Session session = new Session())
{
session.Open(sessionOptions);
// Your code
}
(我是WinSCP的作者)
最好的选择是直接使用对文件具有读取特权的帐户登录。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。