Package net.schmizz.sshj

Examples of net.schmizz.sshj.SSHClient


    private final AdminAccess adminAccess = AdminAccess.builder()
        .asCurrentUser().createAdminAccess();

    @Test
    public void testConnectToLocalhostAndCollectOutput() throws IOException {
        SSHClient client = Ssh.newClient(localhost, adminAccess, 1000);
        try {
            Session session = client.startSession();
            try {
                final Session.Command command = session.exec("echo 'stdout' && echo 'stderr' 1>&2");

                String stdout = CharStreams.toString(new InputStreamReader(command.getInputStream()));
                String stderr = CharStreams.toString(new InputStreamReader(command.getErrorStream()));

                command.join();
                assertThat(command.getExitStatus()).isEqualTo(0);
                assertThat(command.getExitErrorMessage()).isNull();

                assertThat(stdout).contains("stdout");
                assertThat(stderr).contains("stderr");

            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here


        }
    }

    @Test
    public void testConnectStreamLoggerToCommand() throws IOException, InterruptedException {
        SSHClient client = Ssh.newClient(localhost, adminAccess, 1000);
        try {
            Session session = client.startSession();
            try {
                final Session.Command command = session.exec("echo 'line1' && echo && echo 'line2'");
                final List<String> lines = Lists.newCopyOnWriteArrayList();

                StreamLogger logger = new StreamLogger(command.getInputStream(), LOG, MarkerFactory.getMarker("live")) {
                    @Override
                    protected void log(Logger logger, Marker marker, String line) {
                        logger.info(marker, line)/* just for visual inspection */
                        lines.add(line);
                    }
                };
                logger.start();

                command.join();
                logger.join();

                assertThat(lines).hasSize(2).contains("line1", "line2");

            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here

        }
    }

    @Test
    public void testCreateFileOverSsh() throws IOException {
        SSHClient client = Ssh.newClient(localhost, adminAccess, 1000);
        try {
            String destination = "/tmp/" + UUID.randomUUID().toString();
            String content = UUID.randomUUID().toString();

            Ssh.createFile(client, content, 0600, destination);

            /* Check the file exists and has the expected content */
            Session session = client.startSession();
            try {
                final Session.Command command = session.exec("set +x +e && cat " + destination);

                String output = CharStreams.toString(new InputStreamReader(command.getInputStream()));
                command.join();

                assertThat(command.getExitStatus()).isEqualTo(0);
                assertThat(output).contains(content);

            } finally {
                session.close();
            }
        } finally {
            client.close();
        }

    }
View Full Code Here

    public static SSHClient newClient(
        Machine machine, AdminAccess adminAccess, int timeoutInMillis
    ) throws IOException {
        checkArgument(timeoutInMillis >= 0, "timeoutInMillis should be positive or 0");

        final SSHClient client = new SSHClient();
        client.addHostKeyVerifier(AcceptAnyHostKeyVerifier.INSTANCE);

        if (timeoutInMillis != 0) {
            client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            client.setTimeout(timeoutInMillis);
        }
        client.connect(machine.getPublicDnsName(), machine.getSshPort());

        OpenSSHKeyFile key = new OpenSSHKeyFile();
        key.init(adminAccess.getPrivateKey(), adminAccess.getPublicKey());
        client.authPublickey(adminAccess.getUsername(), key);

        return client;
    }
View Full Code Here

        Machine machine = (Machine) execution.getVariable("machine");
        checkNotNull(machine, "expecting a process variable named 'machine'");

        LOG.info(">> Connecting to machine {} to run puppet script", machine);

        SSHClient client = Ssh.newClient(machine, overrideAdminAccess(pool));
        try {
            for (Map.Entry<String, String> entry : createAdditionalFiles(pool, machine).entrySet()) {
                Ssh.createFile(client, /* content = */ entry.getValue(), 0600, /* destination= */ entry.getKey());
            }

            final String destination = "/tmp/" + remoteFileName + ".pp";
            Ssh.createFile(client, createPuppetScript(pool, machine), 0600, destination);

            Session session = client.startSession();
            try {
                session.allocateDefaultPTY();

                // TODO: extract this loop outside of this activity (probably using a business process error)
                final String runScriptWithWaitCommand = "while ! which puppet &> /dev/null ; " +
                    "do echo 'Puppet command not found. Waiting for userdata.sh script to finish (10s)' " +
                    "&& sleep 10; " +
                    "done " +
                    "&& sudo puppet apply --detailed-exitcodes --debug --verbose " + destination;
                Session.Command command = session.exec(runScriptWithWaitCommand);

                Ssh.logCommandOutput(LOG, machine.getExternalId(), command);
                command.join();

                final Integer exitStatus = command.getExitStatus();
                if (exitStatus != PUPPET_FINISHED_WITH_NO_FAILURES && exitStatus != 0) {
                    throw new RuntimeException(String.format("Failed to execute puppet. " +
                        "Exit code: %d. Exit message: %s", exitStatus, command.getExitErrorMessage()));

                } else {
                    LOG.info("<< Command completed successfully with exit code 0");
                }


            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here

        }
    }

    private void assertSshCommand(Machine machine, AdminAccess adminAccess, String bashCommand) throws IOException {
        LOG.info("Checking return code for command '{}' on machine {}", bashCommand, machine.getExternalId());
        SSHClient client = Ssh.newClient(machine, adminAccess);
        try {
            Session session = client.startSession();
            try {
                session.allocateDefaultPTY();
                Session.Command command = session.exec(bashCommand);

                command.join();
                assertTrue("Exit code was " + command.getExitStatus() + " for command " + bashCommand,
                    command.getExitStatus() == 0);
            } finally {
                session.close();
            }
        } finally {
            client.close();
        }
    }
View Full Code Here

      assert ssh1.shouldRetry(new RuntimeException(nex));
   }

   public void testDontThrowIOExceptionOnClear() throws Exception {
      SshjSshClient ssh1 = createClient();
      SSHClient ssh = createMock(SSHClient.class);
      expect(ssh.isConnected()).andReturn(true);
      ssh.disconnect();
      expectLastCall().andThrow(new ConnectionException("disconnected"));
      replay(ssh);
      ssh1.sshClientConnection.ssh = ssh;
      ssh1.sshClientConnection.clear();
      verify(ssh);
View Full Code Here

      return true;
    }
  }

  private void exec(String command) throws IOException {
    SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();
    ssh.addHostKeyVerifier(new NullHostKeyVerifier());
    ssh.connect(vmName);
    ssh.authPassword(vmUser, vmPwd);

    final Session session = ssh.startSession();
    try {
      final Command cmd = session.exec(command);
      System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
      cmd.join(10, TimeUnit.SECONDS);
      System.out
          .println("\n** exit status: " + cmd.getExitStatus() + " for the cmd " + command + " on " + vmName);
      if (cmd.getExitStatus() != 0) {
        System.out.println("Command [" + command + "] failed with exit status :" + cmd.getExitStatus() + " on "
            + vmName);
        // System.exit(cmd.getExitStatus());
      }
    }
    finally {
      ssh.close();
    }
    ssh.disconnect();
  }
View Full Code Here

  }

  public Session getSession(String hostAddress) throws IOException {
    try {
      if (sshClient == null) {
        sshClient = new SSHClient();
      }
      if (getSSHClient().isConnected())
        return getSSHClient().startSession();

      KeyProvider pkey = getSSHClient().loadKeys(getPrivateKeyLoc(), getKeyPass());
View Full Code Here

    }
  }

  public SSHClient getSSHClient() {
    if (sshClient == null) {
      sshClient = new SSHClient();
    }
    return sshClient;
  }
View Full Code Here

TOP

Related Classes of net.schmizz.sshj.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.