Search in sources :

Example 6 with ConnectFuture

use of org.apache.sshd.client.future.ConnectFuture in project camel by apache.

the class SshHelper method sendExecCommand.

public static SshResult sendExecCommand(String command, SshEndpoint endpoint, SshClient client) throws Exception {
    SshResult result = null;
    SshConfiguration configuration = endpoint.getConfiguration();
    if (configuration == null) {
        throw new IllegalStateException("Configuration must be set");
    }
    ConnectFuture connectFuture = client.connect(null, configuration.getHost(), configuration.getPort());
    // Wait getTimeout milliseconds for connect operation to complete
    connectFuture.await(configuration.getTimeout());
    if (!connectFuture.isDone() || !connectFuture.isConnected()) {
        final String msg = "Failed to connect to " + configuration.getHost() + ":" + configuration.getPort() + " within timeout " + configuration.getTimeout() + "ms";
        LOG.debug(msg);
        throw new RuntimeCamelException(msg);
    }
    LOG.debug("Connected to {}:{}", configuration.getHost(), configuration.getPort());
    ClientChannel channel = null;
    ClientSession session = null;
    try {
        AuthFuture authResult;
        session = connectFuture.getSession();
        KeyPairProvider keyPairProvider;
        final String certResource = configuration.getCertResource();
        if (certResource != null) {
            LOG.debug("Attempting to authenticate using ResourceKey '{}'...", certResource);
            keyPairProvider = new ResourceHelperKeyPairProvider(new String[] { certResource }, endpoint.getCamelContext().getClassResolver());
        } else {
            keyPairProvider = configuration.getKeyPairProvider();
        }
        if (keyPairProvider != null) {
            LOG.debug("Attempting to authenticate username '{}' using Key...", configuration.getUsername());
            KeyPair pair = keyPairProvider.loadKey(configuration.getKeyType());
            authResult = session.authPublicKey(configuration.getUsername(), pair);
        } else {
            LOG.debug("Attempting to authenticate username '{}' using Password...", configuration.getUsername());
            authResult = session.authPassword(configuration.getUsername(), configuration.getPassword());
        }
        authResult.await(configuration.getTimeout());
        if (!authResult.isDone() || authResult.isFailure()) {
            LOG.debug("Failed to authenticate");
            throw new RuntimeCamelException("Failed to authenticate username " + configuration.getUsername());
        }
        channel = session.createChannel(ClientChannel.CHANNEL_EXEC, command);
        ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 0 });
        channel.setIn(in);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        channel.setOut(out);
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setErr(err);
        OpenFuture openFuture = channel.open();
        openFuture.await(configuration.getTimeout());
        if (openFuture.isOpened()) {
            channel.waitFor(ClientChannel.CLOSED, 0);
            result = new SshResult(command, channel.getExitStatus(), new ByteArrayInputStream(out.toByteArray()), new ByteArrayInputStream(err.toByteArray()));
        }
        return result;
    } finally {
        if (channel != null) {
            channel.close(true);
        }
        // need to make sure the session is closed 
        if (session != null) {
            session.close(false);
        }
    }
}
Also used : KeyPair(java.security.KeyPair) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ClientChannel(org.apache.sshd.ClientChannel) KeyPairProvider(org.apache.sshd.common.KeyPairProvider) OpenFuture(org.apache.sshd.client.future.OpenFuture) ByteArrayInputStream(java.io.ByteArrayInputStream) ClientSession(org.apache.sshd.ClientSession) RuntimeCamelException(org.apache.camel.RuntimeCamelException) AuthFuture(org.apache.sshd.client.future.AuthFuture)

Example 7 with ConnectFuture

use of org.apache.sshd.client.future.ConnectFuture in project tesb-studio-se by Talend.

the class RuntimeClient method connectWithRetries.

private static ClientSession connectWithRetries(SshClient client, ClientConfig config) throws Exception, InterruptedException {
    ClientSession session = null;
    int retries = 0;
    do {
        try {
            ConnectFuture future = client.connect(config.getUser(), config.getHost(), config.getPort());
            future.await();
            session = future.getSession();
        } catch (RuntimeSshException ex) {
            if (++retries < 10) {
                TimeUnit.SECONDS.sleep(2);
            } else {
                throw ex;
            }
        }
    } while (session == null);
    return session;
}
Also used : ClientSession(org.apache.sshd.client.session.ClientSession) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) RuntimeSshException(org.apache.sshd.common.RuntimeSshException)

