c#連線SFTP上傳檔案

ap0581w9c發表於2016-04-15

名詞解釋(百度百科)

sftp是Secure File Transfer Protocol的縮寫,安全檔案傳送協議。可以為傳輸檔案提供一種安全的加密方法。sftp 與 ftp 有著幾乎一樣的語法和功能。SFTP 為 SSH的一部份,是一種傳輸檔案至 Blogger 伺服器的安全方式。其實在SSH軟體包中,已經包含了一個叫作SFTP(Secure File Transfer Protocol)的安全檔案傳輸子系統,SFTP本身沒有單獨的守護程式,它必須使用sshd守護程式(號預設是22)來完成相應的連線操作,所以從某種意義上來說,SFTP並不像一個伺服器程式,而更像是一個客戶端程式。SFTP同樣是使用加密傳輸認證資訊和傳輸的資料,所以,使用SFTP是非常安全的。但是,由於這種傳輸方式使用了加密/解密技術,所以傳輸效率比普通的FTP要低得多,如果您對網路安全性要求更高時,可以使用SFTP代替FTP。

程式碼實現:

1.新增引用 Renci.SshNet(通過Nuget下載)

https://www.nuget.org/packages/SSH.NET/2013.4.7

2.核心程式碼

const int port = 22; //
const string host = " "; //sftp地址
const string username = " "; //使用者名稱
const string password = " ";//密碼
const string workingdirectory = "/";//讀取、上傳檔案的目錄 "/"為根目錄
const string uploadfile = @"c:\1.xml"; //上傳檔案地址

 
using (var client = new SftpClient(host, port, username, password)) //建立連線物件
{
client.Connect(); //連線
 

client.ChangeDirectory(workingdirectory); //切換目錄
 

var listDirectory = client.ListDirectory(workingdirectory); //獲取目錄下所有檔案
 
foreach (var fi in listDirectory) //遍歷檔案
{
Console.WriteLine(" - " + fi.Name);
// client.DeleteFile(fi.FullName);//刪除檔案
}

using (var fileStream = new FileStream(uploadfile, FileMode.Open))
{
client.BufferSize = 4 * 1024; // bypass Payload error large
client.UploadFile(fileStream, Path.GetFileName(uploadfile)); //上傳檔案
//UploadFile方法沒有返回值,無法判斷檔案是否上傳成功,我想到的解決辦法是,上傳後再獲取一下檔案列表,如果檔案列表count比上傳之前大,說明上傳成功。當然
//這樣的前提是隻有你一個人上傳。不知各位大神有沒有其它辦法
}
Console.ReadKey();

 

 完整示例:

/*
    get SSH.NET (BSD License: http://sshnet.codeplex.com/license)
    
    with NuGet:
    >Install-Package SSH.NET -Version 2013.4.7
    
    or just get the dll from here: http://j.mp/sshNet
    
*/
using System;
using System.Collections.Generic;
using Renci.SshNet; /* reference needed: Renci.SshNet.dll */

class Program
{
    static void Main(string[] args){

        // Setup Credentials and Server Information
        ConnectionInfo ConnNfo = new ConnectionInfo("hostOrIP",22,"username",
            new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("username","password"),

                // Key Based Authentication (using keys in OpenSSH Format)
                new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{ 
                    new PrivateKeyFile(@"..\openssh.key","passphrase")
                }),
            }
        );

        // Execute a (SHELL) Command - prepare upload directory
        using (var sshclient = new SshClient(ConnNfo)){
            sshclient.Connect();
            using(var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest")){
                cmd.Execute();
                Console.WriteLine("Command>" + cmd.CommandText);
                Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
            }            
            sshclient.Disconnect();
        }

        // Upload A File
        using (var sftp = new SftpClient(ConnNfo)){
            string uploadfn = "Renci.SshNet.dll";

            sftp.Connect();
            sftp.ChangeDirectory("/tmp/uploadtest");
            using (var uplfileStream = System.IO.File.OpenRead(uploadfn)){
                sftp.UploadFile(uplfileStream, uploadfn, true);
            }
            sftp.Disconnect();
        }

        // Execute (SHELL) Commands
        using (var sshclient = new SshClient(ConnNfo)){
            sshclient.Connect();

            // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
            Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
            Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
            Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
            sshclient.Disconnect();
        }
        Console.ReadKey();
    }
}

 

相關文章