2013-10-03 98 views
0

我有下面的代碼適用於FTP。我如何讓它爲SFTP從FTP轉換爲SFTP

((ChannelExec) channel).setCommand(cmd); 
channel.setXForwarding(true); 
channel.setInputStream(System.in); 
InputStream in=channel.getInputStream(); 
channel.connect(); 
return in; 

我知道我需要使用,而不是Channel類ChannelSftp工作,但我得到的set命令行類型轉換錯誤。 無法將類型ChannelSftp轉換爲ChannelExec

+0

可能的重複http://stackoverflow.com/questions/14617/java-what-is-the-best-way-to-sftp-a-file-from-a-server – mabbas

+0

該命令是什麼?它是一個您嘗試使用SFTP的FTP命令嗎? (對不起,不知道那個lib) –

+0

cmd會作爲參數傳遞。這可能是「頂部」,例如 – MansoorShaikh

回答

1

首先要了解的是SFTP不同於FTP或FTP/s。 SFTP使用SSH而FTP/s使用SSL。這就是說,JSCH提供了一個非常簡單的方式來使用SFTP,包括設置X轉發。看看examples以及來自mabbas的linked question

基於您的評論,看來你真的想要一個遠程shell被調用/反對,請嘗試以下,看它是否會做你所需要的執行:

//connect to the remote shell 
Channel channel=session.openChannel("shell"); 
((ChannelShell)channel).setAgentForwarding(true); 
channel.setInputStream(System.in); //Send commands here 
channel.setOutputStream(System.out); //output responses here  
channel.connect(); 

你不會能夠使用ChannelSftp,因爲它沒有一個setCommandexec方法

+0

此代碼和我發佈的代碼有什麼區別。 – MansoorShaikh

+0

請參閱編輯 - 今天早上沒有足夠的咖啡因:-) –

0

如果您使用JSCH,他們有several example programs這說明如何使用圖書館。 The SFTP client example說明如何打開SFTP會話。

Session session=jsch.getSession(user, host, port); 
... 
session.connect(); 

Channel channel=session.openChannel("sftp"); 
channel.connect(); 
ChannelSftp c=(ChannelSftp)channel; 

這就是你所要做的。 ChannelSftp包含發送和接收文件,獲取文件列表等功能。您不必訪問頻道的輸入或輸出流。