使用JSCH和Java

问题描述 投票:0回答:1

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
通道,而不是
java ssh stdout jsch
1个回答
1
投票
通道。

exec

通道旨在执行命令。 
shell
通道旨在实现交互式会话。这就是为什么您会收到所有提示等。您没有在
exec
频道中得到这些。
请参见使用
exec
渠道
official jsch示例。
如果您需要读取Stdout和Stderr,请参阅我对wow wow wow读取jsch命令输出的答案?

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.