依赖:
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>

代码:
import com.jcraft.jsch.*;

import java.io.IOException;
import java.io.InputStream;

public class Test {
public static void main(String[] args) throws JSchException, InterruptedException, IOException {
JSch jsch = new JSch();
jsch.addIdentity("D:\\文档\\aliecs.pem");
jsch.setConfig("StrictHostKeyChecking", "no");
Session session = jsch.getSession("root", "8.xx.xx.24", 2022);
session.connect();
String command = "ls";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.setErrStream(System.err);
channel.connect();

InputStream input = channel.getInputStream();
byte[] tmp = new byte[1024];
while (true) {
while (input.available() > 0) {
int i = input.read(tmp, 0, 1024);
if (i < 0) break;
System.out.println(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
Thread.sleep(1000);
}
channel.disconnect();
session.disconnect();
}
}