org.apache.sshd.client.channel.ClientChannelEvent Java Examples

The following examples show how to use org.apache.sshd.client.channel.ClientChannelEvent. 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: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 6L * 60L * 1000L)
public void testTrafficHeavyLoad() throws Exception {
    try (SshClient client = setupTestClient()) {
        client.start();

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

            try (final ClientChannel channel = session.createShellChannel()) {
                channel.setOut(new VerifyingOutputStream(channel, END_FILE));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open().verify(15L, TimeUnit.SECONDS);

                Collection<ClientChannelEvent> result =
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(2L));
                assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
            }
        } 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 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 #3
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 #4
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 6L * 60L * 1000L)
public void testTrafficHeavyLoad() throws Exception {
    try (SshClient client = setupTestClient()) {
        client.start();

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

            try (final ClientChannel channel = session.createShellChannel()) {
                channel.setOut(new VerifyingOutputStream(channel, END_FILE));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open().verify(15L, TimeUnit.SECONDS);

                Collection<ClientChannelEvent> result =
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(2L));
                assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #5
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 #6
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 #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: SshdHolder.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execWaitForComplete(String host, String user, char[] pemPrivateKey, String password, String command,
                                 ProcessFunction<ChannelExec, T> processor, long timeoutMs) throws Exception {
    return doExecCommand(host, user, pemPrivateKey, password, command, channelExec -> {
        // Wait for completed by condition.
        channelExec.waitFor(singleton(ClientChannelEvent.CLOSED), timeoutMs);
        return processor.process(channelExec);
    });
}
 
Example #9
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 #10
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 #11
Source File: FuseUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String getCommandOutput(String user, String password, String command) throws IOException {
    if (!command.endsWith("\n"))
        command += "\n";

    try (ClientSession session = openSshChannel(user, password);
      ChannelExec channel = session.createExecChannel(command);
      ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        channel.setOut(out);
        channel.setErr(out);
        channel.open();
        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.EOF), 0);

        return new String(out.toByteArray());
    }
}
 
