PuTTY in C# for file transfer

偶尔善良 提交于 2019-12-08 11:52:01

问题


Can any one help me with a code snippet in C# for transferring a file on my local machine to a remote server using PSCP (PuTTY) transfer methodology? I would really appreciate the help. Thanks


回答1:


You can use a library that support SCP like SSHNet or WinSCP. Both provide samples and tests that demonstrate how they work.

With SSH.Net you can upload a file using this code (from the test files):

using (var scp = new ScpClient(host, username, password))
{
    scp.Connect();
    scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
    scp.Disconnect();

}

With the WinSCP library the code looks like this (from the samples):

SessionOptions sessionOptions = new SessionOptions {
            Protocol = Protocol.Sftp,
            HostName = "example.com",
            UserName = "user",
            Password = "mypassword",
            SshHostKey = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload files
    TransferOptions transferOptions = new TransferOptions();
    transferOptions.TransferMode = TransferMode.Binary;

    TransferOperationResult transferResult;
    transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);

    // Throw on any error
    transferResult.Check();

}



回答2:


Using SFTP and SCP supported clients with .NET Libraries might be the best option. But here is a simple way to use PSCP:

Process cmd = new Process();
cmd.StartInfo.FileName = @"C:\PuTTY\pscp.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
string argument = @"-pw pass C:\testfile.txt user@10.10.10.10:/home/usr";
cmd.StartInfo.Arguments = argument;

cmd.Start();
cmd.StandardInput.WriteLine("exit");
string output = cmd.StandardOutput.ReadToEnd();


来源:https://stackoverflow.com/questions/11472633/putty-in-c-sharp-for-file-transfer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!