Example 8 with ConnectFuture

use of org.apache.sshd.client.future.ConnectFuture in project karaf by apache.

the class ClientMojo method connect.

private ClientSession connect(SshClient client) throws IOException, InterruptedException {
    int retries = 0;
    ClientSession session = null;
    do {
        final ConnectFuture future = client.connect(user, host, port);
        future.await();
        try {
            session = future.getSession();
        } catch (RuntimeSshException ex) {
            if (retries++ < attempts) {
                Thread.sleep(TimeUnit.SECONDS.toMillis(delay));
                getLog().info("retrying (attempt " + retries + ") ...");
            } else {
                throw ex;
            }
        }
    } while (session == null);
    return session;
}
Also used : ClientSession(org.apache.sshd.client.session.ClientSession) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) RuntimeSshException(org.apache.sshd.common.RuntimeSshException)

Example 9 with ConnectFuture

use of org.apache.sshd.client.future.ConnectFuture in project karaf by apache.

the class SshCommandTestBase method openSshChannel.

private OutputStream openSshChannel(String username, String password, OutputStream... outputs) throws Exception {
    client = SshClient.setUpDefaultClient();
    client.start();
    String sshPort = getSshPort();
    ConnectFuture future = client.connect(username, "localhost", Integer.parseInt(sshPort));
    future.await();
    session = future.getSession();
    Set<ClientSessionEvent> ret = EnumSet.of(ClientSessionEvent.WAIT_AUTH);
    while (ret.contains(ClientSessionEvent.WAIT_AUTH)) {
        session.addPasswordIdentity(password);
        session.auth().verify();
        ret = session.waitFor(EnumSet.of(ClientSessionEvent.WAIT_AUTH, ClientSessionEvent.CLOSED, ClientSessionEvent.AUTHED), 0);
    }
    if (ret.contains(ClientSessionEvent.CLOSED)) {
        throw new Exception("Could not open SSH channel");
    }
    channel = session.createChannel("shell");
    PipedOutputStream pipe = new PipedOutputStream();
    channel.setIn(new PipedInputStream(pipe));
    OutputStream out;
    if (outputs.length >= 1) {
        out = outputs[0];
    } else {
        out = new ByteArrayOutputStream();
    }
    channel.setOut(out);
    OutputStream err;
    if (outputs.length >= 2) {
        err = outputs[1];
    } else {
        err = new ByteArrayOutputStream();
    }
    channel.setErr(err);
    channel.open();
    return pipe;
}
Also used : ClientSessionEvent(org.apache.sshd.client.session.ClientSession.ClientSessionEvent) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PipedOutputStream(java.io.PipedOutputStream) PipedOutputStream(java.io.PipedOutputStream) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) PipedInputStream(java.io.PipedInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

ConnectFuture (org.apache.sshd.client.future.ConnectFuture)9 ClientSession (org.apache.sshd.client.session.ClientSession)6 RuntimeSshException (org.apache.sshd.common.RuntimeSshException)4 IOException (java.io.IOException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ClientSessionEvent (org.apache.sshd.client.session.ClientSession.ClientSessionEvent)2 ByteSource (com.google.common.io.ByteSource)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 OutputStream (java.io.OutputStream)1 PipedInputStream (java.io.PipedInputStream)1 PipedOutputStream (java.io.PipedOutputStream)1 URL (java.net.URL)1 KeyPair (java.security.KeyPair)1 RuntimeCamelException (org.apache.camel.RuntimeCamelException)1 PKCS8Key (org.apache.commons.ssl.PKCS8Key)1 ClientChannel (org.apache.sshd.ClientChannel)1 ClientSession (org.apache.sshd.ClientSession)1 SshClient (org.apache.sshd.SshClient)1 SshClient (org.apache.sshd.client.SshClient)1 AuthFuture (org.apache.sshd.client.future.AuthFuture)1