Skip to content

scmd and EOF #496

@grimdug

Description

@grimdug

Seems like newer sshj versions do not transmit an EOF to the running command. This did work fine at least up to version 0.8.1 and now just hangs (runs into timeout) with recent versions. I force the EOF by closing the cmd.getOutputStream() after all data was sent using a custom StreamCopier.:

//
// Do something like: echo "hello" | ssh myhost cat
//
class MyStreamCopier {
private final InputStream in;
private final OutputStream out;
MyStreamCopier(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
public void spawn() {
Thread thread = new Thread() {
@OverRide
public void run() {
try {
final byte[] buf = new byte[5];
int read;
while((read = in.read(buf)) != -1) {
out.write(buf, 0, read);
out.flush();
}
out.flush();
out.close();
} catch(IOException ioe) {
System.err.println(ioe);
}
}
};
thread.start();
}
}
class SSH {
public static void main(String... args) throws IOException {
final SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier((String hostname, int port, PublicKey key) -> true);
ssh.connect("myhost");
try {
ssh.authPassword(System.getProperty("user.name"), "mypass".toCharArray());
try(Session session = ssh.startSession()) {
Session.Command cmd = session.exec("cat");
InputStream instream = new ByteArrayInputStream("hello\n".getBytes(StandardCharsets.UTF_8));
new StreamCopier(cmd.getInputStream(), System.out).spawn("stdout");
new StreamCopier(cmd.getErrorStream(), System.err).spawn("stderr");
//new StreamCopier(cmd.getInputStream(), System.out, LoggerFactory.DEFAULT).spawn("stdout");
//new StreamCopier(cmd.getErrorStream(), System.err, LoggerFactory.DEFAULT).spawn("stderr");
new MyStreamCopier(instream, cmd.getOutputStream()).spawn();
cmd.join(10, TimeUnit.SECONDS);
}
} finally {
ssh.disconnect();
}
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions