Java Code Examples for org.apache.sshd.client.SshClient#start()

The following examples show how to use org.apache.sshd.client.SshClient#start() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdleClient() throws Exception {
    SshClient client = setupTestClient();
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)));
        }
    } finally {
        client.stop();
    }
}
 
Example 2
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientWithHeartBeat() throws Exception {
    SshClient client = setupTestClient();
    PropertyResolverUtils.updateProperty(client, ClientFactoryManager.HEARTBEAT_INTERVAL, HEARTBEAT);
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.contains(ClientChannelEvent.TIMEOUT));
        }
    } finally {
        client.stop();
    }
}
 
Example 3
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdleClient() throws Exception {
    SshClient client = setupTestClient();
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)));
        }
    } finally {
        client.stop();
    }
}
 
Example 4
Source File: KeepAliveTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientWithHeartBeat() throws Exception {
    SshClient client = setupTestClient();
    PropertyResolverUtils.updateProperty(client, ClientFactoryManager.HEARTBEAT_INTERVAL, HEARTBEAT);
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result, result.contains(ClientChannelEvent.TIMEOUT));
        }
    } finally {
        client.stop();
    }
}
 
Example 5
Source File: FuseUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static ClientSession openSshChannel(String username, String password) throws IOException {
    SshClient client = SshClient.setUpDefaultClient();
    client.start();
    ConnectFuture future = client.connect(username, "localhost", 8101);
    future.await();
    ClientSession session = future.getSession();

    Set<ClientSession.ClientSessionEvent> ret = EnumSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH);
    while (ret.contains(ClientSession.ClientSessionEvent.WAIT_AUTH)) {
        session.addPasswordIdentity(password);
        session.auth().verify();
        ret = session.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH, ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED), 0);
    }
    if (ret.contains(ClientSession.ClientSessionEvent.CLOSED)) {
        throw new RuntimeException("Could not open SSH channel");
    }

    return session;
}
 
Example 6
Source File: KeepAliveTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testShellClosedOnClientTimeout() throws Exception {
    TestEchoShell.latch = new CountDownLatch(1);

    SshClient client = setupTestClient();
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL);
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             ByteArrayOutputStream err = new ByteArrayOutputStream()) {

            channel.setOut(out);
            channel.setErr(err);
            channel.open().verify(9L, TimeUnit.SECONDS);

            assertTrue("Latch time out", TestEchoShell.latch.await(10L, TimeUnit.SECONDS));
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result,
                       result.containsAll(
                           EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.OPENED)));
        }
    } finally {
        TestEchoShell.latch = null;
        client.stop();
    }
}
 
Example 7
Source File: KeepAliveTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testShellClosedOnClientTimeout() throws Exception {
    TestEchoShell.latch = new CountDownLatch(1);

    SshClient client = setupTestClient();
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL);
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             ByteArrayOutputStream err = new ByteArrayOutputStream()) {

            channel.setOut(out);
            channel.setErr(err);
            channel.open().verify(9L, TimeUnit.SECONDS);

            assertTrue("Latch time out", TestEchoShell.latch.await(10L, TimeUnit.SECONDS));
            Collection<ClientChannelEvent> result =
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT);
            assertTrue("Wrong channel state: " + result,
                       result.containsAll(
                           EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.OPENED)));
        }
    } finally {
        TestEchoShell.latch = null;
        client.stop();
    }
}
 
Example 8
Source File: SSHServerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000L)
public void call() throws Exception {
    final SshClient client = SshClient.setUpDefaultClient();
    client.start();
    try {
        final ClientSession session = client.connect("jonathan", "localhost", 4222).verify().getSession();
        session.addPasswordIdentity("secret");
        session.auth().verify(FactoryManager.DEFAULT_AUTH_TIMEOUT);

        final ClientChannel channel = session.createChannel("shell");
        ByteArrayOutputStream sent = new ByteArrayOutputStream();
        PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
        channel.setIn(new PipedInputStream(pipedIn));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setOut(out);
        channel.setErr(err);
        channel.open();

        pipedIn.write("properties\r\n".getBytes());
        pipedIn.flush();

        pipedIn.write("exit\r\n".getBytes());
        pipedIn.flush();

        channel.waitFor(Collections.singleton(ClientChannelEvent.CLOSED), 0);
        channel.close(false);
        client.stop();

        assertTrue(new String(sent.toByteArray()).contains("properties\r\nexit\r\n"));
        assertTrue(new String(out.toByteArray()).contains("ServerService(id=ssh)"));
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}
 
Example 9
Source File: SSHUtil.java    From xenon with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new {@link SshClient} with the desired configuration.
 * <p>
 * SSH clients have a significant number of options. This method will create a <code>SshClient</code> providing the most important settings.
 * </p>
 *
 * @param useKnownHosts
 *            Load the SSH known_hosts file from the default location (for OpenSSH this is typically found in $HOME/.ssh/known_hosts).
 * @param loadSSHConfig
 *            Load the SSH config file from the default location (for OpenSSH this is typically found in $HOME/.ssh/config).
 * @param stricHostCheck
 *            Perform a strict host key check. When setting up a connection, the key presented by the server is compared to the default known_hosts file
 *            (for OpenSSH this is typically found in $HOME/.ssh/known_hosts).
 * @param useSSHAgent
 *            When setting up a connection, handoff authentication to a separate SSH agent process.
 * @param useAgentForwarding
 *            Support agent forwarding, allowing remote SSH servers to use the local SSH agent process to authenticate connections to other servers.
 * @return the configured {@link SshClient}
 */
public static SshClient createSSHClient(boolean useKnownHosts, boolean loadSSHConfig, boolean stricHostCheck, boolean useSSHAgent,
        boolean useAgentForwarding) {

    SshClient client = SshClient.setUpDefaultClient();

    // This sets the idle time after which the connection is closed automatically. The default is set to 10 minutes.
    // client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT, TimeUnit.SECONDS.toMillis(120L));

    // We set the heartbeat of SSH to once every 10 seconds, and expect a reply within 5 seconds.
    // This prevents an SSH operation to hang for 10 minutes if the network connection is lost.
    client.getProperties().putIfAbsent(ClientFactoryManager.HEARTBEAT_INTERVAL, TimeUnit.SECONDS.toMillis(10L));
    client.getProperties().putIfAbsent(ClientFactoryManager.HEARTBEAT_REPLY_WAIT, TimeUnit.SECONDS.toMillis(5L));

    if (useKnownHosts) {
        DefaultKnownHostsServerKeyVerifier tmp;

        if (stricHostCheck) {
            tmp = new DefaultKnownHostsServerKeyVerifier(RejectAllServerKeyVerifier.INSTANCE, true);
        } else {
            tmp = new DefaultKnownHostsServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE, true);
            tmp.setModifiedServerKeyAcceptor(
                    (ClientSession clientSession, SocketAddress remoteAddress, KnownHostEntry entry, PublicKey expected, PublicKey actual) -> true);
        }

        client.setServerKeyVerifier(tmp);
    } else {
        client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE);
    }

    if (loadSSHConfig) {
        client.setHostConfigEntryResolver(DefaultConfigFileHostEntryResolver.INSTANCE);
    }

    if (useSSHAgent) {
        client.setAgentFactory(new ProxyAgentFactory());
    }

    if (useAgentForwarding) {
        // Enable ssh-agent-forwarding
        LOGGER.debug("(UNIMPLEMENTED) Enabling ssh-agent-forwarding");
    }

    client.start();

    return client;
}