【问题标题】:Capture server command output using JSch and Java使用 JSch 和 Java 捕获服务器命令输出
【发布时间】:2016-04-20 09:11:04
【问题描述】:

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

代码:

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

【问题讨论】:

    标签: java ssh stdout jsch


    【解决方案1】:

    使用exec 频道,而不是shell 频道。 exec 通道用于命令执行。 shell 频道旨在实现交互式会话。这就是为什么您会收到所有提示等。您不会在exec 频道中获得这些。

    请参阅official JSCh example for using exec channel

    如果您需要同时阅读 stdout 和 stderr,请参阅我对How to read JSch command output?的回答

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 2013-05-04
      • 2017-02-26
      • 2013-01-16
      • 1970-01-01
      相关资源
      最近更新 更多