專案需要實現資源管理功能,除 FastDFS 存儲單檔外,特定資源仍需暫存於應用伺服器。考慮到 FTP 權限管理繁雜(尤其 Linux 環境刪除文件權限問題),團隊決定採用 SFTP 協議。本文基於 JSch(純 Java 實現 SSH2)封裝完整工具類,支援檔案上傳下載、目錄操作、遠端命令執行、壓縮解壓、磁碟/CPU 監控等實用功能。
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
官網範例:Shell.java
實作 UserInfo 與 UIKeyboardInteractive 介面,處理密碼、密鑰、Yes/No 確認等交互邏輯。
單例模式管理 Session 與 ChannelSftp,提供 connect()/disconnect() 統一入口,支援連線超時設定。
sftp.put(local, remote, monitor, ChannelSftp.OVERWRITE) 支援進度監聽與覆蓋模式sftp.get(remote, local, monitor, ChannelSftp.OVERWRITE)sftp.rm() / execCommand("rm -rf " + dir)sftp.ls(path) 過濾 . .. 返回檔名列表sftp.mkdir(path)// 執行任意 Shell 命令
public String execCommand(String command, boolean waitForResult) {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("export TERM=ansi && " + command);
// ... 讀取輸入流 ...
}
// 獲取 CPU 資訊
public String[] getCpuInfo() { /* top -bn 1 解析 */ }
// 獲取磁碟資訊
public String getHardDiskInfo() { /* df -lh 解析 */ }
// 獲取剩餘空間(位元組)
public double getFreeDisk() { /* 單位換算 KB/MB/GB/TB/PB */ }
// 遠端壓縮目錄
public void compressDir(String directory, String zipName) {
execCommand("cd " + directory + " && zip -r " + zipName + " .");
}
// 解壓(中文檔名編碼注意)
// unzip -O cp936 test.zip -d /target/path
public class Ssh {
private String host, user, password;
private int port = 22;
private Session session;
private ChannelSftp sftp;
// 連線/斷線
public void connect() throws JSchException { ... }
public void disconnect() { ... }
// 檔案操作
public boolean upload(String local, String remote) { ... }
public boolean download(String local, String remote) { ... }
public boolean deleteFile(String dir, String file) { ... }
public String deleteDir(String dir, boolean sure) { ... }
public List<String> listFiles(String directory) { ... }
public boolean mkdir(String path) { ... }
// 遠端命令與監控
public String execCommand(String cmd, boolean wait) { ... }
public String[] getCpuInfo() { ... }
public String getHardDiskInfo() { ... }
public double getFreeDisk() { ... }
public void compressDir(String dir, String zipName) { ... }
}
public static void main(String[] args) throws Exception {
Ssh ssh = new Ssh("10.10.10.83", 22, "test", "test");
ssh.connect();
// 上傳測試
ssh.upload("d:/test.zip", "webapp/test.zip");
// 列出目錄
ssh.listFiles("webapp").forEach(System.out::println);
// 系統監控
System.out.println("CPU: " + Arrays.toString(ssh.getCpuInfo()));
System.out.println("Disk: " + ssh.getHardDiskInfo());
System.out.println("Free: " + ssh.getFreeDisk() + " bytes");
ssh.disconnect();
}
unzip -O cp936 指定編碼finally 區塊務必關閉 Channel 與 Sessionsession.setConfig("compression.s2c", "zlib@openssh.com")JSch 作為成熟的 Java SSH2 實現,配合 SFTP 協議,能優雅解決跨平台檔案傳輸與遠端運維需求,是替代傳統 FTP 的不二之選。