在单独的控制台/命令窗口中显示使用JSch执行SSH命令的结果,可以通过以下步骤实现:
import com.jcraft.jsch.*;
public class SSHCommandExecutor {
public static void main(String[] args) {
String host = "your_host";
String username = "your_username";
String password = "your_password";
int port = 22;
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command = "your_ssh_command";
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] buffer = new byte[1024];
StringBuilder result = new StringBuilder();
while (true) {
while (in.available() > 0) {
int bytesRead = in.read(buffer, 0, 1024);
if (bytesRead < 0) break;
result.append(new String(buffer, 0, bytesRead));
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
System.out.println("Exit status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(result.toString());
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
}
这种方法使用JSch库建立SSH连接,并通过执行SSH命令获取命令的输出结果。然后,将结果显示在控制台/命令窗口中。这对于需要在Java程序中执行远程服务器上的命令并查看结果的场景非常有用。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云