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

The following examples show how to use org.apache.sshd.client.channel.ClientChannel. 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: KeyReExchangeTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testSwitchToNoneCipher() throws Exception {
    setUp(0L, 0L, 0L);

    sshd.getCipherFactories().add(BuiltinCiphers.none);
    try (SshClient client = setupTestClient()) {
        client.getCipherFactories().add(BuiltinCiphers.none);
        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);

            outputDebugMessage("Request switch to none cipher for %s", session);
            KeyExchangeFuture switchFuture = session.switchToNoneCipher();
            switchFuture.verify(5L, TimeUnit.SECONDS);
            try (ClientChannel channel = session.createSubsystemChannel(SftpConstants.SFTP_SUBSYSTEM_NAME)) {
                channel.open().verify(5L, TimeUnit.SECONDS);
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #5
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 6 votes vote down vote up
@Test
public void testSwitchToNoneCipher() throws Exception {
    setUp(0L, 0L, 0L);

    sshd.getCipherFactories().add(BuiltinCiphers.none);
    try (SshClient client = setupTestClient()) {
        client.getCipherFactories().add(BuiltinCiphers.none);
        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);

            outputDebugMessage("Request switch to none cipher for %s", session);
            KeyExchangeFuture switchFuture = session.switchToNoneCipher();
            switchFuture.verify(5L, TimeUnit.SECONDS);
            try (ClientChannel channel = session.createSubsystemChannel(SftpConstants.SFTP_SUBSYSTEM_NAME)) {
                channel.open().verify(5L, TimeUnit.SECONDS);
            }
        } 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: 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 #8
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 #9
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 #10
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 #11
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 #12
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 4 votes vote down vote up
VerifyingOutputStream(ClientChannel channel, final byte eofSignal) {
    this.log = LoggerFactory.getLogger(getClass());
    this.channel = channel;
    this.eofSignal = eofSignal;
}
 
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: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithAsyncStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);

    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 (ChannelShell channel = session.createShellChannel()) {
            channel.setStreaming(ClientChannel.Streaming.Async);
            channel.open().verify(5L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789\n";
                final byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
                final int nbMessages = 500;
                IoOutputStream output = channel.getAsyncIn();
                IoInputStream input = channel.getAsyncOut();
                for (int i = 0; i < nbMessages; i++) {
                    Buffer buffer = new ByteArrayBuffer(bytes);
                    output.write(buffer).verify(5L, TimeUnit.SECONDS);

                    waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                    Buffer buf = new ByteArrayBuffer(16);
                    IoReadFuture future = input.read(buf);
                    future.verify(5L, TimeUnit.SECONDS);
                    assertEquals("Mismatched available data at line #" + i, message.length(), buf.available());
                    assertEquals("Mismatched data at line #" + i, message, new String(buf.array(), buf.rpos(), buf.available()));

                    waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                    waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #15
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithAsyncStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);

    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 (ChannelShell channel = session.createShellChannel()) {
            channel.setStreaming(ClientChannel.Streaming.Async);
            channel.open().verify(5L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789\n";
                final byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
                final int nbMessages = 500;
                IoOutputStream output = channel.getAsyncIn();
                IoInputStream input = channel.getAsyncOut();
                for (int i = 0; i < nbMessages; i++) {
                    Buffer buffer = new ByteArrayBuffer(bytes);
                    output.write(buffer).verify(5L, TimeUnit.SECONDS);

                    waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                    Buffer buf = new ByteArrayBuffer(16);
                    IoReadFuture future = input.read(buf);
                    future.verify(5L, TimeUnit.SECONDS);
                    assertEquals("Mismatched available data at line #" + i, message.length(), buf.available());
                    assertEquals("Mismatched data at line #" + i, message, new String(buf.array(), buf.rpos(), buf.available()));

                    waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                    waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #16
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 #17
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 #18
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;
}
 
Example #19
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public ClientChannel createChannel(String type) throws IOException {
    throw new RuntimeException("Not implemented");
}
 
Example #20
Source File: MockClientSession.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public ClientChannel createChannel(String type, String subType) throws IOException {
    throw new RuntimeException("Not implemented");
}
 
Example #21
Source File: MockSftpClient.java    From xenon with Apache License 2.0 4 votes vote down vote up
@Override
public ClientChannel getClientChannel() {
    return null;
}
 
Example #22
Source File: WindowAdjustTest.java    From termd with Apache License 2.0 4 votes vote down vote up
VerifyingOutputStream(ClientChannel channel, final byte eofSignal) {
    this.log = LoggerFactory.getLogger(getClass());
    this.channel = channel;
    this.eofSignal = eofSignal;
}