예제 #1
0
  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";
    }
  }
예제 #2
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();
   }
 }