I’m using the following SSH method on Android device to send a command to a local server.
protected String sshConnect(String username, String password, String host, int port, long defaultTimeoutSeconds, String command) {
ClientChannel channel;
String responseString = null;
// create a client instance
try (SshClient client = SshClient.setUpDefaultClient()) {
client.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); //?
client.start();
Log.d(TAG, "sshConnect(): client.start(): client started");
// connection and authentication
try (ClientSession session = client.connect(username, host, port).verify(TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds)).getSession()) {
Log.d(TAG, "ssh: client.connect()");
session.addPasswordIdentity(password);
session.auth().verify(TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds));
Log.d(TAG, "ssh: connection established");
// create a channel to communicate
channel = session.createChannel(Channel.CHANNEL_SHELL);
Log.d(TAG, "ssh: starting shell");
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOut(responseStream);
// open channel
channel.open().verify(5, TimeUnit.SECONDS);
// open channel
channel.open().verify(5, TimeUnit.SECONDS);
try (OutputStream pipedIn = channel.getInvertedIn()) {
pipedIn.write(command.getBytes());
pipedIn.flush();
}
// close channel
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED),
TimeUnit.SECONDS.toMillis(5));
// output after converting to string type
responseString = responseStream.toString();
Log.d(TAG, "ssh: responseString == " + responseString);
} catch (Exception e) {
Log.d(TAG, "sshConnect(): client.connect(): Exception: " + e);
}
} catch (Exception e) {
Log.d(TAG, "sshConnect(): client.start(): Exception: " + e);
}
return responseString;
}
Problem is it seems to be opening a dummy terminal and then return literally double everything in the terminal including the welcome message, the command prompt, the command, the result, and some warning messages about being a “dummy” terminal. Printing out the responseString
in the logs, I get..
debian raspbian buster 10 computer
debian raspbian buster 10 computer
touch test.file
'dummy': unknown terminal type.
username@computer:~$ 'dummy': unknown terminal type.
username@computer:~$ touch test.file
username@computer:~$
I would like the same behavior as when I ..
sss -p port username@host 'touch test.file'
where it doesn’t open a dummy terminal and simply returns the result of the command.