Example #1
2
 public String sendCommand(Session session, String Command) {
   StringBuilder result = new StringBuilder();
   try {
     Channel channel = session.openChannel("exec");
     ((ChannelExec) channel).setCommand(Command);
     InputStream in = channel.getInputStream();
     channel.connect();
     byte[] tmp = new byte[1024];
     boolean allow = true;
     while (allow) {
       while (in.available() > 0) {
         int i = in.read(tmp, 0, 1024);
         if (i < 0) break;
         result.append(new String(tmp, 0, i));
       }
       if (channel.isClosed()) {
         if (in.available() > 0) continue;
         System.out.println("exit-status: " + channel.getExitStatus());
         break;
       }
     }
     channel.disconnect();
     return result.toString();
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Example #2
0
 /**
  * Tries to create a directory path on the target system
  *
  * @param path to create
  * @param connnection to use
  */
 private void makePath(String path, Session session) throws IOException {
   ChannelExec channel = null;
   String trimmed = path;
   try {
     while (trimmed.length() > 0 && trimmed.charAt(trimmed.length() - 1) == fileSeparator) {
       trimmed = trimmed.substring(0, trimmed.length() - 1);
     }
     if (trimmed.length() == 0 || checkExistence(trimmed, session)) {
       return;
     }
     int nextSlash = trimmed.lastIndexOf(fileSeparator);
     if (nextSlash > 0) {
       String parent = trimmed.substring(0, nextSlash);
       makePath(parent, session);
     }
     channel = getExecChannel(session);
     String mkdir = replaceArgument(createDirCommand, trimmed);
     Message.debug("SShRepository: trying to create path: " + mkdir);
     channel.setCommand(mkdir);
     StringBuffer stdOut = new StringBuffer();
     StringBuffer stdErr = new StringBuffer();
     readSessionOutput(channel, stdOut, stdErr);
   } finally {
     if (channel != null) {
       channel.disconnect();
     }
   }
 }
Example #3
0
 /*
  * (non-Javadoc)
  *
  * @see org.apache.ivy.repository.Repository#list(java.lang.String)
  */
 public List list(String parent) throws IOException {
   Message.debug("SShRepository:list called: " + parent);
   ArrayList result = new ArrayList();
   Session session = null;
   ChannelExec channel = null;
   session = getSession(parent);
   channel = getExecChannel(session);
   URI parentUri = null;
   try {
     parentUri = new URI(parent);
   } catch (URISyntaxException e) {
     IOException ioe = new IOException("The uri '" + parent + "' is not valid!");
     ioe.initCause(e);
     throw ioe;
   }
   String fullCmd = replaceArgument(listCommand, parentUri.getPath());
   channel.setCommand(fullCmd);
   StringBuffer stdOut = new StringBuffer();
   StringBuffer stdErr = new StringBuffer();
   readSessionOutput(channel, stdOut, stdErr);
   if (channel.getExitStatus() != 0) {
     Message.error("Ssh ListCommand exited with status != 0");
     Message.error(stdErr.toString());
     return null;
   } else {
     BufferedReader br = new BufferedReader(new StringReader(stdOut.toString()));
     String line = null;
     while ((line = br.readLine()) != null) {
       result.add(line);
     }
   }
   return result;
 }
  /**
   * This will execute the given command with given session and session is not closed at the end.
   *
   * @param commandInfo
   * @param session
   * @param commandOutput
   * @throws SSHApiException
   */
  public static Session executeCommand(
      CommandInfo commandInfo, Session session, CommandOutput commandOutput)
      throws SSHApiException {

    String command = commandInfo.getCommand();

    Channel channel = null;
    try {
      if (!session.isConnected()) {
        session.connect();
      }
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
    } catch (JSchException e) {
      session.disconnect();

      throw new SSHApiException("Unable to execute command - ", e);
    }

    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(commandOutput.getStandardError());
    try {
      channel.connect();
    } catch (JSchException e) {

      channel.disconnect();
      session.disconnect();
      throw new SSHApiException("Unable to retrieve command output. Command - " + command, e);
    }

    commandOutput.onOutput(channel);
    // Only disconnecting the channel, session can be reused
    channel.disconnect();
    return session;
  }
Example #5
0
 private void executeCommand(final String command) throws JSchException, IOException {
   c = (ChannelExec) session.openChannel("exec");
   c.setCommand(command);
   latestChannelOutputStream = c.getOutputStream();
   latestChannelInputStream = c.getInputStream();
   c.connect();
 }
  public ExecResult executeCommand(Session session, String command, String workingDir)
      throws PortalServiceException {
    ChannelExec channel = null;
    if (workingDir != null) {
      command = "cd " + workingDir + "; " + command;
    }

    try {
      channel = (ChannelExec) session.openChannel("exec");
      channel.setCommand(command);
      channel.setInputStream(null);
      channel.setErrStream(null);

      channel.connect();

      try (InputStream out = channel.getInputStream();
          InputStream err = channel.getErrStream()) {
        String outStr = readStream(out, channel);
        String errStr = readStream(err, channel);
        return new ExecResult(outStr, errStr, channel.getExitStatus());
      } catch (IOException | InterruptedException e) {
        throw new PortalServiceException(e.getMessage(), e);
      }
    } catch (JSchException e) {
      throw new PortalServiceException(e.getMessage(), e);
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
Example #7
0
  private String execAndGetOutput(String command)
      throws JSchException, MachineException, IOException {
    ChannelExec exec = (ChannelExec) session.openChannel("exec");
    exec.setCommand(command);

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        InputStream erStream = exec.getErrStream()) {

      exec.connect(connectionTimeout);

      ListLineConsumer listLineConsumer = new ListLineConsumer();
      String line;
      while ((line = reader.readLine()) != null) {
        listLineConsumer.writeLine(line);
      }
      // read stream to wait until command finishes its work
      IoUtil.readStream(erStream);
      if (exec.getExitStatus() != 0) {
        throw new MachineException(
            format(
                "Error code: %s. Error: %s",
                exec.getExitStatus(), IoUtil.readAndCloseQuietly(exec.getErrStream())));
      }
      return listLineConsumer.getText();
    } finally {
      exec.disconnect();
    }
  }
Example #8
0
 /**
  * check for existence of file or dir on target system
  *
  * @param filePath to the object to check
  * @param session to use
  * @return true: object exists, false otherwise
  */
 private boolean checkExistence(String filePath, Session session) throws IOException {
   Message.debug("SShRepository: checkExistence called: " + filePath);
   ChannelExec channel = null;
   channel = getExecChannel(session);
   String fullCmd = replaceArgument(existCommand, filePath);
   channel.setCommand(fullCmd);
   StringBuffer stdOut = new StringBuffer();
   StringBuffer stdErr = new StringBuffer();
   readSessionOutput(channel, stdOut, stdErr);
   return channel.getExitStatus() == 0;
 }
Example #9
0
  /**
   * Copy a file to specific destination with WinSCP command
   *
   * @param lfile file you want to transfer
   * @param rfile destination file
   */
  public synchronized void scpTo(String lfile, String rfile) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    try {
      // exec 'scp -t rfile' remotely
      String command = "scp -p -t " + rfile;

      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      // get I/O streams for remote scp
      OutputStream out = channel.getOutputStream();
      InputStream in = channel.getInputStream();

      channel.connect();

      // byte[] tmp = new byte[1];
      checkAck(in);

      // send "C0644 filesize filename", where filename should not include '/'
      int filesize = (int) (new File(lfile)).length();
      command = "C0644 " + filesize + " ";
      if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
      } else {
        command += lfile;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      checkAck(in);

      // send a content of lfile
      FileInputStream fis = new FileInputStream(lfile);
      byte[] buf = new byte[1024];
      while (true) {
        int len = fis.read(buf, 0, buf.length);
        if (len <= 0) break;
        out.write(buf, 0, len);
        out.flush();
      }
      fis.close();

      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();

      checkAck(in);
    } catch (Exception e) {
      throw new ItemNotFoundException("Failed to copy file: " + e.getMessage());
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
Example #10
0
 /**
  * FIXME Comment this
  *
  * @param session
  * @param cmd
  * @return return code of the process.
  * @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
  */
 private int executeCommand(Session session, String cmd)
     throws JSchException, IOException, TimeoutException {
   final ChannelExec channel;
   session.setTimeout((int) maxwait);
   /* execute the command */
   channel = (ChannelExec) session.openChannel("exec");
   channel.setCommand(cmd);
   attachStreams(channel);
   project.log("executing command: " + cmd, Project.MSG_VERBOSE);
   channel.connect();
   try {
     waitFor(channel);
   } finally {
     streamHandler.stop();
     closeStreams(channel);
   }
   return channel.getExitStatus();
 }
  private static void runCommandOnHost(String host, String user, String password, String command) {
    try {
      JSch jsch = new JSch();

      Session session = jsch.getSession(user, host, 22);
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.setPassword(password);
      session.connect();
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      channel.setInputStream(null);

      ((ChannelExec) channel).setErrStream(System.err);

      InputStream in = channel.getInputStream();

      channel.connect();

      byte[] tmp = new byte[1024];
      while (true) {
        while (in.available() > 0) {
          int i = in.read(tmp, 0, 1024);
          if (i < 0) break;
        }
        if (channel.isClosed()) {
          if (in.available() > 0) continue;
          // System.out.println("exit-status: "+channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception ee) {
        }
      }
      channel.disconnect();
      session.disconnect();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Example #12
0
 @Override
 public JschSshProcess createProcess(String commandLine) throws MachineException {
   try {
     ChannelExec exec = (ChannelExec) session.openChannel("exec");
     exec.setCommand(commandLine);
     envVars
         .entrySet()
         .stream()
         .forEach(
             envVariableEntry ->
                 exec.setEnv(envVariableEntry.getKey(), envVariableEntry.getValue()));
     return new JschSshProcess(exec);
   } catch (JSchException e) {
     throw new MachineException(
         "Can't establish connection to perform command execution in ssh machine. Error: "
             + e.getLocalizedMessage(),
         e);
   }
 }
Example #13
0
  /**
   * Reads out the output of a ssh session exec
   *
   * @param channel Channel to read from
   * @param strStdout StringBuffer that receives Session Stdout output
   * @param strStderr StringBuffer that receives Session Stderr output
   * @throws IOException in case of trouble with the network
   */
  private void readSessionOutput(
      ChannelExec channel, StringBuffer strStdout, StringBuffer strStderr) throws IOException {
    InputStream stdout = channel.getInputStream();
    InputStream stderr = channel.getErrStream();

    try {
      channel.connect();
    } catch (JSchException e1) {
      throw (IOException) new IOException("Channel connection problems").initCause(e1);
    }

    byte[] buffer = new byte[BUFFER_SIZE];
    while (true) {
      int avail = 0;
      while ((avail = stdout.available()) > 0) {
        int len = stdout.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail));
        strStdout.append(new String(buffer, 0, len));
      }
      while ((avail = stderr.available()) > 0) {
        int len = stderr.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail));
        strStderr.append(new String(buffer, 0, len));
      }
      if (channel.isClosed()) {
        break;
      }
      try {
        Thread.sleep(POLL_SLEEP_TIME);
      } catch (Exception ee) {
        // ignored
      }
    }
    int avail = 0;
    while ((avail = stdout.available()) > 0) {
      int len = stdout.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail));
      strStdout.append(new String(buffer, 0, len));
    }
    while ((avail = stderr.available()) > 0) {
      int len = stderr.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail));
      strStderr.append(new String(buffer, 0, len));
    }
  }
