示例#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;
   }
 }
  /**
   * 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;
  }
示例#3
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();
    }
  }
示例#4
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();
     }
   }
 }
示例#5
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;
 }
示例#6
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();
      }
    }
  }
示例#8
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();
      }
    }
  }
示例#9
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;
 }
示例#10
0
  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();
  }
  /**
   * 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();
    }
  }
示例#12
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();
  }
示例#13
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);
    }
  }
示例#15
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);
   }
 }
示例#16
0
  /*
   * (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);
    }
  }
示例#17
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;
  }
 /**
  * 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";
    }
  }
示例#20
0
  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();
      }
    }
  }
示例#21
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();
   }
 }
示例#22
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();
    }
  }
示例#23
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();
            }
          });
    }
  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) {
      }
    }
  }
 /**
  * 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;
 }
  private static void scpConfigFile(
      String host,
      String user,
      String password,
      String runReporterConfigFilePath,
      String remoteFile) {
    FileInputStream fis = null;
    try {

      String lfile = runReporterConfigFilePath;
      String rfile = remoteFile;

      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();
      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();

    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
    }
  }
示例#27
0
  public void transfer(String fromFile, String toFile) throws IOException, JSchException {
    FileInputStream fis = null;
    String rfile = toFile;
    String lfile = fromFile;
    String command = "scp -t " + rfile; // $NON-NLS-1$
    try {
      Channel channel = session.openChannel("exec"); // $NON-NLS-1$
      ((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.out.println("err"); // $NON-NLS-1$
      }

      // send "C0644 filesize filename", where filename should not include
      // '/'
      long filesize = (new File(lfile)).length();
      command = "C0644 " + filesize + " "; // $NON-NLS-1$ //$NON-NLS-2$
      if (lfile.lastIndexOf('/') > 0) {
        command += lfile.substring(lfile.lastIndexOf('/') + 1);
      } else {
        command += lfile;
      }
      command += "\n"; // $NON-NLS-1$

      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        System.out.println("err"); // $NON-NLS-1$
      }

      // 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);
      }
      fis.close();
      fis = null;
      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      if (checkAck(in) != 0) {
        System.out.println("err"); // $NON-NLS-1$
      }
      out.close();

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

    } catch (IOException e) {
      if (fis != null) fis.close();
      throw e;
    }
  }
  private static void scpOutputFile(
      String host,
      String user,
      String password,
      String remoteOutputFilePath,
      String localOutputFilePath) {
    FileOutputStream fos = null;
    try {
      String rfile = remoteOutputFilePath;
      String lfile = localOutputFilePath;

      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();

      // exec 'scp -f rfile' remotely
      String command = "scp -f " + 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();

      byte[] buf = new byte[1024];

      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();
      while (true) {
        int c = checkAck(in);
        if (c != 'C') {
          break;
        }

        // read '0644 '
        in.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
          if (in.read(buf, 0, 1) < 0) {
            // error
            break;
          }
          if (buf[0] == ' ') break;
          filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
          in.read(buf, i, 1);
          if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
          }
        }

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

        // read a content of lfile
        fos = new FileOutputStream(lfile);
        int foo;
        while (true) {
          if (buf.length < filesize) foo = buf.length;
          else foo = (int) filesize;
          foo = in.read(buf, 0, foo);
          if (foo < 0) {
            // error
            break;
          }
          fos.write(buf, 0, foo);
          filesize -= foo;
          if (filesize == 0L) break;
        }
        fos.close();
        fos = null;

        if (checkAck(in) != 0) {
          break;
        }

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

    } catch (Exception e) {
      e.printStackTrace();
      try {
        if (fos != null) fos.close();
      } catch (Exception ee) {
      }
    }
  }
  /**
   * This will not reuse any session, it will create the session and close it at the end
   *
   * @param commandInfo Encapsulated information about command. E.g :- executable name parameters
   *     etc ...
   * @param serverInfo The SSHing server information.
   * @param authenticationInfo Security data needs to be communicated with remote server.
   * @param commandOutput The output of the command.
   * @param configReader configuration required for ssh/gshissh connection
   * @throws SSHApiException throw exception when error occurs
   */
  public static void executeCommand(
      CommandInfo commandInfo,
      ServerInfo serverInfo,
      AuthenticationInfo authenticationInfo,
      CommandOutput commandOutput,
      ConfigReader configReader)
      throws SSHApiException {

    if (authenticationInfo instanceof GSIAuthenticationInfo) {
      System.setProperty(
          X509_CERT_DIR,
          (String)
              ((GSIAuthenticationInfo) authenticationInfo).getProperties().get("X509_CERT_DIR"));
    }

    JSch jsch = new ExtendedJSch();

    log.debug(
        "Connecting to server - "
            + serverInfo.getHost()
            + ":"
            + serverInfo.getPort()
            + " with user name - "
            + serverInfo.getUserName());

    Session session;

    try {
      session =
          jsch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getPort());
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while creating SSH session."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    java.util.Properties config = configReader.getProperties();
    session.setConfig(config);

    // =============================================================
    // Handling vanilla SSH pieces
    // =============================================================
    if (authenticationInfo instanceof SSHPasswordAuthentication) {
      String password =
          ((SSHPasswordAuthentication) authenticationInfo)
              .getPassword(serverInfo.getUserName(), serverInfo.getHost());

      session.setUserInfo(new SSHAPIUIKeyboardInteractive(password));

      // TODO figure out why we need to set password to session
      session.setPassword(password);

    } else if (authenticationInfo instanceof SSHPublicKeyFileAuthentication) {
      SSHPublicKeyFileAuthentication sshPublicKeyFileAuthentication =
          (SSHPublicKeyFileAuthentication) authenticationInfo;

      String privateKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The private key file for vanilla SSH " + privateKeyFile);

      String publicKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The public key file for vanilla SSH " + publicKeyFile);

      Identity identityFile;

      try {
        identityFile = GSISSHIdentityFile.newInstance(privateKeyFile, null, jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using files. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName()
                + " private key file - "
                + privateKeyFile
                + ", public key file - "
                + publicKeyFile,
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);

    } else if (authenticationInfo instanceof SSHPublicKeyAuthentication) {

      SSHPublicKeyAuthentication sshPublicKeyAuthentication =
          (SSHPublicKeyAuthentication) authenticationInfo;

      Identity identityFile;

      try {
        String name = serverInfo.getUserName() + "_" + serverInfo.getHost();
        identityFile =
            GSISSHIdentityFile.newInstance(
                name,
                sshPublicKeyAuthentication.getPrivateKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                sshPublicKeyAuthentication.getPublicKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using byte arrays. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName(),
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);
    }

    // Not a good way, but we dont have any choice
    if (session instanceof ExtendedSession) {
      if (authenticationInfo instanceof GSIAuthenticationInfo) {
        ((ExtendedSession) session)
            .setAuthenticationInfo((GSIAuthenticationInfo) authenticationInfo);
      }
    }

    try {
      session.connect();
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while connecting to server."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    String command = commandInfo.getCommand();

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

      throw new SSHApiException(
          "Unable to execute command - "
              + command
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          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
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    commandOutput.onOutput(channel);

    channel.disconnect();
    session.disconnect();
  }
示例#30
0
 public void setCommand(String command) {
   ((ChannelExec) channel).setCommand(command);
 }