public static void main(String[] args) throws JSchException { SshClient ssh = new SshClient(); CommandExecution exec = ssh.getCommandExecutor( ChefNodeManager.DEFAULT_CHEF_HOST, new LoginCredentialsPassword("chef login creds", "root", "redundant"), // "ps aux"); "knife bootstrap 23.20.100.107 -i /tmp/creds3268697130713915657.tmp -x ubuntu --sudo --no-host-key-verify -d ubuntu10.04-apt -N mytestNode1"); Future<Integer> result = exec.execute(); System.out.println("result: " + result); exec.shutdown(); }
@Override public Integer call() { int exitstatus = Integer.MAX_VALUE; Boolean useIdentityFile = null; String credentials = null; String userName = nodeCredentials.getUsername(); if (nodeCredentials instanceof LoginCredentialsPassword) { useIdentityFile = false; credentials = ((LoginCredentialsPassword) nodeCredentials).getPassword(); } else if (nodeCredentials instanceof LoginCredentialsPrivateKey) { useIdentityFile = true; credentials = ((LoginCredentialsPrivateKey) nodeCredentials).getKey().getKeyPath(); } ChannelExec c = null; SshClient ssh = null; try { ssh = new SshClient(); ssh.createSession(nodeAddress, userName, false); log.info("connecting with username: "******"connecting using identity file: " + credentials); } else { log.info("connecting using password: "******"executing command: " + command); c.connect(); new Thread( new Runnable() { public void run() { String line; BufferedReader bufferedInputReader = new BufferedReader(new InputStreamReader(is)); try { while ((line = bufferedInputReader.readLine()) != null) { output.append(line); synchronized (timeStamp) { timeStamp = System.currentTimeMillis(); } } } catch (IOException e) { e.printStackTrace(); } } }) .start(); new Thread( new Runnable() { public void run() { String line; BufferedReader bufferedErrorReader = new BufferedReader(new InputStreamReader(err)); try { while ((line = bufferedErrorReader.readLine()) != null) { error.append(line); synchronized (timeStamp) { timeStamp = System.currentTimeMillis(); } } } catch (IOException e) { e.printStackTrace(); } } }) .start(); while (!c.isClosed()) { synchronized (this.timeStamp) { if (System.currentTimeMillis() - this.timeStamp > MAXIMUM_WAITING_TIME_INACTIVITY) { log.warn("command execution seems inactive, canceling!"); break; } } log.info("waiting for command to finish."); try { Thread.sleep(SshClient.DEFAULT_WAITING_TIME_PER_CYCLE); } catch (InterruptedException e) { e.printStackTrace(); } } exitstatus = c.getExitStatus(); } catch (JSchException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (c != null) { c.disconnect(); } if (ssh != null) { try { ssh.disconnectSession(); } catch (JSchException e) { e.printStackTrace(); } } } return exitstatus; }