I am using JSch exec channel to login to multiple servers and run few commands. Then I need to capture the output and store it in a file called log
. For some odd reason, the 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 ");
}
for (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 i = 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 the output via the IDE console, but the output file gets created but it remains blank.
Then I set the system.setOut
to a file, this prevented the console from displaying anymore more data but the output.txt
file remains blank.
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt"))));