Examples of SSHClient


Examples of net.schmizz.sshj.SSHClient

        return server;
    }

    public void startClient(boolean authenticate)
            throws IOException {
        client = new SSHClient();
        client.addHostKeyVerifier(fingerprint);
        client.connect(hostname, port);
        if (authenticate)
            dummyAuth();
        clientRunning = true;
View Full Code Here

Examples of net.schmizz.sshj.SSHClient

        String ipAddress=findIpAddress(instanceId);
        System.out.println("instance "+instanceId+" is up and running at IP address: "+ipAddress);

        Thread.sleep(2*60*1000);   // primitive, ssh will take a little while to be ready

        final SSHClient ssh = new SSHClient();
        String $HOME=System.getProperty("user.home");
        OpenSSHKeyFile k=new OpenSSHKeyFile();
        k.init(new File($HOME+"/.haruhi/o2key.pem"));
        ssh.addHostKeyVerifier(new PromiscuousVerifier());

        ssh.connect(ipAddress);
        ssh.authPublickey("ubuntu",k);
        final Session session = ssh.startSession();
        try {
            final Session.Command cmd = session.exec("ls -a");

            System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
            cmd.join(5, TimeUnit.SECONDS);
            System.out.println("\n** exit status: " + cmd.getExitStatus());
        } finally {
            session.close();
            ssh.disconnect();
        }
    }
View Full Code Here

Examples of net.schmizz.sshj.SSHClient

        return instances.get(0).getInstances().get(0).getPublicIpAddress();
    }

    private void logIntoIp(String ipAddress) throws IOException, InterruptedException {
        final SSHClient ssh = new SSHClient();
        OpenSSHKeyFile k = new OpenSSHKeyFile();
        k.init(new File(dotHaruhi, keyPairName + ".pem"));
        ssh.addHostKeyVerifier(new PromiscuousVerifier());

        ssh.connect(ipAddress);
        try {
            ssh.authPublickey(clusterUsername, k);
            Session that = ssh.startSession();
            try {
                that.allocateDefaultPTY();
                Session.Shell shell = that.startShell();

                new StreamCopier(shell.getInputStream(), System.out)
                        .bufSize(shell.getLocalMaxPacketSize())
                        .spawn("stdout");

                new StreamCopier(shell.getErrorStream(), System.err)
                        .bufSize(shell.getLocalMaxPacketSize())
                        .spawn("stderr");

                new StreamCopier(System.in, shell.getOutputStream())
                        .bufSize(shell.getRemoteMaxPacketSize())
                        .copy();

            } finally {
                that.close();
            }
        } finally {
            ssh.close();
        }
    }
View Full Code Here

Examples of net.schmizz.sshj.SSHClient

public class SshTransport implements Transport {
  private final SSHClient ssh;

