SshClient ssh = new SshClient(); ssh.connect(host, port); //Authenticate PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient(); passwordAuthenticationClient.setUsername(userName); passwordAuthenticationClient.setPassword(password); int result = ssh.authenticate(passwordAuthenticationClient); if(result != AuthenticationProtocolState.COMPLETE){ throw new SFTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed"); } //Open the SFTP channel SftpClient client = ssh.openSftpClient(); //Send the file client.put(filePath); //disconnect client.quit(); ssh.disconnect();
SshClient sshClient = createMock(SshClient.class); sshClient.connect(); sshClient.put("/tmp/init-jclouds-script-0", init.render(OsFamily.UNIX)); expect(sshClient.getUsername()).andReturn("tester").atLeastOnce(); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com").atLeastOnce(); expect(sshClient.exec("chmod 755 /tmp/init-jclouds-script-0")).andReturn(new ExecResponse("", "", 0)); expect(sshClient.exec("ln -fs /tmp/init-jclouds-script-0 jclouds-script-0")).andReturn( new ExecResponse("", "", 0)); expect(sshClient.exec("/tmp/init-jclouds-script-0 init")).andReturn(new ExecResponse("", "", 0)); expect(sshClient.exec("sudo /tmp/init-jclouds-script-0 start")).andReturn(new ExecResponse("", "", 0)); expect(sshClient.exec("/tmp/init-jclouds-script-0 status")).andReturn(new ExecResponse("", "", 1)).times(1); expect(sshClient.exec("/tmp/init-jclouds-script-0 stdout")).andReturn(new ExecResponse("out", "", 0)); expect(sshClient.exec("/tmp/init-jclouds-script-0 stderr")).andReturn(new ExecResponse("err", "", 0)); expect(sshClient.exec("/tmp/init-jclouds-script-0 exitstatus")).andReturn(new ExecResponse("0", "", 0)); sshClient.disconnect(); replay(sshClient); statusFactory, timeouts, Functions.forMap(ImmutableMap.of(node, sshClient)), eventBus, InitScriptConfigurationForTasks.create().appendIncrementingNumberToAnonymousTaskNames(), node, command, new RunScriptOptions());
protected void checkSSH(HostAndPort socket) { socketTester.apply(socket); SshClient client = sshFactory.create(socket, loginCredentials); try { client.connect(); ExecResponse exec = client.exec("echo hello"); System.out.println(exec); assertEquals(exec.getOutput().trim(), "hello"); } finally { if (client != null) client.disconnect(); } }
public void simpleTest() { RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"), wrapInInitScript(false).runAsRoot(false)); testMe.init(); sshClient.connect(); expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect(sshClient.exec("echo $USER\n" + "echo $USER\n")).andReturn(new ExecResponse("tester\ntester\n", null, 0)); sshClient.disconnect(); replay(sshClient); testMe.call(); }
LoginCredentials.builder().user("root").password("password1").build())).andReturn(client1); client2.connect(); expect(client2.exec("hostname\n")).andReturn(new ExecResponse("stub-r\n", "", 0)); client2.disconnect(); client2.connect(); expect(client2.exec("hostname\n")).andReturn(new ExecResponse("stub-r\n", "", 0)); client2.disconnect(); client2.connect(); try { runScript(client2, "runScriptWithCreds", client2.disconnect(); client2New.connect(); try { runScript(client2New, "adminUpdate", Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class client2New.disconnect(); client2Foo.connect(); expect(client2Foo.getUsername()).andReturn("foo").atLeastOnce(); expect(client2Foo.getHostAddress()).andReturn("foo").atLeastOnce(); expect(client2Foo.exec("echo $USER\n")).andReturn(new ExecResponse("foo\n", "", 0)); client2Foo.disconnect();
public void simpleRootTestWithSudoPassword() { node = createMock(NodeMetadata.class); expect(node.getCredentials()).andReturn(LoginCredentials.builder().user("tester").password("testpassword!").authenticateSudo(true).build()) .atLeastOnce(); replay(node); RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec("echo $USER\necho $USER"), wrapInInitScript(false).runAsRoot(true)); testMe.init(); sshClient.connect(); expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect( sshClient.exec("sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + "testpassword!\n" + "echo $USER\n" + "echo $USER\n" + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0)); sshClient.disconnect(); replay(sshClient); testMe.call(); }
@Test public void testPutAndGet() throws IOException { temp = File.createTempFile("foo", "bar"); temp.deleteOnExit(); SshClient client = setupClient(); client.put(temp.getAbsolutePath(), Payloads.newStringPayload("rabbit")); Payload input = setupClient().get(temp.getAbsolutePath()); String contents = Strings2.toString(input); assertEquals(contents, "rabbit"); }
@Test public void testExecInvalidCommand() throws IOException { SshClient client = setupClient(); try { ExecResponse response = client.exec("thisCommandDoesNotExist"); assertNotEquals(response.getExitStatus(), 0); assertTrue(response.getOutput().contains("not found") || response.getError().contains("not found"), "stdout="+response.getOutput()+"; stderr="+response.getError()); } finally { client.disconnect(); } }
private void runScriptAndService(SshClient client, SshClient clientNew) { client.connect(); client.put("/tmp/init-" + scriptName, Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class .getResourceAsStream("/initscript_with_jetty.sh"))); expect(client.exec("chmod 755 /tmp/init-" + scriptName)).andReturn(EXEC_GOOD); expect(client.exec("ln -fs /tmp/init-" + scriptName + " " + scriptName)).andReturn(EXEC_GOOD); expect(client.getUsername()).andReturn("root").atLeastOnce(); expect(client.getHostAddress()).andReturn("localhost").atLeastOnce(); expect(client.exec("/tmp/init-" + scriptName + " init")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " start")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " status")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " status")).andReturn(EXEC_BAD); expect(client.exec("/tmp/init-" + scriptName + " stdout")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " stderr")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " exitstatus")).andReturn(EXEC_RC_GOOD); client.disconnect(); clientNew.connect(); expect(clientNew.getUsername()).andReturn("web").atLeastOnce(); expect(clientNew.getHostAddress()).andReturn("localhost").atLeastOnce(); expect(clientNew.exec("head -1 /usr/local/jetty/VERSION.txt | cut -f1 -d ' '\n")).andReturn(EXEC_GOOD); clientNew.disconnect(); clientNew.connect(); expect(clientNew.exec("java -fullversion\n")).andReturn(EXEC_GOOD); clientNew.disconnect();
private void runScript(SshClient client, String scriptName, String script, int nodeId) { client.put("/tmp/init-" + scriptName, script); expect(client.exec("chmod 755 /tmp/init-" + scriptName)).andReturn(EXEC_GOOD); expect(client.exec("ln -fs /tmp/init-" + scriptName + " " + scriptName)).andReturn(EXEC_GOOD); expect(client.getUsername()).andReturn("root").atLeastOnce(); expect(client.getHostAddress()).andReturn(nodeId + "").atLeastOnce(); expect(client.exec("/tmp/init-" + scriptName + " init")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " start")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " status")).andReturn(EXEC_GOOD); // next status says the script is done, since not found. expect(client.exec("/tmp/init-" + scriptName + " status")).andReturn(EXEC_BAD); expect(client.exec("/tmp/init-" + scriptName + " stdout")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " stderr")).andReturn(EXEC_GOOD); expect(client.exec("/tmp/init-" + scriptName + " exitstatus")).andReturn(EXEC_RC_GOOD); }
private void helloAndJava(SshClient client) { client.connect(); expect(client.exec("echo hello")).andReturn(new ExecResponse("hello", "", 0)); expect(client.exec("java -version")).andReturn(new ExecResponse("", "OpenJDK", 0)); client.disconnect(); }
SshClient connection; if (Strings.emptyToNull(sshKeyFile) != null) { connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser) .privateKey(Files.toString(new File(sshKeyFile), Charsets.UTF_8)).build()); } else { connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser).password(sshPass).build()); connection.connect(); return connection;
try { try { ssh.put(initFile, init.render(OsFamily.UNIX)); } catch (SshException e) { else logger.warn("<< (%s) problem using sftp [%s], attempting via sshexec", ssh.toString(), e.getMessage()); ssh.disconnect(); ssh.connect(); ssh.exec("rm " + initFile); ssh.exec(Statements.appendFile(initFile, Splitter.on('\n').split(init.render(OsFamily.UNIX)), AppendFile.DELIMITER + "_" + init.getInstanceName()).render(OsFamily.UNIX)); ssh.exec("chmod 755 " + initFile); setupLinkToInitFile();
protected void refreshSshIfNewAdminCredentialsConfigured(AdminAccess input) { if (input.getAdminCredentials() != null && input.shouldGrantSudoToAdminUser()) { ssh.disconnect(); logger.debug(">> reconnecting as %s@%s", input.getAdminCredentials().identity, ssh.getHostAddress()); ssh = sshFactory.apply(node = NodeMetadataBuilder.fromNodeMetadata(node) .credentials(LoginCredentials.fromCredentials(input.getAdminCredentials())).build()); ssh.connect(); setupLinkToInitFile(); } }
protected ExecResponse runCommand(String command) { ExecResponse returnVal; logger.debug(">> running [%s] as %s@%s", command.replace(node.getCredentials().getOptionalPassword().isPresent() ? node .getCredentials().getOptionalPassword().get() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh.getHostAddress()); returnVal = ssh.exec(command); return returnVal; }
protected ExecResponse runCommand(String command) { ExecResponse returnVal; logger.debug(">> running [%s] as %s@%s", command.replace(node.getCredentials().getPassword() != null ? node .getCredentials().getPassword() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh.getHostAddress()); returnVal = ssh.exec(command); return returnVal; }
public ExecResponse refreshAndRunAction(String action) { checkState(ssh != null, "please call init() before invoking call"); try { ssh.connect(); return runAction(action); } finally { if (ssh != null) ssh.disconnect(); } }
@Override public boolean apply(SshClient input) { input.connect(); if (input.exec("id").getExitStatus() == 0) { return true; } return false; } }, getSpawnNodeMaxWait(), 1l, SECONDS).apply(client));
public ExecResponse refreshAndRunAction(String action) { checkState(ssh != null, "please call init() before invoking call"); try { if (!ssh.isConnected()) { ssh.connect(); } return runAction(action); } finally { if (ssh != null) ssh.disconnect(); } }
/** * Upload a file on a selected node * @param sourcePath path to the file to be uploaded * @param destinationPath path to the file to be created * @param nodeId Id of a node * @param login user login * @param key key to connect */ public void uploadFile(String sourcePath, String destinationPath, String nodeId, String login, String key){ try { String contentKey=FileUtils.readFileToString(new File(key)); SshClient ssh = compute.getContext().getUtils().sshForNode().apply(NodeMetadataBuilder.fromNodeMetadata(getNodeById(nodeId)).credentials(new LoginCredentials(login, null, contentKey, true)).build()); try { ssh.connect(); ssh.put(destinationPath, Payloads.newPayload(new File(sourcePath))); } finally { if (ssh != null) ssh.disconnect(); journal.log(Level.INFO, ">> File uploaded!"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }