@Override public void execute(DelegateExecution execution) throws Exception { Pool pool = (Pool) execution.getVariable(CoreProcessVariables.POOL); checkNotNull( pool, "Please add the pool description as a process " + "variable with the name '%s'.", CoreProcessVariables.POOL); Machine machine = (Machine) execution.getVariable("machine"); LOG.info(">> Connecting to machine {} to install packages", machine); SSHClient client = Ssh.newClient(machine, pool.getAdminAccess()); try { String puppetScript = Mustache.toString( InstallPackages.class, "/com/axemblr/provisionr/core/puppet/packages.pp.mustache", ImmutableMap.of("packages", packagesAsListOfMaps(pool.getSoftware()))); Ssh.createFile(client, puppetScript, 0600, "/tmp/packages.pp"); Session session = client.startSession(); try { session.allocateDefaultPTY(); Session.Command command = session.exec("sudo puppet apply --verbose /tmp/packages.pp"); Ssh.logCommandOutput(LOG, machine.getExternalId(), command); command.join(); if (command.getExitStatus() != 0) { throw new RuntimeException( String.format( "Failed to execute puppet. Exit code: %d. Exit message: %s", command.getExitStatus(), command.getExitErrorMessage())); } else { LOG.info("<< Command completed successfully with exit code 0"); } } finally { session.close(); } } finally { client.close(); } }
public String exec(String command, int time, TimeUnit unit) throws IOException { Session s = ssh.startSession(); try { Session.Command cmd = s.exec(command); StringBuilder all = new StringBuilder(); BufferedReader out = new BufferedReader(new InputStreamReader(cmd.getInputStream())); String buf; while (null != (buf = out.readLine())) { logger.debug(buf); all.append(buf).append("\n"); } cmd.join(time, unit); cmd.close(); return all.toString(); } finally { s.close(); } }
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 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(); } }
@Override public ExecResponse create() throws Exception { try { session = acquire(execConnection()); Command output = session.exec(checkNotNull(command, "command")); String outputString = IOUtils.readFully(output.getInputStream()).toString(); output.join(timeoutMillis, TimeUnit.SECONDS); int errorStatus = output.getExitStatus(); String errorString = IOUtils.readFully(output.getErrorStream()).toString(); return new ExecResponse(outputString, errorString, errorStatus); } finally { clear(); } }
@Override public void clear() throws TransportException, ConnectionException { if (session != null) session.close(); }