Example #14
0
 @Override
 public ExecResponse create() throws Exception {
   try {
     ConnectionWithStreams<ChannelExec> connection = execConnection(command);
     executor = acquire(connection);
     String outputString = Strings2.toStringAndClose(connection.getInputStream());
     String errorString = Strings2.toStringAndClose(connection.getErrStream());
     int errorStatus = executor.getExitStatus();
     int i = 0;
     String message = String.format("bad status -1 %s", toString());
     while ((errorStatus = executor.getExitStatus()) == -1
         && i < JschSshClient.this.sshRetries) {
       logger.warn("<< " + message);
       backoffForAttempt(++i, message);
     }
     if (errorStatus == -1) throw new SshException(message);
     return new ExecResponse(outputString, errorString, errorStatus);
   } finally {
     clear();
   }
 }
 /**
  * This method execute the given command over SSH
  *
  * @param session
  * @param command Command to be executed
  * @throws JSchException
  * @throws IOException
  * @throws InterruptedException
  */
 @SuppressWarnings("unused")
 private static void executeCommand(Session session, String command)
     throws JSchException, IOException, InterruptedException {
   InputStream in = null;
   Channel channel = null;
   try {
     channel = session.openChannel("exec");
     ((ChannelExec) channel).setCommand(command);
     channel.setInputStream(null);
     ((ChannelExec) channel).setErrStream(System.err);
     in = channel.getInputStream();
     channel.connect();
     String msg = validateCommandExecution(channel, in);
   } finally {
     if (in != null) {
       in.close();
     }
     if (channel != null) {
       channel.disconnect();
     }
   }
 }
  public String runCommand(String params) {
    try {
      StringBuilder sb = new StringBuilder();
      Channel channel = ConnectionManager.getSession().openChannel("exec");
      channel.setInputStream(null);
      channel.setOutputStream(System.out);
      ((ChannelExec) channel).setCommand(params);
      ((ChannelExec) channel).setPty(false);
      channel.connect();
      InputStream in = channel.getInputStream();
      //			byte[] tmp = new byte[1024];
      while (true) {
        InputStreamReader is = new InputStreamReader(in);

        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();
        while (read != null) {
          System.out.println(read);
          sb.append(read);
          read = br.readLine();
        }
        if (channel.isClosed()) {
          System.out.println(sb.toString());
          System.out.println("exit-status:" + channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception ee) {
        }
      }
      channel.disconnect();
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return "empty";
    }
  }
Example #17
0
 // From org.apache.sshd.ScpTest.java
 protected void sendFile(
     final String path, final String name, final String data, final boolean checkAck)
     throws Exception {
   final String command = "scp -t " + path;
   executeCommand(command);
   if (checkAck) {
     assertEquals(0, latestChannelInputStream.read());
   }
   writeAndFlush("C7777 " + data.length() + " " + name + "\n", checkAck);
   writeAndFlush(data, checkAck);
   writeAndFlush0();
   Thread.sleep(100);
   c.disconnect();
 }
Example #18
0
 public ExecResponse exec(String command) {
   checkConnected();
   ChannelExec executor = null;
   try {
     try {
       executor = (ChannelExec) session.openChannel("exec");
       executor.setPty(true);
     } catch (JSchException e) {
       throw new SshException(
           String.format("%s@%s:%d: Error connecting to exec.", username, host, port), e);
     }
     executor.setCommand(command);
     ByteArrayOutputStream error = new ByteArrayOutputStream();
     executor.setErrStream(error);
     try {
       executor.connect();
       String outputString = Strings2.toStringAndClose(executor.getInputStream());
       String errorString = error.toString();
       int errorStatus = executor.getExitStatus();
       int i = 0;
       while ((errorStatus = executor.getExitStatus()) == -1 && i < this.sshRetries)
         backoffForAttempt(++i, String.format("%s@%s:%d: bad status: -1", username, host, port));
       if (errorStatus == -1)
         throw new SshException(
             String.format(
                 "%s@%s:%d: received exit status %d executing %s",
                 username, host, port, executor.getExitStatus(), command));
       return new ExecResponse(outputString, errorString, errorStatus);
     } catch (Exception e) {
       throw new SshException(
           String.format("%s@%s:%d: Error executing command: %s", username, host, port, command),
           e);
     }
   } finally {
     if (executor != null) executor.disconnect();
   }
 }
Example #19
0
  public void execCmd(String command) {
    //        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    //        String command = "";
    BufferedReader reader = null;
    Channel channel = null;

    try {
      //            while ((command = br.readLine()) != null) {
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
      channel.setInputStream(null);
      ((ChannelExec) channel).setErrStream(System.err);

      channel.connect();
      InputStream in = channel.getInputStream();
      reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
      String buf = null;
      while ((buf = reader.readLine()) != null) {
        System.out.println(buf);
      }
      //            }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      channel.disconnect();
      session.disconnect();
    }
  }
Example #20
0
 public boolean getStreams() {
   try {
     in = channel.getInputStream();
   } catch (IOException e) {
     NeptusLog.pub().error(this + " :: Could not getInputStream.", e);
     execResponse += "\n :: Could not getInputStream. " + e.getMessage();
     return false;
   }
   try {
     out = channel.getOutputStream();
   } catch (IOException e) {
     NeptusLog.pub().error(this + " :: Could not getOutputStream.", e);
     execResponse += "\n :: Could not getOutputStream. " + e.getMessage();
     return false;
   }
   ((ChannelExec) channel).setErrStream(System.err);
   return true;
 }
Example #21
0
  // From org.apache.sshd.ScpTest.java
  protected String readFile(final String path) throws Exception {
    executeCommand("scp -f " + path);
    final String header = readLine(latestChannelInputStream);
    writeAndFlush0();

    int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6)));
    byte[] buffer = new byte[length];
    length = latestChannelInputStream.read(buffer, 0, buffer.length);
    assertEquals(length, buffer.length);
    assertEquals(0, latestChannelInputStream.read());
    writeAndFlush0();

    c.disconnect();
    final String result = new String(buffer);
    assertEquals(
        String.format("C0644 %d %s", result.length(), path.substring(path.lastIndexOf("/") + 1)),
        header);
    return result;
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ecf.provider.filetransfer.outgoing.AbstractOutgoingFileTransfer
   * #openStreams()
   */
  protected void openStreams() throws IncomingFileTransferException {
    try {
      // Set input stream from local file
      final URL url = getRemoteFileURL();
      this.username = url.getUserInfo();

      scpUtil = new ScpUtil(this);
      final Session s = scpUtil.getSession();
      s.connect();

      final String command = SCP_COMMAND + scpUtil.trimTargetFile(url.getPath());
      channel = s.openChannel(SCP_EXEC);
      ((ChannelExec) channel).setCommand(command);
      channel.connect();

      final InputStream ins = channel.getInputStream();
      responseStream = channel.getOutputStream();
      scpUtil.sendZeroToStream(responseStream);

      final int c = checkAck(ins);
      if (c != 'C') throw new IOException(Messages.ScpRetrieveFileTransfer_EXCEPTION_SCP_PROTOCOL);
      // read '0644 '
      final byte[] buf = new byte[1024];
      ins.read(buf, 0, 5);

      setFileLength(readFileSize(ins, buf));
      readFileName(ins, buf);
      // set input stream for reading rest of file
      remoteFileContents = ins;

      scpUtil.sendZeroToStream(responseStream);

      fireReceiveStartEvent();
    } catch (final Exception e) {
      channel = null;
      username = null;
      throw new IncomingFileTransferException(
          NLS.bind(
              Messages.ScpRetrieveFileTransfer_EXCEPTION_CONNECTING, getRemoteFileURL().toString()),
          e);
    }
  }
