我在 Android 设备上使用以下 SSH 方法向本地服务器发送命令。
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);
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;
}
问题是它似乎打开了一个虚拟终端,然后返回终端中的所有内容,包括欢迎消息、命令提示符、命令、结果以及一些有关成为“虚拟”终端的警告消息。打印出日志中的
responseString
,我得到..
debian raspbian buster 10 computer
touch test.file
'dummy': unknown terminal type.
username@computer:~$ touch test.file
username@computer:~$
我想要和我时一样的行为..
sss -p port username@host 'touch test.file'
,它不会打开虚拟终端,只是返回命令的返回值。
而不是..
channel = session.createChannel(Channel.CHANNEL_SHELL);
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOut(responseStream);
// open channel
channel.open().verify(5, TimeUnit.SECONDS);
try (OutputStream pipedIn = channel.getInvertedIn()) {
pipedIn.write(command.getBytes());
pipedIn.flush();
}
做..
channel = session.createExecChannel(this.command);
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOut(responseStream);
// open channel
channel.open().verify(5, TimeUnit.SECONDS);
// close channel
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED),
TimeUnit.SECONDS.toMillis(5));
// output after converting to string type
responseString = responseStream.toString();
它不是打开 shell 并发送回 shell 的所有内容,而是简单地发送命令并返回命令的结果。