Examples of SSHClient


Examples of org.apache.sshd.SshClient

            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

Examples of org.apache.sshd.SshClient

                username = readLine("Login: ");
            }
        }

        // Create the client from prototype
        SshClient client = (SshClient) container.getComponentInstance(sshClientId);

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

        try {
            ClientSession sshSession = client.connect(username, hostname, port).await().getSession();

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

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

                if (password != null) {
                    sshSession.addPasswordIdentity(password);
                }
                sshSession.auth().verify();

                this.session.put( Console.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().verify();
                channel.waitFor(ClientChannel.CLOSED, 0);
            } finally {
                session.put(Console.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
                sshSession.close(false);
            }
        } finally {
            client.stop();
        }

        return null;
    }
View Full Code Here

Examples of org.apache.sshd.SshClient

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

        SshClient client = null;
        Terminal terminal = null;
        try {
            client = SshClient.setUpDefaultClient();
            setupAgent(config.getUser(), client);
            client.start();
            ClientSession session = connectWithRetries(client, config);
            Console console = System.console();
            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);
        } 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

Examples of org.apache.sshd.SshClient

                username = readLine("Login: ");
            }
        }

        // Create the client from prototype
        SshClient client = (SshClient) container.getComponentInstance(sshClientId);
        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(Console.IGNORE_INTERRUPTS);
            this.session.put( Console.IGNORE_INTERRUPTS, Boolean.TRUE );

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

                boolean authed = false;
                if (agentSocket != null) {
                    sshSession.authAgent(username);
                    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) {
                    log.debug("Prompting user for password");
                    String password = readLine("Password: ");
                    sshSession.authPassword(username, password);
                    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;
                }

                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(Console.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
                sshSession.close(false);
            }
        } finally {
            client.stop();
        }

        return null;
    }
View Full Code Here

Examples of org.deepak.util.SSHClient

          }
          else
          {
            port = -1;
          }
          SSHClient ssh = null;
          if (port < 0)
          {
            ssh = new SSHClient(host, user, pwd);
          }
          else
          {
            ssh = new SSHClient(host, port, user, pwd);
          }
          ssh.login();
          ssh.copyFrom(tmpFilePath, copyDir);
          ssh.logout();
          filePath = copyDir + File.separator + tmpFileName;
        }
        else if ("local".equalsIgnoreCase(tmpSrc.trim()))
        {
          // Just return the filename here
View Full Code Here

Examples of org.jclouds.ssh.SshClient

               TemplateOptions.Builder.overrideLoginUser("toor"));
      assertEquals(numNodes, nodes.size(), "wrong number of nodes");
      for (NodeMetadata node : nodes) {
         assertTrue(node.getGroup().equals("test-launch-cluster"));
         logger.debug("Created Node: %s", node);
         SshClient client = context.utils().sshForNode().apply(node);
         client.connect();
         ExecResponse hello = client.exec("echo hello");
         assertEquals(hello.getOutput().trim(), "hello");
      }
      context.getComputeService().destroyNodesMatching(new Predicate<NodeMetadata>() {
         @Override
         public boolean apply(NodeMetadata input) {
View Full Code Here

Examples of org.jclouds.ssh.SshClient

      IMachine machine = null;
      try {
         machine = cloneFromMaster();
         machineController.ensureMachineIsLaunched(machine.getName());
         sshClientForIMachine = injector.getInstance(IMachineToSshClient.class);
         SshClient client = sshClientForIMachine.apply(machine);

         sshResponds = injector.getInstance(SshResponds.class);
         checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh",
                  machine.getName());
        
View Full Code Here

Examples of org.jclouds.ssh.SshClient

      try {
         IMachine machine = cloneFromMaster();
         machineController.ensureMachineIsLaunched(machine.getName());

         sshClientForIMachine = injector.getInstance(IMachineToSshClient.class);
         SshClient client = sshClientForIMachine.apply(machine);

         sshResponds = injector.getInstance(SshResponds.class);
         checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh",
                  machine.getName());
View Full Code Here

Examples of org.jclouds.ssh.SshClient

      configureOsInstallationWithKeyboardSequence(masterName, installationKeySequence);

      masterMachine.setExtraData(GUEST_OS_USER, masterSpec.getLoginCredentials().getUser());
      masterMachine.setExtraData(GUEST_OS_PASSWORD, masterSpec.getLoginCredentials().getPassword());

      SshClient client = sshClientForIMachine.apply(masterMachine);
      logger.debug(">> awaiting installation to finish node(%s)", masterName);
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.start();
      checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", masterName);
      stopwatch.stop();
View Full Code Here

Examples of org.jclouds.ssh.SshClient

      client.destroyDrive(drive.getUuid());
      assertEquals(client.getDriveInfo(drive.getUuid()), null);
   }

   protected void doConnectViaSsh(Server server, LoginCredentials creds) throws IOException {
      SshClient ssh = Guice.createInjector(new SshjSshClientModule()).getInstance(SshClient.Factory.class)
            .create(HostAndPort.fromParts(server.getVnc().getIp(), 22), creds);
      try {
         ssh.connect();
         ExecResponse hello = ssh.exec("echo hello");
         assertEquals(hello.getOutput().trim(), "hello");
         System.err.println(ssh.exec("df -k").getOutput());
         System.err.println(ssh.exec("mount").getOutput());
         System.err.println(ssh.exec("uname -a").getOutput());
      } finally {
         if (ssh != null)
            ssh.disconnect();
      }
   }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.