【问题标题】:Real time console output (Live output) while running a UNIX Shell script from Java从 Java 运行 UNIX Shell 脚本时的实时控制台输出(实时输出)
【发布时间】:2017-08-16 09:53:54
【问题描述】:

要求是在 UI 上向用户显示脚本执行输出的实时流。

我有一个 UNIX Shell 脚本,其中包含多个命令和 sleep 命令。从 Java 执行每个命令后,我需要读取控制台输出。

我正在使用 JSCH (JCraft) 连接到 UNIX 服务器并运行 Shell 脚本。执行完整的脚本后,我能够获得控制台输出。但无法在每次命令执行后获取。

这是一个 UNIX Shell 脚本:

#!/bin/bash 
echo "Executing touch ChaosMonkey"
sleep 5
echo "Connection and Execution Successfully"
if [ $? = 0 ]
then
  echo "Monkey executed successfully"
else
  echo "Monkey execution returned with error" $?
fi

附:我不能采用文件方法,我可以将该 o/p 放入文件并通过其他 SSH 连接读取该文件。

【问题讨论】:

  • 请同时发布您的 Java 代码。

标签: java shell unix ssh jsch


【解决方案1】:

以下是解决此问题的方法:

这是 Java 代码 (JSCH) 的 sn-p。在 while 循环中,您将收到实时控制台输出。

        channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand("bash /tmp/temp.sh");
        channel.setInputStream(null);
        channel.setOutputStream(System.out);
        InputStream out = channel.getInputStream();
        channel.connect();          
        StringBuilder outputBuffer = new StringBuilder();
        byte[] tmp = new byte[1024];

        while (true) {
            while (out.available() > 0) {
                int i = out.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                outputBuffer.append(new String(tmp, 0, i));
            }
            if (channel.isEOF()) {
                break;
            }
        }
        System.out.println(" console output::::::::::: "+ outputBuffer.toString());
        System.out.println("Channel exit-status: " + channel.getExitStatus());
        channel.disconnect();

【讨论】:

  • 这个 sn-p 只在退出 while 循环后打印控制台输出。它没有做你想要的问题。
  • 要让它显示在 UI 上,还有更多的事情要做。获得这些实时日志后,您可以将其保存到任何 Collection 并与 Event Emitter 挂钩,该事件发射器将不断将此日志发送到 UI 应用程序,该应用程序将通过 Web 套接字监听它。我已经实现了端到端的东西,项目在 github 上可用。检查弹性工作室代理文件夹。 github.com/att/Resiliency-Studio
猜你喜欢
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 2012-07-22
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多