Example #23
0
  private int execAndGetCode(String command) throws JSchException, IOException {
    ChannelExec exec = (ChannelExec) session.openChannel("exec");
    exec.setCommand(command);

    try (InputStream inStream = exec.getInputStream();
        InputStream erStream = exec.getErrStream()) {

      exec.connect(connectionTimeout);

      // read streams to wait until command finishes its work
      IoUtil.readStream(inStream);
      IoUtil.readStream(erStream);
    } finally {
      exec.disconnect();
    }

    return exec.getExitStatus();
  }
  void scpStringToFile(Session session, String workingDir, String fileName, String userDataString)
      throws PortalServiceException {
    String command = "scp -t " + workingDir + "/" + fileName;

    ChannelExec channel;
    try {
      channel = (ChannelExec) session.openChannel("exec");
    } catch (JSchException e1) {
      throw new PortalServiceException(e1.getMessage(), e1);
    }
    channel.setCommand(command);

    // get I/O streams for remote scp
    try (OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream()) {
      channel.connect();

      checkAck(in);

      byte[] userData = userDataString.getBytes("UTF-8");

      // send "C0644 filesize filename", where filename should not include '/'
      long filesize = userData.length;
      command = "C0644 " + filesize + " " + fileName;
      // if (lfile.lastIndexOf('/') > 0) {
      // command += lfile.substring(lfile.lastIndexOf('/') + 1);
      // } else {
      // command += lfile;
      // }
      command += "\n";
      out.write(command.getBytes());
      out.flush();

      checkAck(in);

      out.write(userData);
      out.write(0);

      out.flush();
      checkAck(in);
      out.close();

    } catch (IOException | JSchException e) {
      throw new PortalServiceException(e.getMessage(), e);
    }

    channel.disconnect();
  }
