将SshClient转换为SftpClient

时间:2018-03-30 18:27:28

标签: c# ssh

我正在使用Renci.SshNet在我的ubuntu服务器上安全地发送文件和执行命令。

无论如何,我经常需要发送文件并执行命令。所以我现在正在做的是:

TCHAR szModName[MAX_PATH];
if (!GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) // Get the full path to the module's file
    continue;

wstring modName = szModName; <-------- this is what im having problem with

我的问题是我可以从SshClient转换为SftpClient,这样我就不必创建2个连接吗?如果我可以做这样的事情会很棒:

using (Renci.SshNet.SshClient client1 = new Renci.SshNet.SshClient("someDomain.com", 22, "root", new PrivateKeyFile(@"C:\Path\To\PrivateKey\id_rsa")))
{
    // connect
    client1.Connect();

    // execute a command
    var c = client1.RunCommand("echo 'hello world' > /root/test.txt");

    // create a second connection in order to download a file 
    SftpClient client_2 = new SftpClient(client1.ConnectionInfo);
    client_2.Connect();

    using (FileStream fs = new FileStream("output.txt", FileMode.OpenOrCreate))
             client_2.DownloadFile("/root/test.txt", fs);
}

或另一种解决方案是以base64格式传递文件。如果我做这样的事情来下载文件会被认为是不好的做法吗?

 SftpClient client_2 = (SftpClient)client1;

使用相同的术语上传文件:

 var fileConentInBase64 = client1.RunCommand("cat'/root/someFile' | base64");

1 个答案:

答案 0 :(得分:1)

根据我对C#中演员的了解,当你使用对象时,这些类必须有一个共同的继承。 The C# documentation will be clearer than me

因此,如果SftpClient继承自BaseClient,您可以通过某种方式继续。 正如您帖子的评论中所说,实际上不可能这样做出于这个原因 对不起,我把文档快点了。

也许我错过了一些东西,但是你不能用SSH做任何事情? From what I'm reading here it is possible to "upload" and "download" a file with SSH

相关问题