我有以下代码,它使用JSch在远程服务器上运行命令,并在通过main方法调用时工作正常。
public static void runCommand(String user, String password, String host, String command,String yesorno ) {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session;
try {
session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected to " + host);
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setPty(true);
channel.connect();
out.write((password + "\n").getBytes());
out.flush();
OutputStream out1 = channel.getOutputStream();
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(new String(tmp,0,i).toLowerCase().contains("y/n"))
{
out1.write((yesorno + "\n").getBytes());
out1.flush();
}
else if(new String(tmp,0,i).contains("password"))
{
out1.write((password + "\n").getBytes());
out1.flush();
}
}
if (channel.isClosed()) {
System.out.println("Exit status: " + channel.getExitStatus());
break;
}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch (JSchException | IOException e) {
e.printStackTrace();
}
}
现在我想打印命令执行跟踪,但我希望它在我的网页界面中,我将命令传递给这个java方法。我怎样才能做到这一点。我一直在互联网上搜索最近2天没有任何好的答案。提前致谢
我最终决定使用Web套接字并在Java中的onmessage块中使用整个函数。我使用Json从前端提供命令和require字段并解析并在函数中使用它然后在UI中打印输出