Example #25
0
  public String Conecta(String host, String command)
      throws JSchException, IOException, InterruptedException {

    ConstantesUsers constantes = new ConstantesUsers();

    JSch jsch = new JSch();
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    Session session = jsch.getSession(constantes.getUser(), host, constantes.getPort());
    session.setPassword(constantes.getPassword());
    session.setConfig(config);
    String saida = null;
    if (!session.isConnected()) {
      session.connect();
      //			System.out.println("Conectado");
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
      InputStream in = channel.getInputStream();
      channel.connect();
      byte[] tmp = new byte[1024];
      while (true) {
        while (in.available() > 0) {
          int i = in.read(tmp, 0, 1024);
          if (i < 0) break;
          //		          System.out.print(new String(tmp, 0, i));
          saida = new String(tmp, 0, i);
        }
        if (channel.isClosed()) {
          channel.disconnect();
          break;
        }
      }

      channel.disconnect();
      session.disconnect();
    } else {
      System.out.println("Conexao já estabelecida");
    }
    return saida;
  }
  /**
   * Gets the value of the specified environment variable.
   *
   * @param ses SSH session.
   * @param cmd environment variable name.
   * @return environment variable value.
   * @throws JSchException In case of SSH error.
   * @throws IOException If failed.
   */
  private String exec(Session ses, String cmd) throws JSchException, IOException {
    ChannelExec ch = null;

    try {
      ch = (ChannelExec) ses.openChannel("exec");

      ch.setCommand(cmd);

      ch.connect();

      try (BufferedReader reader = new BufferedReader(new InputStreamReader(ch.getInputStream()))) {
        return reader.readLine();
      }
    } finally {
      if (ch != null && ch.isConnected()) ch.disconnect();
    }
  }
  public Streams executeCommand(String command, boolean ignoreFailures)
      throws CommandExecutionException {
    ChannelExec channel = null;
    BufferedReader stdoutReader = null;
    BufferedReader stderrReader = null;
    try {
      channel = (ChannelExec) session.openChannel(EXEC_CHANNEL);

      channel.setCommand(command + "\n");

      InputStream stdout = channel.getInputStream();
      InputStream stderr = channel.getErrStream();

      channel.connect();

      stdoutReader = new BufferedReader(new InputStreamReader(stdout));
      stderrReader = new BufferedReader(new InputStreamReader(stderr));

      Streams streams = CommandExecutorStreamProcessor.processStreams(stderrReader, stdoutReader);

      if (streams.getErr().length() > 0 && !ignoreFailures) {
        int exitCode = channel.getExitStatus();
        throw new CommandExecutionException("Exit code: " + exitCode + " - " + streams.getErr());
      }

      return streams;
    } catch (IOException e) {
      throw new CommandExecutionException("Cannot execute remote command: " + command, e);
    } catch (JSchException e) {
      throw new CommandExecutionException("Cannot execute remote command: " + command, e);
    } finally {
      IOUtil.close(stdoutReader);
      IOUtil.close(stderrReader);
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
Example #28
0
    @Override
    public ExecChannel create() throws Exception {
      this.sessionConnection =
          acquire(
              SessionConnection.builder()
                  .from(JschSshClient.this.sessionConnection)
                  .sessionTimeout(0)
                  .build());
      String channel = "exec";
      executor = (ChannelExec) sessionConnection.openChannel(channel);
      executor.setCommand(command);
      executor.setErrStream(new ByteArrayOutputStream());
      InputStream inputStream = executor.getInputStream();
      InputStream errStream = executor.getErrStream();
      OutputStream outStream = executor.getOutputStream();
      executor.connect();
      return new ExecChannel(
          outStream,
          inputStream,
          errStream,
          new Supplier<Integer>() {

            @Override
            public Integer get() {
              int exitStatus = executor.getExitStatus();
              return exitStatus != -1 ? exitStatus : null;
            }
          },
          new Closeable() {

            @Override
            public void close() throws IOException {
              clear();
            }
          });
    }
 /**
  * Open an ssh channel.
  *
  * @param command the command to use
  * @return the channel
  * @throws JSchException on error
  */
 protected Channel openExecChannel(String command) throws JSchException {
   ChannelExec channel = (ChannelExec) session.openChannel("exec");
   channel.setCommand(command);
   return channel;
 }
  public static void main(String[] arg) {
    if (arg.length != 2) {
      System.err.println("usage: java ScpTo file1 user@remotehost:file2");
      System.exit(-1);
    }

    FileInputStream fis = null;
    try {

      String lfile = arg[0];
      String user = arg[1].substring(0, arg[1].indexOf('@'));
      arg[1] = arg[1].substring(arg[1].indexOf('@') + 1);
      String host = arg[1].substring(0, arg[1].indexOf(':'));
      String rfile = arg[1].substring(arg[1].indexOf(':') + 1);

      JSch jsch = new JSch();
      Session session = jsch.getSession(user, host, 22);

      // username and password will be given via UserInfo interface.
      UserInfo ui = new MyUserInfo();
      session.setUserInfo(ui);
      session.connect();

      boolean ptimestamp = true;

      // exec 'scp -t rfile' remotely
      String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile;
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      // get I/O streams for remote scp
      OutputStream out = channel.getOutputStream();
      InputStream in = channel.getInputStream();

      channel.connect();

      if (checkAck(in) != 0) {
        System.exit(0);
      }

      File _lfile = new File(lfile);

      if (ptimestamp) {
        command = "T " + (_lfile.lastModified() / 1000) + " 0";
        // The access time should be sent here,
        // but it is not accessible with JavaAPI ;-<
        command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
      }

      // send "C0644 filesize filename", where filename should not include '/'
      long filesize = _lfile.length();
      command = "C0644 " + filesize + " ";
      if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
      } else {
        command += lfile;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }

      // send a content of lfile
      fis = new FileInputStream(lfile);
      byte[] buf = new byte[1024];
      while (true) {
        int len = fis.read(buf, 0, buf.length);
        if (len <= 0) break;
        out.write(buf, 0, len); // out.flush();
      }
      fis.close();
      fis = null;
      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }
      out.close();

      channel.disconnect();
      session.disconnect();

      System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
    }
  }