Search in sources :

Example 1 with ClientSession

use of org.apache.sshd.client.session.ClientSession in project karaf by apache.

the class Main method connectWithRetries.

private static ClientSession connectWithRetries(SshClient client, ClientConfig config) throws Exception {
    ClientSession session = null;
    int retries = 0;
    do {
        ConnectFuture future = client.connect(config.getUser(), config.getHost(), config.getPort());
        future.await();
        try {
            session = future.getSession();
        } catch (RuntimeSshException ex) {
            if (retries++ < config.getRetryAttempts()) {
                Thread.sleep(config.getRetryDelay() * 1000);
                System.out.println("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 2 with ClientSession

use of org.apache.sshd.client.session.ClientSession in project karaf by apache.

the class DeployMojo 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 3 with ClientSession

use of org.apache.sshd.client.session.ClientSession in project karaf by apache.

the class SshAction method connectWithRetries.

private static ClientSession connectWithRetries(SshClient client, String username, String host, int port, int maxAttempts) throws Exception {
    ClientSession session = null;
    int retries = 0;
    do {
        ConnectFuture future = client.connect(username, host, port);
        future.await();
        try {
            session = future.getSession();
        } catch (Exception ex) {
            if (retries++ < maxAttempts) {
                Thread.sleep(2 * 1000);
                System.out.println("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) IOException(java.io.IOException)

Example 4 with ClientSession

use of org.apache.sshd.client.session.ClientSession in project karaf by apache.

the class SshKeyFormatTest method usePemKey.

@Test
public void usePemKey() throws Exception {
    SshClient client = SshClient.setUpDefaultClient();
    URL testPemURL = Resources.getResource(SshKeyFormatTest.class, "test.pem");
    ByteSource source = Resources.asByteSource(testPemURL);
    PKCS8Key pkcs8 = new PKCS8Key(source.openStream(), null);
    String sshPort = getSshPort();
    client.setServerKeyVerifier(new RequiredServerKeyVerifier(pkcs8.getPublicKey()));
    client.start();
    ConnectFuture future = client.connect("karaf", "localhost", Integer.parseInt(sshPort));
    future.await();
    ClientSession session = future.getSession();
    Set<ClientSessionEvent> ret = EnumSet.of(ClientSessionEvent.WAIT_AUTH);
    while (ret.contains(ClientSessionEvent.WAIT_AUTH)) {
        session.addPasswordIdentity("karaf");
        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");
    }
    session.close(true);
}
Also used : PKCS8Key(org.apache.commons.ssl.PKCS8Key) ClientSessionEvent(org.apache.sshd.client.session.ClientSession.ClientSessionEvent) SshClient(org.apache.sshd.client.SshClient) RequiredServerKeyVerifier(org.apache.sshd.client.keyverifier.RequiredServerKeyVerifier) ClientSession(org.apache.sshd.client.session.ClientSession) ByteSource(com.google.common.io.ByteSource) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) URL(java.net.URL) Test(org.junit.Test)

Example 5 with ClientSession

use of org.apache.sshd.client.session.ClientSession in project karaf by apache.

the class Main method main.

public static void main(String[] args) throws Exception {
    ClientConfig config = new ClientConfig(args);
    SimpleLogger.setLevel(config.getLevel());
    if (config.getFile() != null) {
        StringBuilder sb = new StringBuilder();
        sb.setLength(0);
        try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(config.getFile())))) {
            for (int c = reader.read(); c >= 0; c = reader.read()) {
                sb.append((char) c);
            }
        }
        config.setCommand(sb.toString());
    } else if (config.isBatch()) {
        StringBuilder sb = new StringBuilder();
        sb.setLength(0);
        Reader reader = new BufferedReader(new InputStreamReader(System.in));
        for (int c = reader.read(); c >= 0; c = reader.read()) {
            sb.append((char) c);
        }
        config.setCommand(sb.toString());
    }
    try (SshClient client = ClientBuilder.builder().build()) {
        FilePasswordProvider passwordProvider = null;
        final Console console = System.console();
        if (console != null) {
            passwordProvider = resourceKey -> {
                char[] pwd = console.readPassword("Enter password for " + resourceKey + ": ");
                return new String(pwd);
            };
            client.setFilePasswordProvider(passwordProvider);
            client.setUserInteraction(new UserInteraction() {

                @Override
                public void welcome(ClientSession s, String banner, String lang) {
                    System.out.println(banner);
                }

                @Override
                public String[] interactive(ClientSession s, String name, String instruction, String lang, String[] prompt, boolean[] echo) {
                    String[] answers = new String[prompt.length];
                    try {
                        for (int i = 0; i < prompt.length; i++) {
                            if (echo[i]) {
                                answers[i] = console.readLine(prompt[i] + " ");
                            } else {
                                answers[i] = new String(console.readPassword(prompt[i] + " "));
                            }
                            if (answers[i] == null) {
                                return null;
                            }
                        }
                        return answers;
                    } catch (IOError e) {
                        return null;
                    }
                }

                @Override
                public boolean isInteractionAllowed(ClientSession session) {
                    return true;
                }

                @Override
                public void serverVersionInfo(ClientSession session, List<String> lines) {
                }

                @Override
                public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
                    return null;
                }
            });
        }
        if (config.getUser() == null || config.getUser().isEmpty()) {
            while (true) {
                String user = console.readLine("Enter user: ");
                if (user == null || user.isEmpty()) {
                    System.err.println("User must not be empty!");
                } else {
                    config.setUser(user);
                    break;
                }
            }
        } else if (console != null) {
            console.printf("Logging in as %s\n", config.getUser());
        }
        setupAgent(config.getUser(), config.getKeyFile(), client, passwordProvider);
        // define hearbeat (for the keep alive) and timeouts
        // TODO this should be dealt by Apache SSH client directly using .ssh/config
        client.getProperties().put(ClientFactoryManager.HEARTBEAT_INTERVAL, "60000");
        client.getProperties().put(ClientFactoryManager.IDLE_TIMEOUT, String.valueOf(config.getIdleTimeout()));
        client.getProperties().put(ClientFactoryManager.NIO2_READ_TIMEOUT, String.valueOf(config.getIdleTimeout()));
        // TODO: remove the line below when SSHD-732 is fixed
        client.setKeyPairProvider(new FileKeyPairProvider());
        client.start();
        ClientSession session = connectWithRetries(client, config);
        if (config.getPassword() != null) {
            session.addPasswordIdentity(config.getPassword());
        }
        session.auth().verify();
        int exitStatus = 0;
        try (Terminal terminal = TerminalBuilder.builder().nativeSignals(true).signalHandler(Terminal.SignalHandler.SIG_IGN).build()) {
            if (config.getCommand().length() > 0) {
                ChannelExec channel = session.createExecChannel(config.getCommand() + "\n");
                channel.setIn(new ByteArrayInputStream(new byte[0]));
                channel.setAgentForwarding(true);
                NoCloseOutputStream output = new NoCloseOutputStream(terminal.output());
                channel.setOut(output);
                channel.setErr(output);
                channel.open().verify();
                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
            } else {
                ChannelShell channel = session.createShellChannel();
                Attributes attributes = terminal.enterRawMode();
                try {
                    Map<PtyMode, Integer> modes = new HashMap<>();
                    // Control chars
                    modes.put(PtyMode.VINTR, attributes.getControlChar(ControlChar.VINTR));
                    modes.put(PtyMode.VQUIT, attributes.getControlChar(ControlChar.VQUIT));
                    modes.put(PtyMode.VERASE, attributes.getControlChar(ControlChar.VERASE));
                    modes.put(PtyMode.VKILL, attributes.getControlChar(ControlChar.VKILL));
                    modes.put(PtyMode.VEOF, attributes.getControlChar(ControlChar.VEOF));
                    modes.put(PtyMode.VEOL, attributes.getControlChar(ControlChar.VEOL));
                    modes.put(PtyMode.VEOL2, attributes.getControlChar(ControlChar.VEOL2));
                    modes.put(PtyMode.VSTART, attributes.getControlChar(ControlChar.VSTART));
                    modes.put(PtyMode.VSTOP, attributes.getControlChar(ControlChar.VSTOP));
                    modes.put(PtyMode.VSUSP, attributes.getControlChar(ControlChar.VSUSP));
                    modes.put(PtyMode.VDSUSP, attributes.getControlChar(ControlChar.VDSUSP));
                    modes.put(PtyMode.VREPRINT, attributes.getControlChar(ControlChar.VREPRINT));
                    modes.put(PtyMode.VWERASE, attributes.getControlChar(ControlChar.VWERASE));
                    modes.put(PtyMode.VLNEXT, attributes.getControlChar(ControlChar.VLNEXT));
                    modes.put(PtyMode.VSTATUS, attributes.getControlChar(ControlChar.VSTATUS));
                    modes.put(PtyMode.VDISCARD, attributes.getControlChar(ControlChar.VDISCARD));
                    // Input flags
                    modes.put(PtyMode.IGNPAR, getFlag(attributes, InputFlag.IGNPAR));
                    modes.put(PtyMode.PARMRK, getFlag(attributes, InputFlag.PARMRK));
                    modes.put(PtyMode.INPCK, getFlag(attributes, InputFlag.INPCK));
                    modes.put(PtyMode.ISTRIP, getFlag(attributes, InputFlag.ISTRIP));
                    modes.put(PtyMode.INLCR, getFlag(attributes, InputFlag.INLCR));
                    modes.put(PtyMode.IGNCR, getFlag(attributes, InputFlag.IGNCR));
                    modes.put(PtyMode.ICRNL, getFlag(attributes, InputFlag.ICRNL));
                    modes.put(PtyMode.IXON, getFlag(attributes, InputFlag.IXON));
                    modes.put(PtyMode.IXANY, getFlag(attributes, InputFlag.IXANY));
                    modes.put(PtyMode.IXOFF, getFlag(attributes, InputFlag.IXOFF));
                    // Local flags
                    modes.put(PtyMode.ISIG, getFlag(attributes, LocalFlag.ISIG));
                    modes.put(PtyMode.ICANON, getFlag(attributes, LocalFlag.ICANON));
                    modes.put(PtyMode.ECHO, getFlag(attributes, LocalFlag.ECHO));
                    modes.put(PtyMode.ECHOE, getFlag(attributes, LocalFlag.ECHOE));
                    modes.put(PtyMode.ECHOK, getFlag(attributes, LocalFlag.ECHOK));
                    modes.put(PtyMode.ECHONL, getFlag(attributes, LocalFlag.ECHONL));
                    modes.put(PtyMode.NOFLSH, getFlag(attributes, LocalFlag.NOFLSH));
                    modes.put(PtyMode.TOSTOP, getFlag(attributes, LocalFlag.TOSTOP));
                    modes.put(PtyMode.IEXTEN, getFlag(attributes, LocalFlag.IEXTEN));
                    // Output flags
                    modes.put(PtyMode.OPOST, getFlag(attributes, OutputFlag.OPOST));
                    modes.put(PtyMode.ONLCR, getFlag(attributes, OutputFlag.ONLCR));
                    modes.put(PtyMode.OCRNL, getFlag(attributes, OutputFlag.OCRNL));
                    modes.put(PtyMode.ONOCR, getFlag(attributes, OutputFlag.ONOCR));
                    modes.put(PtyMode.ONLRET, getFlag(attributes, OutputFlag.ONLRET));
                    channel.setPtyModes(modes);
                    channel.setPtyColumns(terminal.getWidth());
                    channel.setPtyLines(terminal.getHeight());
                    channel.setAgentForwarding(true);
                    channel.setEnv("TERM", terminal.getType());
                    String ctype = System.getenv("LC_CTYPE");
                    if (ctype == null) {
                        ctype = Locale.getDefault().toString() + "." + System.getProperty("input.encoding", Charset.defaultCharset().name());
                    }
                    channel.setEnv("LC_CTYPE", ctype);
                    channel.setIn(new NoCloseInputStream(terminal.input()));
                    channel.setOut(new NoCloseOutputStream(terminal.output()));
                    channel.setErr(new NoCloseOutputStream(terminal.output()));
                    channel.open().verify();
                    Terminal.SignalHandler prevWinchHandler = terminal.handle(Terminal.Signal.WINCH, signal -> {
                        try {
                            Size size = terminal.getSize();
                            channel.sendWindowChange(size.getColumns(), size.getRows());
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    Terminal.SignalHandler prevQuitHandler = terminal.handle(Terminal.Signal.QUIT, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VQUIT));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    Terminal.SignalHandler prevIntHandler = terminal.handle(Terminal.Signal.INT, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VINTR));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    Terminal.SignalHandler prevStopHandler = terminal.handle(Terminal.Signal.TSTP, signal -> {
                        try {
                            channel.getInvertedIn().write(attributes.getControlChar(Attributes.ControlChar.VDSUSP));
                            channel.getInvertedIn().flush();
                        } catch (IOException e) {
                        // Ignore
                        }
                    });
                    try {
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
                    } finally {
                        terminal.handle(Terminal.Signal.WINCH, prevWinchHandler);
                        terminal.handle(Terminal.Signal.INT, prevIntHandler);
                        terminal.handle(Terminal.Signal.TSTP, prevStopHandler);
                        terminal.handle(Terminal.Signal.QUIT, prevQuitHandler);
                    }
                    if (channel.getExitStatus() != null) {
                        exitStatus = channel.getExitStatus();
                    }
                } finally {
                    terminal.setAttributes(attributes);
                }
            }
        }
        System.exit(exitStatus);
    } catch (Throwable t) {
        if (config.getLevel() > SimpleLogger.WARN) {
            t.printStackTrace();
        } else {
            System.err.println(t.getMessage());
        }
        System.exit(1);
    }
}
Also used : SshClient(org.apache.sshd.client.SshClient) HashMap(java.util.HashMap) Size(org.jline.terminal.Size) Attributes(org.jline.terminal.Attributes) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ChannelShell(org.apache.sshd.client.channel.ChannelShell) ClientSession(org.apache.sshd.client.session.ClientSession) Console(java.io.Console) InputStreamReader(java.io.InputStreamReader) PtyMode(org.apache.sshd.common.channel.PtyMode) IOException(java.io.IOException) Terminal(org.jline.terminal.Terminal) FileInputStream(java.io.FileInputStream) ChannelExec(org.apache.sshd.client.channel.ChannelExec) FileKeyPairProvider(org.apache.sshd.common.keyprovider.FileKeyPairProvider) NoCloseInputStream(org.apache.sshd.common.util.io.NoCloseInputStream) IOError(java.io.IOError) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction) FilePasswordProvider(org.apache.sshd.common.config.keys.FilePasswordProvider) NoCloseOutputStream(org.apache.sshd.common.util.io.NoCloseOutputStream)

Aggregations

ClientSession (org.apache.sshd.client.session.ClientSession)15 SshClient (org.apache.sshd.client.SshClient)10 ConnectFuture (org.apache.sshd.client.future.ConnectFuture)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ClientChannel (org.apache.sshd.client.channel.ClientChannel)6 IOException (java.io.IOException)5 UserInteraction (org.apache.sshd.client.auth.keyboard.UserInteraction)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Console (java.io.Console)4 IOError (java.io.IOError)4 RuntimeSshException (org.apache.sshd.common.RuntimeSshException)4 HashMap (java.util.HashMap)3 ChannelShell (org.apache.sshd.client.channel.ChannelShell)3 PtyMode (org.apache.sshd.common.channel.PtyMode)3 Attributes (org.jline.terminal.Attributes)3 Test (org.junit.Test)3 BufferedReader (java.io.BufferedReader)2 FileInputStream (java.io.FileInputStream)2 InputStreamReader (java.io.InputStreamReader)2 Reader (java.io.Reader)2