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

The following examples show how to use org.apache.sshd.client.SshClient#setUpDefaultClient() . 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: NetconfSessionMinaImpl.java    From onos with Apache License 2.0 8 votes vote down vote up
private void startClient() throws IOException {
    log.info("Creating NETCONF session to {}",
            deviceInfo.getDeviceId());

    client = SshClient.setUpDefaultClient();
    if (idleTimeout != NetconfControllerImpl.netconfIdleTimeout) {
        client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT,
                TimeUnit.SECONDS.toMillis(idleTimeout));
        client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT,
                TimeUnit.SECONDS.toMillis(idleTimeout + 15L));
    }
    client.start();
    client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    startSession();

    disconnected = false;
}
 
Example 2
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 3
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static SshClient setupTestClient(Class<?> anchor) {
    SshClient client = SshClient.setUpDefaultClient();
    client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE);
    client.setHostConfigEntryResolver(HostConfigEntryResolver.EMPTY);
    client.setKeyPairProvider(KeyPairProvider.EMPTY_KEYPAIR_PROVIDER);
    return client;
}
 
Example 4
Source File: ClientImpl.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    this.client = SshClient.setUpDefaultClient();
    if (serverKeyVerifier != null) {
        client.setServerKeyVerifier(serverKeyVerifier);
    }
    this.client.start();
}
 
Example 5
Source File: SshClientSessionImpl.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public void connect() throws IOException {
    client = SshClient.setUpDefaultClient();
    client.start();
    session = client.connect(userCredentials.getUserName(),
            hostData.getHostName(), hostData.getPort()).verify().getSession();
    session.addPasswordIdentity(userCredentials.getPassword());
    session.auth().await();
}
 
Example 6
Source File: NetconfSSHClient.java    From anx with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new NETCONF connection to the given server
 *
 * The connection will not be established immediately, but instead upon creating the first session.
 *
 * @param hostname
 * @param port
 * @param username
 */
public NetconfSSHClient(String hostname, int port, String username) {
    this.hostname = hostname;
    this.port = port;
    this.username = username;

    client = SshClient.setUpDefaultClient();
    client.setSessionHeartbeat(HeartbeatType.IGNORE, TimeUnit.MILLISECONDS, 5000);
    client.start();
}
 
Example 7
Source File: Utils.java    From termd with Apache License 2.0 5 votes vote down vote up
public static SshClient setupTestClient(Class<?> anchor) {
    SshClient client = SshClient.setUpDefaultClient();
    client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE);
    client.setHostConfigEntryResolver(HostConfigEntryResolver.EMPTY);
    client.setKeyPairProvider(KeyPairProvider.EMPTY_KEYPAIR_PROVIDER);
    return client;
}
 
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: SshFtpClient.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public SshFtpClient() {
    client = SshClient.setUpDefaultClient();
    client.start();
}
 
Example 10
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 11
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 12
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;
}