Search in sources :

Example 1 with ClientChannel

use of org.apache.sshd.client.channel.ClientChannel in project gitblit by gitblit.

the class SshUnitTest method testSshCommand.

protected String testSshCommand(String cmd, String stdin) throws IOException, InterruptedException {
    SshClient client = getClient();
    ClientSession session = client.connect(username, "localhost", GitBlitSuite.sshPort).await().getSession();
    session.addPublicKeyIdentity(rwKeyPair);
    assertTrue(session.auth().await().isSuccess());
    ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_EXEC, cmd);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (stdin != null) {
        Writer w = new OutputStreamWriter(baos);
        w.write(stdin);
        w.close();
    }
    channel.setIn(new ByteArrayInputStream(baos.toByteArray()));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    channel.setOut(out);
    channel.setErr(err);
    channel.open();
    channel.waitFor(ClientChannel.CLOSED, 0);
    String result = out.toString().trim();
    channel.close(false);
    client.stop();
    return result;
}
Also used : SshClient(org.apache.sshd.client.SshClient) ByteArrayInputStream(java.io.ByteArrayInputStream) ClientSession(org.apache.sshd.client.session.ClientSession) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) ClientChannel(org.apache.sshd.client.channel.ClientChannel)

Example 2 with ClientChannel

use of org.apache.sshd.client.channel.ClientChannel 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;
                }
            });
        }
        setupAgent(config.getUser(), config.getKeyFile(), client, passwordProvider);
        client.getProperties().put(FactoryManager.IDLE_TIMEOUT, String.valueOf(config.getIdleTimeout()));
        // TODO: remove the line below when SSHD-732 is fixed
        client.setKeyPairProvider(new FileKeyPairProvider());
        client.start();
        if (console != null) {
            console.printf("Logging in as %s\n", config.getUser());
        }
        ClientSession session = connectWithRetries(client, config);
        if (config.getPassword() != null) {
            session.addPasswordIdentity(config.getPassword());
        }
        session.auth().verify();
        int exitStatus = 0;
        try (Terminal terminal = TerminalBuilder.terminal()) {
            Attributes attributes = terminal.enterRawMode();
            try {
                ClientChannel channel;
                if (config.getCommand().length() > 0) {
                    ChannelExec exec = session.createExecChannel(config.getCommand() + "\n");
                    channel = exec;
                    channel.setIn(new ByteArrayInputStream(new byte[0]));
                    exec.setAgentForwarding(true);
                } else {
                    ChannelShell shell = session.createShellChannel();
                    channel = shell;
                    channel.setIn(new NoCloseInputStream(terminal.input()));
                    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));
                    shell.setPtyModes(modes);
                    shell.setPtyColumns(terminal.getWidth());
                    shell.setPtyLines(terminal.getHeight());
                    shell.setAgentForwarding(true);
                    String ctype = System.getenv("LC_CTYPE");
                    if (ctype == null) {
                        ctype = Locale.getDefault().toString() + "." + System.getProperty("input.encoding", Charset.defaultCharset().name());
                    }
                    shell.setEnv("LC_CTYPE", ctype);
                }
                channel.setOut(terminal.output());
                channel.setErr(terminal.output());
                channel.open().verify();
                if (channel instanceof PtyCapableChannelSession) {
                    registerSignalHandler(terminal, (PtyCapableChannelSession) channel);
                }
                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
                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) 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) PtyCapableChannelSession(org.apache.sshd.client.channel.PtyCapableChannelSession) InputStreamReader(java.io.InputStreamReader) PtyMode(org.apache.sshd.common.channel.PtyMode) Terminal(org.jline.terminal.Terminal) FileInputStream(java.io.FileInputStream) ChannelExec(org.apache.sshd.client.channel.ChannelExec) ClientChannel(org.apache.sshd.client.channel.ClientChannel) 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)

Example 3 with ClientChannel

use of org.apache.sshd.client.channel.ClientChannel in project karaf by apache.

the class SshAction method execute.

