for (int c = reader.read(); c >= 0; c = reader.read()) {
command.append((char) c);
}
}
SshClient client = null;
Terminal terminal = null;
SshAgent agent = null;
int exitStatus = 0;
try {
final Console console = System.console();
client = SshClient.setUpDefaultClient();
setupAgent(user, client, keyFile);
client.setUserInteraction(new UserInteraction() {
public void welcome(String banner) {
System.out.println(banner);
}
public String[] interactive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
String[] answers = new String[prompt.length];
try {
for (int i = 0; i < prompt.length; i++) {
if (console != null) {
if (echo[i]) {
answers[i] = console.readLine(prompt[i] + " ");
} else {
answers[i] = new String(console.readPassword(prompt[i] + " "));
}
}
}
} catch (IOError e) {
}
return answers;
}
});
client.start();
if (console != null) {
console.printf("Logging in as %s\n", user);
}
ClientSession session = null;
int retries = 0;
do {
ConnectFuture future = client.connect(user, host, port);
future.await();
try {
session = future.getSession();
} catch (RuntimeSshException ex) {
if (retries++ < retryAttempts) {
Thread.sleep(retryDelay * 1000);
System.out.println("retrying (attempt " + retries + ") ...");
} else {
throw ex;
}
}
} while (session == null);
if (password != null) {
session.addPasswordIdentity(password);
}
session.auth().verify();
ClientChannel channel;
if (command.length() > 0) {
channel = session.createChannel("exec", command.append("\n").toString());
channel.setIn(new ByteArrayInputStream(new byte[0]));
} else {
terminal = new TerminalFactory().getTerminal();
channel = session.createChannel("shell");
ConsoleInputStream in = new ConsoleInputStream(terminal.wrapInIfNeeded(System.in));
new Thread(in).start();
channel.setIn(in);
((ChannelShell) channel).setPtyColumns(terminal != null ? terminal.getWidth() : 80);
((ChannelShell) channel).setupSensibleDefaultPty();
((ChannelShell) channel).setAgentForwarding(true);
String ctype = System.getenv("LC_CTYPE");
if (ctype == null) {
ctype = Locale.getDefault().toString() + "."
+ System.getProperty("input.encoding", Charset.defaultCharset().name());
}
((ChannelShell) channel).setEnv("LC_CTYPE", ctype);
}
channel.setOut(AnsiConsole.wrapOutputStream(System.out));
channel.setErr(AnsiConsole.wrapOutputStream(System.err));
channel.open();
channel.waitFor(ClientChannel.CLOSED, 0);
if (channel.getExitStatus() != null) {
exitStatus = channel.getExitStatus();
}
} catch (Throwable t) {
if (level > 1) {
t.printStackTrace();
} else {
System.err.println(t.getMessage());
}
System.exit(1);
} finally {
try {
client.stop();
} catch (Throwable t) { }
try {
if (terminal != null) {
terminal.restore();
}