2012-07-31 90 views
0

我有要求從一臺遠程服務器下載大文件(20GB +)到另一臺C#遠程服務器。我們已經爲其他文件操作建立了ssh連接。我們需要以二進制模式從ssh會話啓動ftp下載(這是遠程服務器要求以特定格式傳送文件)。問題 - 如何在ssh會話中發送ftp命令來建立與證書的連接並將模式設置爲'bin'?基本上相當於以下使用ssh的:C# - 使用ftp通過ssh從一臺遠程服務器下載文件到另一臺

FtpWebRequest request =(FtpWebRequest)WebRequest.Create(
     @"ftp://xxx.xxx.xxx.xxx/someDirectory/someFile"); 

request.Credentials = new NetworkCredential("username", "password"); 
request.UseBinary = true; 
request.Method = WebRequestMethods.Ftp.DownloadFile; 

FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 

回答

1

SSH是一個「安全殼」這就好比一個命令提示符中,你給它的命令來運行。它不是FTP。 SSH可以執行FTP實用程序或應用程序。

SSH確實有一些稱爲SFTP(或SSH文件傳輸協議)的東西,但是沒有內置於.NET(即BCL)的內容來做到這一點。 FtpWebRequest不支持SFTP。

儘管共享「FTP」,它們是不同的協議,並且彼此不兼容。

如果您想啓動FTP下載,您必須告訴SSH執行某種實用程序。如果您想啓動SFTP傳輸,則可以發出sftp命令。但是,另一端需要支持sftp。或者,您可以發出scp命令(安全副本);但另一方面,另一端將需要支持該協議(它與SFTP和FTP不同)...

如果你想寫另一端,你必須找到一個第三方庫,它執行SFTP或SCP ...

+0

感謝您的回覆。正如我所提到的,我們已經在使用SSH執行很多文件操作了(從c#服務連接到我們的unix框)。僅當我們使用特定憑證進行ftp連接時,纔會以所需格式傳送來自遠程服務器的文件。它不支持sftp。最有可能的是,我打算執行批處理文件以使用ftp從ssh命令下載文件(ssh連接從web服務啓動)。 – user1408552 2012-08-01 12:13:47

0

我最喜歡的庫,以實現你所需要的是從奇爾卡特軟件Chilkat (免責聲明:我只是一個付費用戶沒有隸屬於公司)。

Chilkat.SFtp sftp = new Chilkat.SFtp(); 

// Any string automatically begins a fully-functional 30-day trial. 
bool success; 
success = sftp.UnlockComponent("Anything for 30-day trial"); 
if (success != true) { 
    MessageBox.Show(sftp.LastErrorText); 
    return; 
} 

// Set some timeouts, in milliseconds: 
sftp.ConnectTimeoutMs = 5000; 
sftp.IdleTimeoutMs = 10000; 

// Connect to the SSH server. 
// The standard SSH port = 22 
// The hostname may be a hostname or IP address. 
int port; 
string hostname; 
hostname = "www.my-ssh-server.com"; 
port = 22; 
success = sftp.Connect(hostname,port); 
if (success != true) { 
    MessageBox.Show(sftp.LastErrorText); 
    return; 
} 

// Authenticate with the SSH server. Chilkat SFTP supports 
// both password-based authenication as well as public-key 
// authentication. This example uses password authenication. 
success = sftp.AuthenticatePw("myLogin","myPassword"); 
if (success != true) { 
    MessageBox.Show(sftp.LastErrorText); 
    return; 
} 

// After authenticating, the SFTP subsystem must be initialized: 
success = sftp.InitializeSftp(); 
if (success != true) { 
    MessageBox.Show(sftp.LastErrorText); 
    return; 
} 

// Open a file on the server: 
string handle; 
handle = sftp.OpenFile("hamlet.xml","readOnly","openExisting"); 
if (handle == null) { 
    MessageBox.Show(sftp.LastErrorText); 
    return; 
} 

// Download the file: 
success = sftp.DownloadFile(handle,"c:/temp/hamlet.xml"); 
if (success != true) { 
    MessageBox.Show(sftp.LastErrorText); 
    return; 
} 

// Close the file. 
success = sftp.CloseHandle(handle); 
if (success != true) { 
    MessageBox.Show(sftp.LastErrorText); 
    return; 
} 
相關問題