java - 使用 JSch 和 Java 捕获服务器命令输出

标签 java ssh stdout jsch

我正在使用 JSch 通过 SSH 连接到多个服务器并运行一些命令。我的输出文件捕获了所有内容。但我正在寻找一种只捕获服务器响应的方法。

代码:

try (OutputStream log = new BufferedOutputStream( new FileOutputStream("OUTPUT_FILE"))) {
    JSch jsch = new JSch();

    for (String host : jssh.listOfhost()) {
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(getProperties());
        session.connect(10 * 1000);

        Channel channel = session.openChannel("shell");
        channel.setOutputStream(log, true);

        try (PipedInputStream commandSource = new PipedInputStream();
             OutputStream commandSink = new PipedOutputStream(commandSource)) {

            CommandSender sender = new CommandSender(commandSink);
            Thread sendThread = new Thread(sender);
            sendThread.start();

            channel.setInputStream(commandSource);
            channel.connect(15 * 1000);

            sendThread.join();
            if (sender.exception != null) {
                throw sender.exception;
            }
        }

        channel.disconnect();
        session.disconnect();
    }
}

当前输出:

Last login: Thu Jan 14 15:06:17 2016 from 192.168.1.4
mypc:~ user$ 
mypc:~ user$ hostname
mypc
mypc:~ user$ df -l | grep disk0s3 |tr -s [:blank:]|cut -d ' ' -f 7
19098537

但我只想输出以下内容

mypc 19098537

这是以下两个命令的结果

hostname
df -l | grep disk0s3 |tr -s [:blank:]|cut -d ' ' -f 7

最佳答案

使用exec channel ,而不是shell channel 。 exec channel 用于命令执行。 shell channel 用于实现交互式 session 。这就是为什么您会收到所有提示等的原因。您不会在 exec channel 中获得这些内容。

参见 official JSCh example for using exec channel .

如果您需要阅读标准输出和标准错误,请参阅我对 How to read JSch command output? 的回答

关于java - 使用 JSch 和 Java 捕获服务器命令输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34799815/

相关文章:

java - 如何处理 DAO 中的连接对象 (Java EE)

Python2.7 : ssh. exec_command 没有执行任何命令

ssh - Pycharm/VS Code是否可以使用远程python解释器(通过SSH)进行远程代码编辑?

php - 从 ssh2_connect() 断开连接

Python 子进程输出到标准输出

java - 单击禁用的 Swing 组件

java - Weblogic keystore 服务异常: Failed to perform cryptographic operation

stdout - 如何使任何 shell 命令的输出不缓冲?

python - 标准输出的行缓冲在 MINGW/MSYS Python 2.7.3 上失败

java - 如何像软键盘一样将 PopupWindow 设置在根布局的底部?