Package net.schmizz.sshj

Examples of net.schmizz.sshj.SSHClient


/** This example demonstrates downloading of a file over SFTP from the SSH server. */
public class SFTPDownload {

    public static void main(String[] args)
            throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.loadKnownHosts();
        ssh.connect("localhost");
        try {
            ssh.authPublickey(System.getProperty("user.name"));
            final SFTPClient sftp = ssh.newSFTPClient();
            try {
                sftp.get("test_file", new FileSystemFile("/tmp"));
            } finally {
                sftp.close();
            }
        } finally {
            ssh.disconnect();
        }
    }
View Full Code Here


     *
     * @throws IOException
     *             if an error occurred during setting up the client
     */
    private void prepareClient() throws IOException {
        ssh = new SSHClient();

        if (sshConfig.getString("tavernaserver.ssh.fingerprint") != null
            && !"".equals(sshConfig.getString("tavernaserver.ssh.fingerprint"))) {
            ssh.addHostKeyVerifier(sshConfig.getString("tavernaserver.ssh.fingerprint"));
        }
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

      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

    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

        }
    }

    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

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.