Example #12
Source File: LoadTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("checkstyle:nestedtrydepth")
protected void runClient(String msg) throws Exception {
    try (SshClient client = setupTestClient()) {
        PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 1024 * 16);
        PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024 * 8);
        client.setKeyExchangeFactories(Arrays.asList(
                ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1)));
        client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc));
        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 (ByteArrayOutputStream out = new ByteArrayOutputStream();
                 ByteArrayOutputStream err = new ByteArrayOutputStream();
                 ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
                channel.setOut(out);
                channel.setErr(err);

                try {
                    channel.open().verify(9L, TimeUnit.SECONDS);
                    try (OutputStream pipedIn = channel.getInvertedIn()) {
                        msg += "\nexit\n";
                        pipedIn.write(msg.getBytes(StandardCharsets.UTF_8));
                        pipedIn.flush();
                    }

                    Collection<ClientChannelEvent> result =
                            channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
                    assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
                } finally {
                    channel.close(false);
                }

                assertArrayEquals("Mismatched message data", msg.getBytes(StandardCharsets.UTF_8), out.toByteArray());
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #13
Source File: LoadTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("checkstyle:nestedtrydepth")
protected void runClient(String msg) throws Exception {
    try (SshClient client = setupTestClient()) {
        PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 1024 * 16);
        PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024 * 8);
        client.setKeyExchangeFactories(Arrays.asList(
                ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1)));
        client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc));
        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 (ByteArrayOutputStream out = new ByteArrayOutputStream();
                 ByteArrayOutputStream err = new ByteArrayOutputStream();
                 ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
                channel.setOut(out);
                channel.setErr(err);

                try {
                    channel.open().verify(9L, TimeUnit.SECONDS);
                    try (OutputStream pipedIn = channel.getInvertedIn()) {
                        msg += "\nexit\n";
                        pipedIn.write(msg.getBytes(StandardCharsets.UTF_8));
                        pipedIn.flush();
                    }

                    Collection<ClientChannelEvent> result =
                            channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
                    assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
                } finally {
                    channel.close(false);
                }

                assertArrayEquals("Mismatched message data", msg.getBytes(StandardCharsets.UTF_8), out.toByteArray());
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #14
Source File: OpenstackNetworkingUtil.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Sends flow trace string to node.
 *
 * @param requestString reqeust string
 * @param node src node
 * @return flow trace result in string format
 */
public static String sendTraceRequestToNode(String requestString,
                                            OpenstackNode node) {
    String traceResult = null;
    OpenstackSshAuth sshAuth = node.sshAuthInfo();

    try (SshClient client = SshClient.setUpDefaultClient()) {
        client.start();

        try (ClientSession session = client
                .connect(sshAuth.id(), node.managementIp().getIp4Address().toString(), SSH_PORT)
                .verify(TIMEOUT_MS, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(sshAuth.password());
            session.auth().verify(TIMEOUT_MS, TimeUnit.SECONDS);


            try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {

                log.debug("requestString: {}", requestString);
                final InputStream inputStream =
                        new ByteArrayInputStream(requestString.getBytes(Charsets.UTF_8));

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                OutputStream errStream = new ByteArrayOutputStream();

                channel.setIn(new NoCloseInputStream(inputStream));
                channel.setErr(errStream);
                channel.setOut(outputStream);

                Collection<ClientChannelEvent> eventList = Lists.newArrayList();
                eventList.add(ClientChannelEvent.OPENED);

                OpenFuture channelFuture = channel.open();

                if (channelFuture.await(TIMEOUT_MS, TimeUnit.SECONDS)) {

                    long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;

                    while (!channelFuture.isOpened()) {
                        if ((timeoutExpiredMs - System.currentTimeMillis()) <= 0) {
                            log.error("Failed to open channel");
                            return null;
                        }
                    }
                    TimeUnit.SECONDS.sleep(WAIT_OUTPUT_STREAM_SECOND);

                    traceResult = outputStream.toString(Charsets.UTF_8.name());

                    channel.close();
                }
            } finally {
                session.close();
            }
        } finally {
            client.stop();
        }

    } catch (Exception e) {
        log.error("Exception occurred because of {}", e);
    }

    return traceResult;
}
 
Example #15
Source File: OpenstackNetworkingUiMessageHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
private String sendTraceRequestToNode(String requestString,
                                            OpenstackNode node) {
    String traceResult = null;
    OpenstackSshAuth sshAuth = node.sshAuthInfo();

    try (SshClient client = SshClient.setUpDefaultClient()) {
        client.start();

        try (ClientSession session = client
                .connect(sshAuth.id(), node.managementIp().getIp4Address().toString(), SSH_PORT)
                .verify(TIMEOUT_MS, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(sshAuth.password());
            session.auth().verify(TIMEOUT_MS, TimeUnit.SECONDS);


            try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {

                log.debug("requestString: {}", requestString);
                final InputStream inputStream =
                        new ByteArrayInputStream(requestString.getBytes());

                OutputStream outputStream = new ByteArrayOutputStream();
                OutputStream errStream = new ByteArrayOutputStream();

                channel.setIn(new NoCloseInputStream(inputStream));
                channel.setErr(errStream);
                channel.setOut(outputStream);

                Collection<ClientChannelEvent> eventList = Lists.newArrayList();
                eventList.add(ClientChannelEvent.OPENED);

                OpenFuture channelFuture = channel.open();

                if (channelFuture.await(TIMEOUT_MS, TimeUnit.SECONDS)) {

                    long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;

                    while (!channelFuture.isOpened()) {
                        if ((timeoutExpiredMs - System.currentTimeMillis()) <= 0) {
                            log.error("Failed to open channel");
                            return null;
                        }
                    }
                    TimeUnit.SECONDS.sleep(WAIT_OUTPUT_STREAM_SECOND);

                    traceResult = ((ByteArrayOutputStream) outputStream).toString(Charsets.UTF_8.name());

                    channel.close();
                }
            } finally {
                session.close();
            }
        } finally {
            client.stop();
        }

    } catch (Exception e) {
        log.error("Exception occurred because of {}", e.toString());
    }

    return traceResult;
}