SSHUtil { public boolean execCmd(String user, String privateKeyFile, String hostIP, int sshPort, String command, InputStream in, OutputStream out) throws JSchException{ AuAssert.check(command != null); connect(user, privateKeyFile, hostIP, sshPort); ChannelExec channel = null; logger.info("going to exec command"); try { channel = (ChannelExec) session.openChannel("exec"); if (channel != null) { logger.debug("SSH channel is opened!"); channel.setPty(true); channel.setCommand(command); channel.setInputStream(in); channel.setOutputStream(out); channel.connect(); if (!channel.isConnected()) { logger.error("Cannot setup SSH channel connection."); } while (true) { if (channel.isClosed()) { int exitStatus = channel.getExitStatus(); logger.debug("Exit status from exec is: " + exitStatus); if (exitStatus == 0) { return true; } return false; } try { Thread.sleep(200); } catch (InterruptedException e) { } } } else { logger.error("Cannot open SSH channel to " + hostIP + "."); return false; } } finally { if (channel != null && channel.isConnected()) { channel.disconnect(); } if (session != null && session.isConnected()) { session.disconnect(); } } }  boolean execCmd(String user, String privateKeyFile,
         String hostIP, int sshPort, String command, InputStream in, OutputStream out);  }
@Test public void testExecCmd() throws Exception { SSHUtil sshUtil = new SSHUtil(); Assert.assertTrue(sshUtil.execCmd(username, tempPrivateKeyFile, hostIP, port, "hostname", null, null)); new File(tempPrivateKeyFile).delete(); }
@Test public void testExecCmdWithoutPrivateKeyFile() { SSHUtil sshUtil = new SSHUtil(); boolean getException = false; try { sshUtil.execCmd(username, null, hostIP, port, "hostname", null, null); } catch (Exception e) { getException = true; } Assert.assertTrue(getException); }