引用最新的依赖(官方的已经很久没更新了,这个是开源的)
<dependency>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>2.27.2</version>
</dependency>
参考:解决com.jcraft.jsch.JSchException: Algorithm negotiation fail-CSDN博客
java
import com.jcraft.jsch.*;
import java.io.InputStream;
public class SSHConnection {
public static void main(String[] args) {
JSch jsch = new JSch();
Session session = null;
try {
// 1. 创建会话并连接
session = jsch.getSession("账号名", "ip地址", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("密码");
session.connect();
System.out.println("SSH连接成功");
// 2. 创建执行通道
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
// 3. 设置命令 - 这里测试环境变量是否加载
String command = "source /etc/profile; source ~/.bashrc; echo $PATH; ls -lh";
channelExec.setCommand(command);
// 4. 设置输入输出流
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
// 5. 获取输出流
InputStream in = channelExec.getInputStream();
// 6. 连接并执行命令
channelExec.connect();
System.out.println("执行命令: " + command);
// 7. 读取命令输出
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
System.out.print(new String(tmp, 0, i));
}
if (channelExec.isClosed()) {
System.out.println("\n退出状态: " + channelExec.getExitStatus());
break;
}
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 8. 关闭连接
if (session != null && session.isConnected()) {
session.disconnect();
System.out.println("SSH连接已关闭");
}
}
}
}
运行结果
可根据上面代码进一步优化。