window中使用PSFTP/WinSCP實現SFTP上傳下載


摘自百度百科
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.WinSCP部分

 1.1 cmd命令行實例

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
 
C:\Documents and Settings\sobne>d:
 
D:\>cd winscp437
 
D:\winscp437>WinSCP
winscp> open ftp://username:userpassword@serverip or hostname
Connecting to 172.0.0.1 ...
Connected with 172.0.0.1. Waiting for welcome message...
Connected
Starting the session...
Reading remote directory...
Session started.
Active session: [1] username@172.0.0.1
winscp> put d:\psftp.exe WinSCP/psftp.exe
d:\psftp.exe              |        320 KiB |  608.0 KiB/s | binary | 100%
 
winscp> get 20120420020049.txt
20120420020049.tx |          0 KiB |    0.0 KiB/s | ascii  | 100%
winscp> get 20120420020049.txt c:\t2.txt
20120420020049.tx |          0 KiB |    0.0 KiB/s | ascii  | 100%

winscp> 

 1.2 Batch批處理實例

 將下面語句存入1.txt:

option batch  on
option confirm  off
# Connect using a password
# open 用戶名 :密碼@主機
# Connect
open 用戶名 :密碼@主機
cd /home/user
option transfer binary
get /root/test.c d:/
put d:/test.txt
close
exit
 

 執行腳本

 winscp.exe /console /script=1.txt

 1.3 C#程序實現

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace SFTP
{
     public  class WinSCPtest
    {
         public  string shellName {  get {  return  " D:\\winscp437\\WinSCP.com "; } }
         public  string userName {  get {  return  " username "; } }
         public  string userPassWord {  get {  return  " userpassword "; } }
         public  string serverAddress {  get {  return  " 172.0.0.1 "; } }
         public  string portNumber {  get {  return  " 21 "; } }
         public  string fromFile {  get {  return  " D:\\psftp.txt "; } }
         public  string toFile {  get {  return  " WinSCP/psftp.txt "; } }
         public  void upload()
        {
            Process CommandLine =  new Process();
            CommandLine.StartInfo.FileName = shellName;
             //  CommandLine.StartInfo.Arguments = "/log=" + this._logPath;
            CommandLine.StartInfo.UseShellExecute =  false;
            CommandLine.StartInfo.RedirectStandardInput =  true;
            CommandLine.StartInfo.RedirectStandardOutput =  true;
            CommandLine.StartInfo.CreateNoWindow =  true;
            CommandLine.Start();
             // username用戶名  targetAddress IP地址  portNumber 端口號
            CommandLine.StandardInput.WriteLine( " open ftp://{0}:{1}@{2}:{3} ",
             this.userName, this.userPassWord,  this.serverAddress,  this.portNumber);
            
             // 上傳文件到sftp服務器
             string command =  " put  " + fromFile +  "   " + toFile ;
             // fromFile要傳送的文件路徑本地的絕對路徑    toFile服務器上保存文件的路徑相對路徑
            CommandLine.StandardOutput.DiscardBufferedData();
            CommandLine.StandardInput.WriteLine(command);
             string result = CommandLine.StandardOutput.ReadLine();
        }
    }
}

 

 1.4 在線資源

http://winscp.net/eng/docs/commandline

 

 

 

 2.SFTP部分

 2.1 cmd命令行實例

C:\Documents and Settings\sobne>e:

E:\>cd SFTP
E:\SFTP>psftp.exe username@172.0.0.1 -i privatekey.ppk
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 0a:**:**:**:54:**:82:**:**:1f:**:**:**:87:30:**
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n) n
Using username "sobne".
Remote working directory is /
psftp>

 2.2 Batch批處理實例

 將下面語句存入myscript.scr:

cd /
put File1.txt
put File2.txt
put File3.txt
close

 執行腳本

  c:\putty\psftp.exe feedusr1@fis-depot.ucdavis.edu -i putty_id_rsa_1024.ppk -b c:\putty\myscript.scr -bc -be -v

 2.3 C#程序實現

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace Lib4Net
{

     public  class PSFTPunity
    {
         public  string shellCommand {  getset; }

         public  string serverName {  getset; }
         public  string userName {  getset; }
         public  string privateKey {  getset; }

         public PSFTPunity() 
        { 
            
        }
         public PSFTPunity( string shell,  string server,  string user,  string ppk)
        {
            shellCommand = shell;
            serverName = server;
            userName = user;
            privateKey = ppk;
        }
         ///   <summary>
        
///  Upload the files
        
///   </summary>
        
///   <param name="localFile"> localfile fullname </param>
        
///   <param name="remotePath"> remotefile fullname </param>
        
///   <returns> output of the plugin during its running in console </returns>
         public  string Upload( string localFile,  string remotePath)
        {
             string outPutMessage =  "";

            ProcessStartInfo processInfo =  new ProcessStartInfo();
            processInfo.FileName =  this.shellCommand;
            processInfo.CreateNoWindow =  true;
            processInfo.UseShellExecute =  false;
            processInfo.RedirectStandardError =  true;
            processInfo.RedirectStandardInput =  true;
            processInfo.RedirectStandardOutput =  true;
             string arguments =  "";
            arguments += userName +  " @ " + serverName +  "   ";
            arguments +=  " -i  " + privateKey;
            processInfo.Arguments = arguments;

            Process process =  new Process();
             try
            {
                process.StartInfo = processInfo;
                process.Start();
                Thread.Sleep( 5000);
                process.StandardInput.WriteLine( " n ");
                Thread.Sleep( 2000);
                 // process.StandardInput.WriteLine("cd " + remotePath);
                process.StandardInput.WriteLine( " put  " + localFile +  "   " + remotePath);
                 // process.StandardInput.Close();
                Thread.Sleep( 10000);
                 // outPutMessage += process.StandardOutput.ReadToEnd();
                
// outPutMessage += process.StandardError.ReadToEnd();
                process.WaitForExit( 3000);
                process.Close();
                 return outPutMessage;
            }
             catch (Exception ex)
            {
                 throw  new Exception( " Error occured during upload file to remote server! ", ex);
            }
             finally
            {
                process.Dispose();
            }
        } 
    }
}

 

 

 2.4 在線資源

 

 

 

 

文中使用的軟件下載地址:http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM