Esempio n. 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;
   }
 }
  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);
    }
  }
 /**
  * This method validates the executed command
  *
  * @param channel SSH channel
  * @param in input stream
  * @return Error message if any
  *     <p>If any error occurred
  */
 private static String validateCommandExecution(Channel channel, InputStream in)
     throws IOException, InterruptedException {
   StringBuilder sb = new StringBuilder();
   byte[] tmp = new byte[Constants.ONE_ZERO_TWO_FOUR];
   while (true) {
     while (in.available() > 0) {
       int i = in.read(tmp, 0, Constants.ONE_ZERO_TWO_FOUR);
       if (i < 0) {
         break;
       }
       sb.append(new String(tmp, 0, i));
     }
     if (channel.isClosed()) {
       break;
     }
     Thread.sleep(Constants.THOUSAND);
   }
   return sb.toString();
 }
 String readStream(InputStream in, Channel channel) throws IOException, InterruptedException {
   StringBuilder res = new StringBuilder();
   byte[] tmp = new byte[1024];
   while (true) {
     while (in.available() > 0) {
       int i = in.read(tmp, 0, 1024);
       if (i < 0) {
         break;
       }
       res.append(new String(tmp, 0, i));
     }
     if (channel.isClosed()) {
       if (in.available() > 0) {
         continue;
       }
       break;
     }
     Thread.sleep(1000);
   }
   return res.toString();
 }
Esempio n. 5
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;
  }
  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";
    }
  }
Esempio n. 7
0
  public boolean exec(String command) {
    execResponse = "";
    if (!prepareChannel()) {
      sessionCleanup();
      return false;
    }

    // channel.setXForwarding(true);

    // channel.setInputStream(System.in);
    // channel.setOutputStream(System.out);

    // FileOutputStream fos=new FileOutputStream("/tmp/stderr");
    // ((ChannelExec)channel).setErrStream(fos);
    // ((ChannelExec) channel).setErrStream(System.err);

    if (!getStreams()) {
      sessionCleanup();
      return false;
    }

    if (command.equalsIgnoreCase(ADJUST_DATE)) {
      command = getAdjustDateCommand();
    }
    setCommand(command);

    if (!connectChannel()) {
      channelCleanup();
      sessionCleanup();
      return false;
    }
    NeptusLog.pub().info("Date to set in vehicle '" + vehicleId + "': " + command);

    try {
      byte[] tmp = new byte[1024];
      while (true) {
        while (in.available() > 0) {
          int i = in.read(tmp, 0, 1024);
          if (i < 0) break;
          String tmpStr = new String(tmp, 0, i);
          execResponse += "\n" + tmpStr;
          System.out.print(tmpStr);
        }
        if (channel.isClosed()) {
          NeptusLog.pub().info("<###>exit-status: " + channel.getExitStatus());
          exitStatus = channel.getExitStatus();
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception ee) {
          NeptusLog.pub().error(ee.getStackTrace());
        }
      }
    } catch (IOException e) {
      NeptusLog.pub().error(this + " :: Error reading from InputStream.", e);
      execResponse += "\n :: Error reading from InputStream. " + e.getMessage();
      channel.disconnect();
      session.disconnect();
      return false;
    }
    exitStatus = channel.getExitStatus();
    channel.disconnect();
    session.disconnect();
    return (exitStatus == 0) ? true : false;
  }
  public String send(String command) throws IOException {
    if (isClosed()) {
      connect(this.host, this.port, this.username, this.password);
    }
    // System.out.println("begin to send cmd = " + command);
    Channel channel = null;
    try {
      channel = session.openChannel("shell");
    } catch (JSchException e) {
      e.printStackTrace();
    }

    if (channel == null) {
      System.out.println("can not open channel shell");
      return null;
    }
    StringBuilder sb = new StringBuilder();
    String result = "";
    String request = new String("echo " + identity + "\n" + command + "\n" + "\nexit\n");
    ChannelShell shell = (ChannelShell) channel;
    shell.setPtyType("vt320", 512, 100, 1024, 768);
    try {
      InputStream input = new ByteArrayInputStream(request.getBytes());
      channel.setInputStream(input);

      input = new ByteArrayInputStream(request.getBytes());
      channel.setInputStream(input);

      InputStream in = channel.getInputStream();

      // channel.setOutputStream(out);
      // channel.setExtOutputStream(System.err);
      channel.connect();

      byte[] tmp = new byte[1024];
      while (true) {
        // System.out.println("waiting for input ...");
        // avai = in.available();
        // System.out.println("available = "+avai );
        while ((in.available()) > 0) {
          // System.out.println("begin to read");
          int i = in.read(tmp, 0, 1024);
          // System.out.println("i" + " = "+ i);
          if (i < 0) break;
          sb.append(new String(tmp, 0, i));
          // System.out.println("sb = " + sb.toString());
          // avai = 0;
        }
        if (channel.isClosed()) {
          // System.out.println("exit-status: " +
          // channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(200);
        } catch (Exception ee) {
        }
      }

      String executeResult = sb.toString();
      executeResult = executeResult.replaceAll("\r\n", "\n");
      if (executeResult.length() > 0) {
        // if(command.indexOf("entstat")>=0)
        // SysLogger.info(executeResult);

        String[] results = executeResult.split("\n");

        sb.setLength(0);

        boolean needAppend = false;

        // if(command.indexOf("entstat")>=0){
        // for(int i = 0 ; i < results.length - 1 ; i++)
        // {
        // String line = results[i];
        // SysLogger.info(line);
        // }
        // }

        for (int i = 0; i < results.length - 1; i++) {
          String line = results[i];
          // if(command.indexOf("entstat")>=0)
          // SysLogger.info(line);
          if (needAppend) {
            // if(command.indexOf("entstat")>=0)
            // SysLogger.info("&&&&&&&&&& "+i+" ====
            // "+(results.length - 2));
            if (line.contains(" exit") && i >= results.length - 2) {
              // SysLogger.info(line);
              needAppend = false;
              break;
            }
            // if(command.indexOf("entstat")>=0)
            // SysLogger.info(line);
            sb.append(line);
            sb.append("\n");
          } else {
            // if(command.indexOf("entstat")>=0)
            // SysLogger.info(line);
            if (line.equals(identity)
                || line.equals("$" + identity)
                || line.equals("#" + identity)) {
              // if(command.indexOf("entstat")>=0)
              // SysLogger.info(results[i+1]);
              if (results[i + 1].indexOf("Hardware Address:") >= 0
                  || results[i + 1].indexOf("load average:") >= 0
                  || results[i + 1].indexOf("$hdisk") >= 0
                  || results[i + 1].indexOf("BEIST") >= 0
                  || command.equalsIgnoreCase("lsuser ALL")
                  || results[i + 1].indexOf("$AIX") >= 0
                  || command.equalsIgnoreCase("cat /etc/group")) {

                needAppend = true;
              } else {
                i++;
                needAppend = true;
              }
            }
          }
        }

        if (sb.length() > 1) {
          sb.setLength(sb.length() - 1);
        }

        result = sb.toString();

        // SysLogger.info("cmd = " + command + " , result = " + result);
        return result;
      }

    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      channel.disconnect();
    }

    // System.out.println("cmd = " + command + " result = " + result);
    // log("cmd = " + command + " , result = " + result);
    return "";
  }