Examples of SSHClient


Examples of net.schmizz.sshj.SSHClient

    ExecutionContext context = invocationContext.getExecutionContext();
    ExecutionModel model = context.getExecutionModel();

    List<String> cmdList = new ArrayList<String>();

    SSHClient ssh = new SSHClient();
    try {

      /*
       * Notifier
       */
      NotificationService notifier = context.getNotificationService();

      /*
       * Builder Command
       */
      cmdList.add(context.getExecutionModel().getExecutable());
      cmdList.addAll(context.getExecutionModel().getInputParameters());

      // create process builder from command
      String command = buildCommand(cmdList);
     
      //redirect StdOut and StdErr
      command += SPACE + "1>" + SPACE + model.getStdOut();
      command += SPACE + "2>" + SPACE + model.getStderr();     

      // get the env of the host and the application
      Map<String, String> nv = context.getExecutionModel().getEnv();     

      // extra env's
      nv.put(GFacConstants.INPUT_DATA_DIR, context.getExecutionModel().getInputDataDir());
      nv.put(GFacConstants.OUTPUT_DATA_DIR, context.getExecutionModel().getOutputDataDir());
     
      // log info
      log.info("Command = " + buildCommand(cmdList));     
      for (String key : nv.keySet()) {
        log.info("Env[" + key + "] = " + nv.get(key));
      }

      // notify start
      DurationObj compObj = notifier.computationStarted();

      /*
       * Create ssh connection
       */
      ssh.loadKnownHosts();
      ssh.connect(model.getHost());

      // TODO how to authenticate with system
      ssh.authPublickey(System.getProperty("user.name"));

      final Session session = ssh.startSession();
      try {
        /*
         * Build working Directory
         */
        log.info("WorkingDir = " + model.getWorkingDir());     
        session.exec("mkdir -p " + model.getWorkingDir());
        session.exec("cd " + model.getWorkingDir());
       
        /*
         * Set environment
         */
        for (String key : nv.keySet()) {
          session.setEnvVar(key, nv.get(key));
        }
       
        /*
         * Execute
         */
        Command cmd = session.exec(command);
        log.info("stdout=" + GfacUtils.readFromStream(session.getInputStream()));
        cmd.join(5, TimeUnit.SECONDS);
       
       
        // notify end
        notifier.computationFinished(compObj);
       
        /*
         * check return value. usually not very helpful to draw conclusions
         * based on return values so don't bother. just provide warning in
         * the log messages
         */       
        if (cmd.getExitStatus() != 0) {
          log.error("Process finished with non zero return value. Process may have failed");
        } else {
          log.info("Process finished with return value of zero.");
        }                       
       
        File logDir = new File("./service_logs");
        if (!logDir.exists()) {
          logDir.mkdir();
        }       
       
        // Get the Stdouts and StdErrs
        QName x = QName.valueOf(invocationContext.getServiceName());
        String timeStampedServiceName = GfacUtils.createServiceDirName(x);
        File localStdOutFile = new File(logDir, timeStampedServiceName + ".stdout");
        File localStdErrFile = new File(logDir, timeStampedServiceName + ".stderr");
       
        SCPFileTransfer fileTransfer = ssh.newSCPFileTransfer();
        fileTransfer.download(model.getStdOut(), localStdOutFile.getAbsolutePath());
        fileTransfer.download(model.getStderr(), localStdErrFile.getAbsolutePath());       
       
        context.getExecutionModel().setStdoutStr(GfacUtils.readFile(localStdOutFile.getAbsolutePath()));
        context.getExecutionModel().setStderrStr(GfacUtils.readFile(localStdErrFile.getAbsolutePath()));
       
        // set to context
        OutputUtils.fillOutputFromStdout(invocationContext.getMessageContext("output"), context.getExecutionModel().getStdoutStr(), context.getExecutionModel().getStderrStr());
       
      } catch (Exception e) {
        throw e;
      } finally {
        try {
          session.close();
        } catch (Exception e) {
        }
      }
    } catch (Exception e) {
      throw new GfacException(e.getMessage(), e);
    } finally {
      try {
        ssh.disconnect();
      } catch (Exception e) {
      }
    }
  }
View Full Code Here

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

Examples of org.apache.sshd.SshClient

        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

Examples of org.apache.sshd.SshClient

        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

Examples of org.apache.sshd.SshClient

                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

Examples of org.apache.sshd.SshClient

                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

Examples of org.apache.sshd.SshClient

                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

Examples of org.apache.sshd.SshClient

    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

Examples of org.apache.sshd.SshClient

            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

Examples of org.apache.sshd.SshClient

                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
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.