java - Redirecting output stream of JSch exec channel to a file using setOutputStream does not work -
i using jsch exec channel login multiple servers , run few commands. need capture output , store in file called log
. odd reason, file remains blank after executing.
try (outputstream log = new bufferedoutputstream(new fileoutputstream(outputfilepath))) { arraylist<string> lists = new arraylist<string>(); lists.add("hostname"); lists.add("df -l"); string host ="localhost"; jsch jsch = new jsch(); try { string user = "user"; string password = "pass"; session session = jsch.getsession(user, host, 22); session.setpassword(password); session.setconfig(getproperties()); session.settimeout(20 * 1000); system.out.println(session.gettimeout()); session.connect(); if (session.isconnected()) { system.out.println(host + " session established "); } (string elem : lists) { channel channel = session.openchannel("exec"); channel.setoutputstream(log); ((channelexec) channel).setcommand(elem); channel.setinputstream(null); ((channelexec) channel).seterrstream(system.err); inputstream in = channel.getinputstream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int = in.read(tmp, 0, 1024); if (i < 0) { break; } system.out.print(new string(tmp, 0, i)); } if (channel.isclosed()) { if (in.available() > 0) { continue; } system.out.println("exit-status: " + channel.getexitstatus()); break; } try { thread.sleep(1000); } catch (exception ee) { } } channel.disconnect(); } session.disconnect();
the program displays output via ide console, output file gets created remains blank.
then set system.setout
file, prevented console displaying anymore more data output.txt
file remains blank.
system.setout(new printstream(new bufferedoutputstream(new fileoutputstream("output.txt"))));
it's because getinputstream
overrides setoutputstream
call.
see how these methods implemented in jsch (both end calling io.setoutputstream
):
public void setoutputstream(outputstream out){ io.setoutputstream(out, false); } public inputstream getinputstream() throws ioexception { int max_input_buffer_size = 32*1024; try { max_input_buffer_size = integer.parseint(getsession().getconfig("max_input_buffer_size")); } catch(exception e){} pipedinputstream in = new mypipedinputstream( 32*1024, // value should customizable. max_input_buffer_size ); boolean resizable = 32*1024<max_input_buffer_size; io.setoutputstream(new passiveoutputstream(in, resizable), false); return in; }
i assume not need output reading block based on inputstream in
. remove , log file writing should start working.
side note: output stream closed default channel. reuse same stream multiple channels, should prevent that.
use override of setoutputstream
dontclose
argument:
public void setoutputstream(outputstream out, boolean dontclose)
like this:
channel.setoutputstream(log, true);
Comments
Post a Comment