@Override
public Object execute() throws Exception {
    if (hostname.indexOf('@') >= 0) {
        if (username == null) {
            username = hostname.substring(0, hostname.indexOf('@'));
        }
        hostname = hostname.substring(hostname.indexOf('@') + 1, hostname.length());
    }
    System.out.println("Connecting to host " + hostname + " on port " + port);
    // If not specified, assume the current user name
    if (username == null) {
        username = (String) this.session.get("USER");
    }
    // If the username was not configured via cli, then prompt the user for the values
    if (username == null) {
        log.debug("Prompting user for login");
        if (username == null) {
            username = session.readLine("Login: ", null);
        }
    }
    SshClient client = SshClient.setUpDefaultClient();
    if (this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME) != null) {
        client.setAgentFactory(KarafAgentFactory.getInstance());
        String agentSocket = this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME).toString();
        client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, agentSocket);
    }
    KnownHostsManager knownHostsManager = new KnownHostsManager(new File(System.getProperty("user.home"), ".sshkaraf/known_hosts"));
    ServerKeyVerifier serverKeyVerifier = new ServerKeyVerifierImpl(knownHostsManager, quiet);
    client.setServerKeyVerifier(serverKeyVerifier);
    client.setKeyPairProvider(new FileKeyPairProvider());
    log.debug("Created client: {}", client);
    client.setUserInteraction(new UserInteraction() {

        @Override
        public void welcome(ClientSession session, 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++) {
                    answers[i] = session.readLine(prompt[i] + " ", echo[i] ? null : '*');
                }
            } catch (IOException e) {
            }
            return answers;
        }

        @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;
        }
    });
    client.start();
    try {
        ClientSession sshSession = connectWithRetries(client, username, hostname, port, retries);
        Object oldIgnoreInterrupts = this.session.get(Session.IGNORE_INTERRUPTS);
        try {
            if (password != null) {
                sshSession.addPasswordIdentity(password);
            }
            sshSession.auth().verify();
            System.out.println("Connected");
            this.session.put(Session.IGNORE_INTERRUPTS, Boolean.TRUE);
            StringBuilder sb = new StringBuilder();
            if (command != null) {
                for (String cmd : command) {
                    if (sb.length() > 0) {
                        sb.append(' ');
                    }
                    sb.append(cmd);
                }
            }
            if (sb.length() > 0) {
                ClientChannel channel = sshSession.createChannel("exec", sb.append("\n").toString());
                channel.setIn(new ByteArrayInputStream(new byte[0]));
                channel.setOut(new NoCloseOutputStream(System.out));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open().verify();
                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
            } else if (session.getTerminal() != null) {
                final ChannelShell channel = sshSession.createShellChannel();
                final org.jline.terminal.Terminal jlineTerminal = (org.jline.terminal.Terminal) session.get(".jline.terminal");
                Attributes attributes = jlineTerminal.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(getTermWidth());
                    channel.setPtyLines(getTermHeight());
                    channel.setAgentForwarding(true);
                    channel.setEnv("TERM", session.getTerminal().getType());
                    Object ctype = session.get("LC_CTYPE");
                    if (ctype != null) {
                        channel.setEnv("LC_CTYPE", ctype.toString());
                    }
                    channel.setIn(new NoCloseInputStream(jlineTerminal.input()));
                    channel.setOut(new NoCloseOutputStream(jlineTerminal.output()));
                    channel.setErr(new NoCloseOutputStream(jlineTerminal.output()));
                    channel.open().verify();
                    SignalListener signalListener = signal -> {
                        try {
                            Size size = jlineTerminal.getSize();
                            channel.sendWindowChange(size.getColumns(), size.getRows());
                        } catch (IOException e) {
                        }
                    };
                    session.getTerminal().addSignalListener(signalListener, Signal.WINCH);
                    try {
                        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
                    } finally {
                        session.getTerminal().removeSignalListener(signalListener);
                    }
                } finally {
                    jlineTerminal.setAttributes(attributes);
                }
            } else {
                throw new IllegalStateException("No terminal for interactive ssh session");
            }
        } finally {
            session.put(Session.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
            sshSession.close(false);
        }
    } finally {
        client.stop();
    }
    return null;
}
Also used : SshClient(org.apache.sshd.client.SshClient) Size(org.jline.terminal.Size) Attributes(org.jline.terminal.Attributes) ChannelShell(org.apache.sshd.client.channel.ChannelShell) ClientSession(org.apache.sshd.client.session.ClientSession) ServerKeyVerifier(org.apache.sshd.client.keyverifier.ServerKeyVerifier) IOException(java.io.IOException) Terminal(org.apache.karaf.shell.api.console.Terminal) ClientChannel(org.apache.sshd.client.channel.ClientChannel) FileKeyPairProvider(org.apache.sshd.common.keyprovider.FileKeyPairProvider) NoCloseInputStream(org.apache.sshd.common.util.io.NoCloseInputStream) SignalListener(org.apache.karaf.shell.api.console.SignalListener) ByteArrayInputStream(java.io.ByteArrayInputStream) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction) File(java.io.File) NoCloseOutputStream(org.apache.sshd.common.util.io.NoCloseOutputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with ClientChannel

use of org.apache.sshd.client.channel.ClientChannel in project tesb-studio-se by Talend.

the class RuntimeClient method connect.

public void connect(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());
    }
    SshClient client = ClientBuilder.builder().build();
    // setupAgent(config.getUser(), config.getKeyFile(), client);
    // client.getProperties().put(FactoryManager.IDLE_TIMEOUT, String.valueOf(config.getIdleTimeout()));
    final Console console = System.console();
    if (console != null) {
        client.setUserInteraction(new UserInteraction() {

            @Override
            public void welcome(ClientSession s, String banner, String lang) {
                System.err.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;
            }
        });
    }
    client.start();
    ClientSession session = connectWithRetries(client, config);
    if (config.getPassword() != null) {
        session.addPasswordIdentity(config.getPassword());
    }
    session.auth().verify();
    int exitStatus = 0;
    Terminal terminal = TerminalBuilder.terminal();
    Attributes attributes = terminal.enterRawMode();
    IOConsoleOutputStream outputStream = RuntimeConsoleUtil.getOutputStream();
    try {
        ClientChannel channel;
        if (config.getCommand().length() > 0) {
            channel = session.createChannel("exec", config.getCommand() + "\n");
            channel.setIn(new ByteArrayInputStream(new byte[0]));
        } else {
            ChannelShell shell = session.createShellChannel();
            channel = shell;
            channel.setIn(new NoCloseInputStream(inputStream));
            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));
            shell.setPtyModes(modes);
            shell.setPtyColumns(terminal.getWidth());
            shell.setPtyLines(terminal.getHeight());
            shell.setAgentForwarding(true);
            String ctype = System.getenv("LC_CTYPE");
            if (ctype == null) {
                ctype = Locale.getDefault().toString() + "." + System.getProperty("input.encoding", Charset.defaultCharset().name());
            }
            shell.setEnv("LC_CTYPE", ctype);
        }
        channel.setOut(outputStream);
        channel.setErr(outputStream);
        channel.open().verify();
        if (channel instanceof PtyCapableChannelSession) {
            registerSignalHandler(terminal, (PtyCapableChannelSession) channel);
        }
        connected = true;
        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
        if (channel.getExitStatus() != null) {
            exitStatus = channel.getExitStatus();
        }
        channel.close();
    } finally {
        terminal.setAttributes(attributes);
        client.stop();
        client.close();
        connected = false;
        if (!outputStream.isClosed()) {
            outputStream.close();
        }
    }
}
Also used : SshClient(org.apache.sshd.client.SshClient) IOConsoleOutputStream(org.eclipse.ui.console.IOConsoleOutputStream) HashMap(java.util.HashMap) 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) ClientConfig(org.apache.karaf.client.ClientConfig) PtyCapableChannelSession(org.apache.sshd.client.channel.PtyCapableChannelSession) InputStreamReader(java.io.InputStreamReader) PtyMode(org.apache.sshd.common.channel.PtyMode) Terminal(org.jline.terminal.Terminal) FileInputStream(java.io.FileInputStream) ClientChannel(org.apache.sshd.client.channel.ClientChannel) NoCloseInputStream(com.sun.xml.internal.ws.util.NoCloseInputStream) IOError(java.io.IOError) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction)

Example 5 with ClientChannel

use of org.apache.sshd.client.channel.ClientChannel in project karaf by apache.

the class ClientMojo method execute.

protected void execute(String cmd) throws MojoExecutionException {
    SshClient client = null;
    try {
        final Console console = System.console();
        client = SshClient.setUpDefaultClient();
        setupAgent(user, keyFile, client);
        client.setUserInteraction(new UserInteraction() {

            @Override
            public void welcome(ClientSession s, String banner, String lang) {
                console.printf(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 (console != null) {
                            if (echo[i]) {
                                answers[i] = console.readLine(prompt[i] + " ");
                            } else {
                                answers[i] = new String(console.readPassword(prompt[i] + " "));
                            }
                        }
                    }
                } catch (IOError e) {
                }
                return answers;
            }

            @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;
            }
        });
        client.start();
        if (console != null) {
            console.printf("Logging in as %s\n", user);
        }
        ClientSession session = connect(client);
        if (password != null) {
            session.addPasswordIdentity(password);
        }
        session.auth().verify();
        final ClientChannel channel = session.createChannel("exec", cmd.concat(NEW_LINE));
        channel.setIn(new ByteArrayInputStream(new byte[0]));
        final ByteArrayOutputStream sout = new ByteArrayOutputStream();
        final ByteArrayOutputStream serr = new ByteArrayOutputStream();
        channel.setOut(AnsiConsole.wrapOutputStream(sout));
        channel.setErr(AnsiConsole.wrapOutputStream(serr));
        channel.open();
        channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
        sout.writeTo(System.out);
        serr.writeTo(System.err);
        // Expects issue KARAF-2623 is fixed
        final boolean isError = (channel.getExitStatus() != null && channel.getExitStatus().intValue() != 0);
        if (isError) {
            final String errorMarker = Ansi.ansi().fg(Color.RED).toString();
            final int fromIndex = sout.toString().indexOf(errorMarker) + errorMarker.length();
            final int toIndex = sout.toString().lastIndexOf(Ansi.ansi().fg(Color.DEFAULT).toString());
            throw new MojoExecutionException(NEW_LINE + sout.toString().substring(fromIndex, toIndex));
        }
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Throwable t) {
        throw new MojoExecutionException(t, t.getMessage(), t.toString());
    } finally {
        try {
            client.stop();
        } catch (Throwable t) {
            throw new MojoExecutionException(t, t.getMessage(), t.toString());
        }
    }
}
Also used : SshClient(org.apache.sshd.client.SshClient) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ClientChannel(org.apache.sshd.client.channel.ClientChannel) IOError(java.io.IOError) ByteArrayInputStream(java.io.ByteArrayInputStream) ClientSession(org.apache.sshd.client.session.ClientSession) Console(java.io.Console) AnsiConsole(org.fusesource.jansi.AnsiConsole) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction)

Aggregations

ByteArrayInputStream (java.io.ByteArrayInputStream)6 SshClient (org.apache.sshd.client.SshClient)6 ClientChannel (org.apache.sshd.client.channel.ClientChannel)6 ClientSession (org.apache.sshd.client.session.ClientSession)6 UserInteraction (org.apache.sshd.client.auth.keyboard.UserInteraction)5 Console (java.io.Console)4 IOError (java.io.IOError)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 HashMap (java.util.HashMap)3 ChannelShell (org.apache.sshd.client.channel.ChannelShell)3 Attributes (org.jline.terminal.Attributes)3 BufferedReader (java.io.BufferedReader)2 FileInputStream (java.io.FileInputStream)2 InputStreamReader (java.io.InputStreamReader)2 Reader (java.io.Reader)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 PtyCapableChannelSession (org.apache.sshd.client.channel.PtyCapableChannelSession)2 PtyMode (org.apache.sshd.common.channel.PtyMode)2 FileKeyPairProvider (org.apache.sshd.common.keyprovider.FileKeyPairProvider)2 NoCloseInputStream (org.apache.sshd.common.util.io.NoCloseInputStream)2