首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 通過 SSH2 遠程執行 Linux 命令與腳本

     編輯:Java 相關知識

使用 Ganymed SSH2 庫實現 Java 程序通過 SSH 協議遠程登錄 Linux 服務器,執行命令或腳本並獲取輸出結果。適用於自動化部署、監控採集、遠程運維等場景。

依賴配置

<dependency>
    <groupId>com.ganymed.ssh2</groupId>
    <artifactId>ganymed-ssh2-build</artifactId>
    <version>210</version>
</dependency>

核心 API 流程

  1. 建立連接: Connection conn = new Connection(hostname); conn.connect();
  2. 密碼認證: conn.authenticateWithPassword(username, password)
  3. 開啟會話: Session sess = conn.openSession();
  4. 執行命令: sess.execCommand("ls -la /tmp");
  5. 讀取輸出: 通過 StreamGobbler 處理 stdout/stderr
  6. 獲取退出碼: sess.getExitStatus()(0 成功,非 0 失敗)
  7. 關閉資源: sess.close(); conn.close();

完整工具類示例


public class RemoteExecutor {
    private final Connection conn;

    public RemoteExecutor(String host, String user, String pwd) throws IOException {
        conn = new Connection(host);
        conn.connect();
        if (!conn.authenticateWithPassword(user, pwd)) {
            throw new RuntimeException("認證失敗");
        }
    }

    public String execute(String command) throws IOException {
        try (Session sess = conn.openSession()) {
            sess.execCommand(command);
            try (InputStream stdout = new StreamGobbler(sess.getStdout());
                 BufferedReader br = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append('\n');
                }
                int exitCode = sess.getExitStatus();
                if (exitCode != 0) {
                    // 可選:讀取 stderr 並拋出異常
                }
                return sb.toString();
            }
        }
    }

    public void close() {
        conn.close();
    }
}

關鍵注意事項

  • 編碼處理: 顯式指定 StandardCharsets.UTF_8 讀取流,避免中文亂碼
  • 工作目錄: 登錄後默認在 /home/user/,腳本路徑需用絕對路徑或先 cd
  • 多命令依賴: 需在同一 Session 內用 cmd1 && cmd2 或腳本文件串聯,多 Session 間環境不共享
  • 超時設置: conn.connect(new SocketTimeout(30000)) 防止掛死
  • 金鑰認證: 生產環境建議使用 authenticateWithPublicKey() 替代密碼

Maven 完整依賴


<dependencies>
    <dependency>
        <groupId>com.ganymed.ssh2</groupId>
        <artifactId>ganymed-ssh2-build</artifactId>
        <version>210</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>
</dependencies>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved