Sending a TAB control character in Java
I am using the Ganymede ssh library (http://www.ganymed.ethz.ch/ssh2/) to connect to a ssh server (obviously ;)).
Normally, when using the bash, when a user presses the TAB key on the keyboard a list of possible command completions appears. I want to achieve the same behaviour, but send the tab character manually. Unfortunately I am n开发者_运维知识库ot aware how to do this. Sending "\t" does not work.
Edit: The solution must be a generic which does not only work in bash, but also in other programs, like octave (open source matlab implementation with command line, just an example where bash commands cannot be applied).
As Joachim Sauer said, this is probably because your session does not have a terminal attached, so programs such as Bash will behave as though they have been called non-interactively.
The documentation for Ganymede ssh library implies that calling session.requestPTY(...) will ask the SSH server to attach a pseudo TTY to the session. It is like passing the "-t" flag to the ssh command.
Code sample:
import java.io.IOException;
import java.io.InputStream;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
public class Main {
public static void main(String[] args) throws Exception {
new Main().test();
}
private Session sess;
public void test() throws IOException, InterruptedException {
Connection c = new Connection("myserver", 22);
c.connect();
boolean OK = c.authenticateWithPassword("user", "pass");
if (!OK) throw new IOException("Bad password");
sess = c.openSession();
sess.requestPTY("vt220");
new Thread(stdoutLogger).start();
sess.execCommand("/bin/bash");
Thread.sleep(2000);
sess.getStdin().write("echo Hello\n".getBytes());
sess.getStdin().write("ls -l /tm\t".getBytes());
Thread.sleep(4000);
sess.close();
c.close();
}
Runnable stdoutLogger = new Runnable() {
public void run() {
InputStream is = sess.getStdout();
int b;
try {
while ( (b = is.read()) != -1) {
System.out.println("Read " + b + " - " + (char)b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
You can use this command :
compgen -c
It list all possible commands in the shell. You may add
grep <something>
to filter the output
Isn't what you're talking about dependent on the command shell? I don't think '\t' works because that's the tab character, not the tab keypress which gets interpreted by your shell as a command that lists the possible command completions.
As this is a library you're asking about, it seems to me what you want, you'd have to implement yourself as the shell normally handles that, I think.
精彩评论