2016-02-12 46 views
0

我試圖列出從遠程服務器使用JSCH的所有文件/目錄,並在遠程服務器上的文件,我可以能夠得到的所有信息以及..列表使用Jsch

但我的問題是JSCH列表所有的文件與文件創建日期,時間戳,類型的讀/寫權限等..,

但在我的情況下,我只需要遠程服務器中的文件/目錄名稱,並且不需要其他信息的。

以下是我的一段java代碼..

上述程序的

結果是

-rw-r--r-- 1 root  root   3161 Feb 11 2014 install.log.syslog 
-rw-r--r-- 1 root  root   18 May 20 2009 .bash_logout 
-rw-r--r-- 1 root  root   176 Sep 23 2004 .bashrc 
-rw-r--r-- 1 root  root   176 May 20 2009 .bash_profile 
-rw-r--r-- 1 root  root   129 Dec 3 2004 .tcshrc 
-rw------- 1 root  root   1114 Feb 11 2014 anaconda-ks.cfg 
dr-xr-x--- 2 root  root   4096 Feb 11 2014 . 
-rw-r--r-- 1 root  root   9169 Feb 11 2014 install.log 
-rw------- 1 root  root   1055 Feb 11 2014 .bash_history 
-rw-r--r-- 1 root  root   100 Sep 23 2004 .cshrc 
dr-xr-xr-x 24 root  root   4096 Feb 12 04:19 .. 

回答

-1

嘗試給exec ls命令:

Channel channel=session.openChannel("exec"); 
    ((ChannelExec)channel).setCommand("cd " + SFTPWORKINGDIR + " && ls"); 
    channel.connect(); 
    channel.run(); 

Vector filelist = channel.run(); 
for(int i=0; i<filelist.size();i++){ 
    System.out.println(filelist.get(i).toString()); 
} 
+1

@CodelsLife:它運作良好! –

+0

第5行返回一個錯誤,指出channel.run()返回void。 –

+0

是它的錯誤在第5行。@CodelsLife你可以更新答案 –

6

嘗試運行該代碼。在這裏,我們將列表元素類型轉換爲LsEntry,然後打印所需的屬性。

import java.util.Vector; 

import com.jcraft.jsch.Channel; 
import com.jcraft.jsch.ChannelSftp; 
import com.jcraft.jsch.ChannelSftp.LsEntry; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.Session; 


public class Listremoteserver { 


    /** 
    * @param args 
    */ 
    @SuppressWarnings("unchecked") 
    public static void main(String[] args) { 
     String SFTPHOST = "xxxxx"; 
     int SFTPPORT = 22; 
     String SFTPUSER = "xxx"; 
     String SFTPPASS = "xxxxx"; 
     String SFTPWORKINGDIR = "/root"; 

     Session  session  = null; 
     Channel  channel  = null; 
     ChannelSftp channelSftp = null; 

     try{ 
      JSch jsch = new JSch(); 
      session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT); 
      session.setPassword(SFTPPASS); 
      java.util.Properties config = new java.util.Properties(); 
      config.put("StrictHostKeyChecking", "no"); 
      session.setConfig(config); 
      session.connect(); 
      channel = session.openChannel("sftp"); 
      channel.connect(); 
      channelSftp = (ChannelSftp)channel; 
      channelSftp.cd(SFTPWORKINGDIR); 
      Vector filelist = channelSftp.ls(SFTPWORKINGDIR); 
      for(int i=0; i<filelist.size();i++){ 
       LsEntry entry = (LsEntry) filelist.get(i); 
       System.out.println(entry.getFilename()); 
      } 

     }catch(Exception ex){ 
      ex.printStackTrace(); 
     } 
    } 
} 
+0

感謝您的快速回復..它解決了我的問題... –