Skip to content

Instantly share code, notes, and snippets.

@mwiede
Created June 25, 2020 22:16
Show Gist options
  • Save mwiede/222611ac8a9bffe8818a3e36e30ccf99 to your computer and use it in GitHub Desktop.
Save mwiede/222611ac8a9bffe8818a3e36e30ccf99 to your computer and use it in GitHub Desktop.
Example reading and writing using exec channel
class JschExec {
private static String runCommand(Session session, String command, String... input) throws JSchException, IOException {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
try {
channel.setCommand(command);
logger.debug("running command: {}", command);
final InputStream in = channel.getInputStream();
final InputStream errStream = channel.getErrStream();
final OutputStream out = channel.getOutputStream();
PrintWriter writer = new PrintWriter(out, true);
channel.connect();
int printed=0;
while (true) {
String response = null;
String errorMessage = null;
while (in.available() > 0) {
byte[] tmp = new byte[1024];
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
response = new String(tmp, 0, i, Charset.defaultCharset());
}
while (errStream.available() > 0) {
byte[] tmp = new byte[1024];
int i = errStream.read(tmp, 0, 1024);
if (i < 0) break;
errorMessage = new String(tmp, Charset.defaultCharset());
}
logger.debug("exit-status: {}", channel.getExitStatus());
logger.debug("stderr:{}", errorMessage);
logger.debug("stdout: {}", response);
if (channel.isClosed()) {
if (channel.getExitStatus() == 0) {
return response;
} else {
throw new RuntimeException("command ended in exit-status:" + channel.getExitStatus() +
" with error message: " + errorMessage);
}
} else if (response != null) {
writer.println(input[printed++]);
}
Thread.sleep(50);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
channel.disconnect();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment