Package org.apache.sshd

Examples of org.apache.sshd.SshClient


    if (state != SshConnectionState.NotConnected) {
      throw new IllegalStateException();
    }

    try {
      SshClient client = sshContext.client;

      System.out.println("New SSH connection to " + connectionInfo.getHost());

      ConnectFuture connect = client.connect(connectionInfo.getSocketAddress());
      if (!connect.await(connectTimeout.getTotalMilliseconds())) {
        connect.cancel();
        throw new SshException("Timeout while waiting for SSH connection to " + connectionInfo.getHost());
      }
View Full Code Here


        System.getProperties().remove("openejb.server.ssh.key");
    }

    @Test(timeout = 10000L)
    public void call() throws Exception {
        final SshClient client = SshClient.setUpDefaultClient();
        client.start();
        try {
            final ClientSession session = client.connect("localhost", 4222).await().getSession();
            session.authPassword("jonathan", "secret");

            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(ClientChannel.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();
View Full Code Here

        File serverDir = new File("target/git/pgm");
        Utils.deleteRecursive(serverDir);

        File repo = new File(serverDir, "test");

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

        ClientSession session = client.connect("sshd", "localhost", 8001).await().getSession();
        session.addPasswordIdentity("sshd");
        session.auth().verify();

        Git.init().setDirectory(repo).call();
        Git git = Git.open(repo);
        git.commit().setMessage("First Commit").setCommitter("sshd", "sshd@apache.org").call();

        new File("target/git/pgm/test/readme.txt").createNewFile();
        execute(session, "git --git-dir test add readme.txt");

        execute(session, "git --git-dir test commit -m \"readme\"");

        client.stop();
        sshd.stop();
    }
View Full Code Here

                password = readLine("Password: ");
            }
        }

        // Create the client from prototype
        SshClient client = (SshClient) container.getComponentInstance(sshClientId);
        log.debug("Created client: {}", client);
        client.start();

        try {
            ConnectFuture future = client.connect(hostname, port);
            future.await();
            sshSession = future.getSession();

            Object oldIgnoreInterrupts = this.session.get(Console.IGNORE_INTERRUPTS);
            this.session.put( Console.IGNORE_INTERRUPTS, Boolean.TRUE );

            try {
                System.out.println("Connected");

                sshSession.authPassword(username, password);
                int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                if ((ret & ClientSession.AUTHED) == 0) {
                    System.err.println("Authentication failed");
                    return null;
                }

                StringBuilder sb = new StringBuilder();
                if (command != null) {
                    for (String cmd : command) {
                        if (sb.length() > 0) {
                            sb.append(' ');
                        }
                        sb.append(cmd);
                    }
                }

                ClientChannel channel;
                if (sb.length() > 0) {
                    channel = sshSession.createChannel("exec", sb.append("\n").toString());
                    channel.setIn(new ByteArrayInputStream(new byte[0]));
                } else {
                    channel = sshSession.createChannel("shell");
                    channel.setIn(new NoCloseInputStream(System.in));
                    ((ChannelShell) channel).setPtyColumns(getTermWidth());
                    ((ChannelShell) channel).setupSensibleDefaultPty();
                    Object ctype = session.get("LC_CTYPE");
                    if (ctype != null) {
                        ((ChannelShell) channel).setEnv("LC_CTYPE", ctype.toString());
                    }
                }
                channel.setOut(new NoCloseOutputStream(System.out));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open();
                channel.waitFor(ClientChannel.CLOSED, 0);
            } finally {
                session.put( Console.IGNORE_INTERRUPTS, oldIgnoreInterrupts );
                sshSession.close(false);
            }
        } finally {
            client.stop();
        }

        return null;
    }
View Full Code Here

                sb.append(' ');
            }
        }
        SimpleLogger.setLevel(level);

        SshClient client = null;
        Terminal terminal = null;
        try {
            client = SshClient.setUpDefaultClient();
            client.start();
            int retries = 0;
            ClientSession session = null;
            do {
                ConnectFuture future = client.connect(host, port);
                future.await();
                try {
                    session = future.getSession();
                } catch (RuntimeSshException ex) {
                    if (retries++ < retryAttempts) {
                        Thread.sleep(retryDelay * 1000);
                        System.out.println("retrying (attempt " + retries + ") ...");
                    } else {
                        throw ex;
                    }
                }
            } while (session == null);
            if (!session.authPassword(user, password).await().isSuccess()) {
                throw new Exception("Authentication failure");
            }
            ClientChannel channel;
      if (sb.length() > 0) {
                channel = session.createChannel("exec", sb.append("\n").toString());
                channel.setIn(new ByteArrayInputStream(new byte[0]));
      } else {
                terminal = new TerminalFactory().getTerminal();
         channel = session.createChannel("shell");
                ConsoleInputStream in = new ConsoleInputStream(terminal.wrapInIfNeeded(System.in));
                new Thread(in).start();
                channel.setIn(in);
                ((ChannelShell) channel).setupSensibleDefaultPty();
                String ctype = System.getenv("LC_CTYPE");
                if (ctype == null) {
                    ctype = Locale.getDefault().toString() + "."
                                + System.getProperty("input.encoding", Charset.defaultCharset().name());
                }
                ((ChannelShell) channel).setEnv("LC_CTYPE", ctype);
            }
            channel.setOut(AnsiConsole.wrapOutputStream(System.out));
            channel.setErr(AnsiConsole.wrapOutputStream(System.err));
            channel.open();
            channel.waitFor(ClientChannel.CLOSED, 0);
        } catch (Throwable t) {
            if (level > 1) {
                t.printStackTrace();
            } else {
                System.err.println(t.getMessage());
            }
            System.exit(1);
        } finally {
            try {
                client.stop();
            } catch (Throwable t) { }
            try {
                if (terminal != null) {
                    terminal.restore();
                }
View Full Code Here

                password = readLine("Password: ");
            }
        }

        // Create the client from prototype
        SshClient client = (SshClient) container.getComponentInstance(sshClientId);
        log.debug("Created client: {}", client);
        client.start();

        try {
            ConnectFuture future = client.connect(hostname, port);
            future.await();
            sshSession = future.getSession();

            Object oldIgnoreInterrupts = this.session.get(Console.IGNORE_INTERRUPTS);
            this.session.put( Console.IGNORE_INTERRUPTS, Boolean.TRUE );

            try {
                System.out.println("Connected");

                sshSession.authPassword(username, password);
                int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                if ((ret & ClientSession.AUTHED) == 0) {
                    System.err.println("Authentication failed");
                    return null;
                }

                StringBuilder sb = new StringBuilder();
                if (command != null) {
                    for (String cmd : command) {
                        if (sb.length() > 0) {
                            sb.append(' ');
                        }
                        sb.append(cmd);
                    }
                }

                ClientChannel channel;
                if (sb.length() > 0) {
                    channel = sshSession.createChannel("exec", sb.append("\n").toString());
                    channel.setIn(new ByteArrayInputStream(new byte[0]));
                } else {
                    channel = sshSession.createChannel("shell");
                    channel.setIn(new NoCloseInputStream(System.in));
                    ((ChannelShell) channel).setPtyColumns(getTermWidth());
                    ((ChannelShell) channel).setupSensibleDefaultPty();
                }
                channel.setOut(new NoCloseOutputStream(System.out));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open();
                channel.waitFor(ClientChannel.CLOSED, 0);
            } finally {
                session.put( Console.IGNORE_INTERRUPTS, oldIgnoreInterrupts );
                sshSession.close(false);
            }
        } finally {
            client.stop();
        }

        return null;
    }
View Full Code Here

    this.agentFactory = agentFactory;
    this.knownHosts = knownHosts;
  }

  public SshClient create(boolean quiet) {
    SshClient client = SshClient.setUpDefaultClient();
        client.setAgentFactory(agentFactory);
        KnownHostsManager knownHostsManager = new KnownHostsManager(knownHosts);
    ServerKeyVerifier serverKeyVerifier = new ServerKeyVerifierImpl(knownHostsManager, quiet);
    client.setServerKeyVerifier(serverKeyVerifier );
    return client;
  }
View Full Code Here

            if (username == null) {
                username = readLine("Login: ");
            }
        }

        SshClient client = sshClientFactory.create(quiet);
        log.debug("Created client: {}", client);
        client.start();

        String agentSocket = null;
        if (this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME) != null) {
            agentSocket = this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME).toString();
            client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME,agentSocket);
        }

        try {
            ConnectFuture future = client.connect(hostname, port);
            future.await();
            sshSession = future.getSession();

            Object oldIgnoreInterrupts = this.session.get(SessionProperties.IGNORE_INTERRUPTS);

            try {

                boolean authed = false;
                if (agentSocket != null) {
                    try {
                        sshSession.authAgent(username);
                    } catch (IllegalStateException ise) {
                        System.err.println(keyChangedMessage);
                        return null;
                    }
                    int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                    if ((ret & ClientSession.AUTHED) == 0) {
                        System.err.println("Agent authentication failed, falling back to password authentication.");
                    } else {
                        authed = true;
                    }
                }
                if (!authed) {
                    if (password == null) {
                        log.debug("Prompting user for password");
                        password = readLine("Password: ");
                    } else {
                        log.debug("Password provided using command line option");
                    }
                    try {
                        sshSession.authPassword(username, password);
                    } catch (IllegalStateException ise) {
                        System.err.println(keyChangedMessage);
                        return null;
                    }
                    int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                    if ((ret & ClientSession.AUTHED) == 0) {
                        System.err.println("Password authentication failed");
                    } else {
                        authed = true;
                    }
                }
                if (!authed) {
                    return null;
                }

                System.out.println("Connected");
                this.session.put( SessionProperties.IGNORE_INTERRUPTS, Boolean.TRUE );

                StringBuilder sb = new StringBuilder();
                if (command != null) {
                    for (String cmd : command) {
                        if (sb.length() > 0) {
                            sb.append(' ');
                        }
                        sb.append(cmd);
                    }
                }

                ClientChannel channel;
                if (sb.length() > 0) {
                    channel = sshSession.createChannel("exec", sb.append("\n").toString());
                    channel.setIn(new ByteArrayInputStream(new byte[0]));
                } else {
                    channel = sshSession.createChannel("shell");
                    channel.setIn(new NoCloseInputStream(System.in));
                    ((ChannelShell) channel).setPtyColumns(getTermWidth());
                    ((ChannelShell) channel).setupSensibleDefaultPty();
                    ((ChannelShell) channel).setAgentForwarding(true);
                    Object ctype = session.get("LC_CTYPE");
                    if (ctype != null) {
                        ((ChannelShell) channel).setEnv("LC_CTYPE", ctype.toString());
                    }
                }
                channel.setOut(new NoCloseOutputStream(System.out));
                channel.setErr(new NoCloseOutputStream(System.err));
                channel.open();
                channel.waitFor(ClientChannel.CLOSED, 0);
            } finally {
                session.put( SessionProperties.IGNORE_INTERRUPTS, oldIgnoreInterrupts );
                sshSession.close(false);
            }
        } finally {
            client.stop();
        }

        return null;
    }
View Full Code Here

                sb.append((char) c);
            }
            config.setCommand(sb.toString());
        }

        SshClient client = null;
        Terminal terminal = null;
        int exitStatus = 0;
        try {
            client = SshClient.setUpDefaultClient();
            setupAgent(config.getUser(), client);
            client.start();
            ClientSession session = connectWithRetries(client, config);
            Console console = System.console();
            if (console != null) {
                console.printf("Logging in as %s\n", config.getUser());
            }
            if (!session.authAgent(config.getUser()).await().isSuccess()) {
                AuthFuture authFuture;
                boolean useDefault = config.getPassword() != null;
                do {
                    String password;
                    if (useDefault) {
                        password = config.getPassword();
                        useDefault = false;
                    } else {
                        if (console != null) {
                            char[] readPassword = console.readPassword("Password: ");
                            if (readPassword != null) {
                                password = new String(readPassword);
                            } else {
                                return;
                            }
                        } else {
                            throw new Exception("Unable to prompt password: could not get system console");
                        }
                    }
                    authFuture = session.authPassword(config.getUser(), password);
                } while (authFuture.await().isFailure());
                if (!authFuture.isSuccess()) {
                    throw new Exception("Authentication failure");
                }
            }
            ClientChannel channel;
            if (config.getCommand().length() > 0) {
                channel = session.createChannel("exec", config.getCommand() + "\n");
                channel.setIn(new ByteArrayInputStream(new byte[0]));
            } else {
                TerminalFactory.registerFlavor(TerminalFactory.Flavor.UNIX, NoInterruptUnixTerminal.class);
                terminal = TerminalFactory.create();
                channel = session.createChannel("shell");
                ConsoleInputStream in = new ConsoleInputStream(terminal.wrapInIfNeeded(System.in));
                new Thread(in).start();
                channel.setIn(in);
                ((ChannelShell) channel).setPtyColumns(terminal != null ? terminal.getWidth() : 80);
                ((ChannelShell) channel).setupSensibleDefaultPty();
                ((ChannelShell) channel).setAgentForwarding(true);
                String ctype = System.getenv("LC_CTYPE");
                if (ctype == null) {
                    ctype = Locale.getDefault().toString() + "."
                            + System.getProperty("input.encoding", Charset.defaultCharset().name());
                }
                ((ChannelShell) channel).setEnv("LC_CTYPE", ctype);
            }
            channel.setOut(AnsiConsole.wrapOutputStream(System.out));
            channel.setErr(AnsiConsole.wrapOutputStream(System.err));
            channel.open();
            channel.waitFor(ClientChannel.CLOSED, 0);
            if (channel.getExitStatus() != null) {
                exitStatus = channel.getExitStatus();
            }
        } catch (Throwable t) {
            if (config.getLevel() > SimpleLogger.WARN) {
                t.printStackTrace();
            } else {
                System.err.println(t.getMessage());
            }
            System.exit(1);
        } finally {
            try {
                client.stop();
            } catch (Throwable t) {
            }
            try {
                if (terminal != null) {
                    terminal.restore();
View Full Code Here

            for (int c = reader.read(); c >= 0; c = reader.read()) {
                command.append((char) c);
            }
        }

        SshClient client = null;
        Terminal terminal = null;
        SshAgent agent = null;
        int exitStatus = 0;
        try {

            final Console console = System.console();
            client = SshClient.setUpDefaultClient();
            setupAgent(user, client, keyFile);
            client.setUserInteraction(new UserInteraction() {
                public void welcome(String banner) {
                    System.out.println(banner);
                }

                public String[] interactive(String destination, String name, String instruction, 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;
                }
            });
            client.start();
            if (console != null) {
                console.printf("Logging in as %s\n", user);
            }
           
            ClientSession session = null;
            int retries = 0;
            do {
                ConnectFuture future = client.connect(user, host, port);
                future.await();
                try {
                    session = future.getSession();
                } catch (RuntimeSshException ex) {
                    if (retries++ < retryAttempts) {
                        Thread.sleep(retryDelay * 1000);
                        System.out.println("retrying (attempt " + retries + ") ...");
                    } else {
                        throw ex;
                    }
                }
            } while (session == null);
           
           
            if (password != null) {
                session.addPasswordIdentity(password);
            }
            session.auth().verify();

            ClientChannel channel;
      if (command.length() > 0) {
                channel = session.createChannel("exec", command.append("\n").toString());
                channel.setIn(new ByteArrayInputStream(new byte[0]));
      } else {
                terminal = new TerminalFactory().getTerminal();
         channel = session.createChannel("shell");
                ConsoleInputStream in = new ConsoleInputStream(terminal.wrapInIfNeeded(System.in));
                new Thread(in).start();
                channel.setIn(in);
                ((ChannelShell) channel).setPtyColumns(terminal != null ? terminal.getWidth() : 80);
                ((ChannelShell) channel).setupSensibleDefaultPty();
                ((ChannelShell) channel).setAgentForwarding(true);
                String ctype = System.getenv("LC_CTYPE");
                if (ctype == null) {
                    ctype = Locale.getDefault().toString() + "."
                                + System.getProperty("input.encoding", Charset.defaultCharset().name());
                }
                ((ChannelShell) channel).setEnv("LC_CTYPE", ctype);
            }
            channel.setOut(AnsiConsole.wrapOutputStream(System.out));
            channel.setErr(AnsiConsole.wrapOutputStream(System.err));
            channel.open();
            channel.waitFor(ClientChannel.CLOSED, 0);
            if (channel.getExitStatus() != null) {
                exitStatus = channel.getExitStatus();
            }
        } catch (Throwable t) {
            if (level > 1) {
                t.printStackTrace();
            } else {
                System.err.println(t.getMessage());
            }
            System.exit(1);
        } finally {
            try {
                client.stop();
            } catch (Throwable t) { }
            try {
                if (terminal != null) {
                    terminal.restore();
                }
View Full Code Here

TOP

Related Classes of org.apache.sshd.SshClient

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.