  public SshTransport(SshConfig config) {
    this.ssh = new SSHClient();
   
    try {
      this.ssh.loadKnownHosts();
    } catch (IOException e) {
      throw new RuntimeException(e);
View Full Code Here

Examples of net.schmizz.sshj.SSHClient

import com.jcraft.jsch.agentproxy.sshj.AuthAgent;

public class Test {

  public static void main(String[] args) throws Exception {
    final SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();

    ssh.connect("dev4");
    try {
      AgentProxy agentProxy = getAgentProxy();
      if (agentProxy == null) {
        System.err.println("No agentProxy");
        System.exit(0);
      }
      ssh.auth(System.getProperty("user.name"), getAuthMethods(agentProxy));
      final Session session = ssh.startSession();
      try {
        final Command cmd = session.exec("ping -c 1 google.com");
        System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
        cmd.join(5, TimeUnit.SECONDS);
        System.out.println("\n** exit status: " + cmd.getExitStatus());
      } finally {
        session.close();
      }
    } finally {
      ssh.disconnect();
    }
  }
View Full Code Here

Examples of net.schmizz.sshj.SSHClient

    private final SCPEngine engine;

    public static void main(String[] args)
            throws IOException {
        SSHClient ssh = new SSHClient();
        // ssh.useCompression(); // Can lead to significant speedup (needs JZlib in classpath)
        ssh.loadKnownHosts();
        ssh.connect("dev4");
        try {
          PasswordFinder password = PasswordUtils.createOneOff("Reishee1".toCharArray());
          final String base = System.getProperty("user.home") + File.separator + ".ssh" + File.separator;
          final KeyProvider keyProvider = ssh.loadKeys(base + "id_dsa", password);
         
          final String user = System.getProperty("user.name");
          ssh.authPublickey(user, keyProvider);
         
            ssh.newSCPFileTransfer().download("/home/erikb/ninja.sh", new FileSystemFile("/tmp/"));
        } finally {
            ssh.disconnect();
        }
    }   
View Full Code Here

Examples of net.schmizz.sshj.SSHClient

        openShellBeforeExecute = options.getBoolean(OPEN_SHELL_BEFORE_EXECUTE, OPEN_SHELL_BEFORE_EXECUTE_DEFAULT);
    }

    protected void connect() {
        try {
            SSHClient client = sshClientFactory.create();
            client.setConnectTimeout(connectionTimeoutMillis);
            client.addHostKeyVerifier(new PromiscuousVerifier());

            try {
                if (localAddress == null) {
                    client.connect(host, port);
                } else {
                    client.connect(host, port, InetAddress.getByName(localAddress), localPort);
                }
            } catch (IOException e) {
                throw new RuntimeIOException("Cannot connect to " + host + ":" + port, e);
            }

            if (privateKeyFile != null) {
                if (password != null) {
                    logger.warn("The " + PRIVATE_KEY_FILE + " and " + PASSWORD + " connection options have both been set for the connection {}. Ignoring "
                            + PASSWORD
                            + " and using " + PRIVATE_KEY_FILE + ".", this);
                }
                KeyProvider keys;
                try {
                    if (passphrase == null) {
                        keys = client.loadKeys(privateKeyFile);
                    } else {
                        keys = client.loadKeys(privateKeyFile, passphrase);
                    }
                } catch (IOException e) {
                    throw new RuntimeIOException("Cannot read key from private key file " + privateKeyFile, e);
                }
                client.authPublickey(username, keys);
            } else if (password != null) {
                PasswordFinder passwordFinder = getPasswordFinder();
                client.auth(username, new AuthPassword(passwordFinder),
                        new AuthKeyboardInteractive(new RegularExpressionPasswordResponseProvider(passwordFinder, interactiveKeyboardAuthPromptRegex)));
            }
            sshClient = client;
            connected();
        } catch (SSHException e) {
View Full Code Here

Examples of net.schmizz.sshj.SSHClient

    model.setHost(this.instance.getPublicDnsName());
   
    /*
     * Make directory
     */
    SSHClient ssh = new SSHClient();
    try {
      ssh.loadKnownHosts();
      ssh.connect(this.instance.getPublicDnsName());

      ssh.authPublickey(privateKeyFilePath);
      final Session session = ssh.startSession();
      try {
        StringBuilder command = new StringBuilder();
        command.append("mkdir -p ");
        command.append(model.getTmpDir());
        command.append(" | ");
        command.append("mkdir -p ");
        command.append(model.getWorkingDir());
        command.append(" | ");
        command.append("mkdir -p ");
        command.append(model.getInputDataDir());
        command.append(" | ");
        command.append("mkdir -p ");
        command.append(model.getOutputDataDir());
        Command cmd = session.exec(command.toString());
        cmd.join(5, TimeUnit.SECONDS);
      } 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 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());
      ssh.authPublickey(privateKeyFilePath);

      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 net.schmizz.sshj.SSHClient

  @Override
  public void initialize(InvocationContext invocationContext) throws GfacException {
    ExecutionContext appExecContext = invocationContext.getExecutionContext();
    ExecutionModel model = appExecContext.getExecutionModel();

    SSHClient ssh = new SSHClient();
    try {
      ssh.loadKnownHosts();
      ssh.connect(model.getHost());

      // TODO how to authenticate with system
      ssh.authPublickey(System.getProperty("user.name"));
      final Session session = ssh.startSession();
      try {
        StringBuilder command = new StringBuilder();
        command.append("mkdir -p ");
        command.append(model.getTmpDir());
        command.append(" | ");
        command.append("mkdir -p ");
        command.append(model.getWorkingDir());
        command.append(" | ");
        command.append("mkdir -p ");
        command.append(model.getInputDataDir());
        command.append(" | ");
        command.append("mkdir -p ");
        command.append(model.getOutputDataDir());
        Command cmd = session.exec(command.toString());
        cmd.join(5, TimeUnit.SECONDS);
      } 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
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.