Java 使用 SSHJ 执行 SSH 命令和 SFTP 文件上传和下载
✅ 推荐:使用 sshj(客户端连接 SSH)
适合:远程登录服务器、执行命令、上传/下载文件等。
❌ 不推荐:使用 jsch(客户端连接 SSH)
不支持 ssh 新版本算法。
🔧 Maven 依赖
<dependency><groupId>com.hierynomus</groupId><artifactId>sshj</artifactId><version>0.40.0</version> <!-- 建议使用最新版本 -->
</dependency>
✅ Java 示例:执行命令
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;public class SshjExecExample {public static void main(String[] args) {String host = "your.server.ip";String user = "root";String password = "your_password";try (SSHClient ssh = new SSHClient()) {ssh.addHostKeyVerifier(new PromiscuousVerifier()); // 跳过 host key 验证ssh.connect(host);ssh.authPassword(user, password);try (Session session = ssh.startSession()) {Session.Command cmd = session.exec("uname -a");System.out.println(new String(cmd.getInputStream().readAllBytes()));cmd.join();}ssh.disconnect();} catch (Exception e) {e.printStackTrace();}}
}
✅ Java 示例:上传文件(SFTP)
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;import java.io.File;
import java.io.IOException;public class SshjUploadExample {public static void main(String[] args) throws IOException {String host = "your.server.ip";String user = "root";String password = "your_password";SSHClient ssh = new SSHClient();ssh.addHostKeyVerifier(new PromiscuousVerifier());ssh.connect(host);ssh.authPassword(user, password);SFTPClient sftp = ssh.newSFTPClient();sftp.put(new File("local.txt").getPath(), "/root/remote.txt");sftp.close();ssh.disconnect();}
}