Java ssh(jsch)输出到UI而不是控制台

时间:2018-07-16 09:55:01

标签: java ajax jsch

我有以下代码,该代码使用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方法的位置。我该如何实现。我过去两天一直在互联网上搜索,但没有任何好的答案。 预先感谢

1 个答案:

答案 0 :(得分:0)

我最终决定为此使用Web套接字,并在Java中的onmessage块中使用整个函数。我使用Json提供了命令,并从前端提供了require字段并进行了解析,并在函数中使用了它,然后在UI中打印输出