username = readLine("Login: ");
}
}
// Create the client from prototype
SshClient client = (SshClient) container.getComponentInstance(sshClientId);
log.debug("Created client: {}", client);
client.start();
String agentSocket = null;
if (this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME) != null) {
agentSocket = this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME).toString();
client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME,agentSocket);
}
try {
ConnectFuture future = client.connect(hostname, port);
future.await();
sshSession = future.getSession();
Object oldIgnoreInterrupts = this.session.get(Console.IGNORE_INTERRUPTS);
this.session.put( Console.IGNORE_INTERRUPTS, Boolean.TRUE );
try {
System.out.println("Connected");
boolean authed = false;
if (agentSocket != null) {
sshSession.authAgent(username);
int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
if ((ret & ClientSession.AUTHED) == 0) {
System.err.println("Agent authentication failed, falling back to password authentication.");
} else {
authed = true;
}
}
if (!authed) {
log.debug("Prompting user for password");
String password = readLine("Password: ");
sshSession.authPassword(username, password);
int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
if ((ret & ClientSession.AUTHED) == 0) {
System.err.println("Password authentication failed");
} else {
authed = true;
}
}
if (!authed) {
return null;
}
StringBuilder sb = new StringBuilder();
if (command != null) {
for (String cmd : command) {
if (sb.length() > 0) {
sb.append(' ');
}
sb.append(cmd);
}
}
ClientChannel channel;
if (sb.length() > 0) {
channel = sshSession.createChannel("exec", sb.append("\n").toString());
channel.setIn(new ByteArrayInputStream(new byte[0]));
} else {
channel = sshSession.createChannel("shell");
channel.setIn(new NoCloseInputStream(System.in));
((ChannelShell) channel).setPtyColumns(getTermWidth());
((ChannelShell) channel).setupSensibleDefaultPty();
((ChannelShell) channel).setAgentForwarding(true);
Object ctype = session.get("LC_CTYPE");
if (ctype != null) {
((ChannelShell) channel).setEnv("LC_CTYPE", ctype.toString());
}
}
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open();
channel.waitFor(ClientChannel.CLOSED, 0);
} finally {
session.put(Console.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
sshSession.close(false);
}
} finally {
client.stop();
}
return null;
}