/** * Execute the command on the remote host. * * @param command - what to execute on the remote host. * @return return code of the process. * @throws BuildException bad parameter. * @throws JSchException if there's an underlying problem exposed in SSH * @throws IOException if there's a problem attaching streams. * @throws TimeoutException if we exceeded our timeout */ public int execute(String command) throws BuildException, JSchException, IOException, TimeoutException { if (command == null) { throw new BuildException("Command is required."); } if (host == null) { throw new BuildException("Host is required."); } if (userInfo.getName() == null) { throw new BuildException("Username is required."); } if (userInfo.getKeyfile() == null && userInfo.getPassword() == null) { throw new BuildException("Password or Keyfile is required."); } Session session = null; try { session = openSession(); return executeCommand(session, command); } finally { if (session != null && session.isConnected()) { session.disconnect(); } } }
/** * Open an ssh seession. * * @return the opened session * @throws JSchException on error */ protected Session openSession() throws JSchException { JSch jsch = new JSch(); if (null != userInfo.getKeyfile()) { jsch.addIdentity(userInfo.getKeyfile()); } if (!userInfo.getTrust() && knownHosts != null) { project.log("Using known hosts: " + knownHosts, Project.MSG_DEBUG); jsch.setKnownHosts(knownHosts); } Session session = jsch.getSession(userInfo.getName(), host, port); session.setUserInfo(userInfo); project.log("Connecting to " + host + ":" + port, Project.MSG_VERBOSE); session.connect(); return session; }