Java利用ganymed-ssh2通路遠端伺服器上檔案的屬性
此方法可以擷取遠端伺服器上某個檔案夾裡面的檔案及其屬性
首先導入ganymed-ssh2的依賴
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
下面是一個測試類
@Test
public void getRemoteFiles() {
String path = "/home/webs/www/patch";
String hostName = "192.168.1.48";
int port = 22;
String username = "此處是伺服器的使用者名";
String password = "此處是服務的登入密碼";
Connection ss = getConnect(hostName, username, password, port);
getFileProperties(ss, path);
}
public static Connection getConnect(String hostName, String username, String password, int port) {
Connection conn = new Connection(hostName, port);
try {
// 連接配接到主機
conn.connect();
// 使用使用者名和密碼校驗
boolean isconn = conn.authenticateWithPassword(username, password);
if (!isconn) {
System.out.println("使用者名稱或者是密碼不正确");
} else {
System.out.println("伺服器連接配接成功.");
return conn;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 在遠端LINUX伺服器上,在指定目錄下,擷取檔案各個屬性
*
* @param[in] conn Conncetion對象
* @param[in] remotePath 遠端主機的指定目錄
*/
public Vector<SFTPv3DirectoryEntry> getFileProperties(Connection conn, String remotePath) {
Vector v = null;
try {
SFTPv3Client sft = new SFTPv3Client(conn);
v = sft.ls(remotePath);
for (int i = 0; i < v.size(); i++) {
SFTPv3DirectoryEntry s = new SFTPv3DirectoryEntry();
s = (SFTPv3DirectoryEntry) v.get(i);
//檔案名
String filename = s.filename;
//檔案的大小
Long fileSize = s.attributes.size;
System.out.println(filename + " " + fileSize);
}
sft.close();
} catch (Exception e1) {
e1.printStackTrace();
}
return v;
}
}
此方法已知問題是會讀到兩個不存在的檔案及屬性,如圖

目前沒有查到原因是啥,有知道的大哥吱一聲~