示例#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 void runJschTest(int port) throws Exception {
    JSchLogger.init();
    JSch sch = new JSch();
    JSch.setConfig("cipher.s2c", CRYPT_NAMES);
    JSch.setConfig("cipher.c2s", CRYPT_NAMES);
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), "localhost", port);
    s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
    s.connect();

    try {
      com.jcraft.jsch.Channel c = s.openChannel("shell");
      c.connect();

      try (OutputStream os = c.getOutputStream();
          InputStream is = c.getInputStream()) {
        String expected = "this is my command\n";
        byte[] expData = expected.getBytes(StandardCharsets.UTF_8);
        byte[] actData = new byte[expData.length + Long.SIZE /* just in case */];
        for (int i = 0; i < 10; i++) {
          os.write(expData);
          os.flush();

          int len = is.read(actData);
          String actual = new String(actData, 0, len);
          assertEquals("Mismatched command at iteration " + i, expected, actual);
        }
      } finally {
        c.disconnect();
      }
    } finally {
      s.disconnect();
    }
  }
示例#4
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();
      }
    }
  }
 @Override
 public void stop() {
   channel.disconnect();
   session.disconnect();
   while (!fmt.isInterrupted()) {
     fmt.interrupt();
   }
   System.out.println("Flexiant cloud monitor stopped!");
 }
示例#6
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;
  }
示例#7
0
 @Override
 public void send(String path, String filename, Binary content) throws IOException {
   Session session = null;
   Channel channel = null;
   ChannelSftp channelSftp = null;
   logger.debug("preparing the host information for sftp.");
   InputStream data = null;
   try {
     JSch jsch = new JSch();
     session = jsch.getSession(this.username, this.server, this.remotePort);
     if (this.password != null) {
       session.setPassword(this.password);
     }
     java.util.Properties config = new java.util.Properties();
     config.put("StrictHostKeyChecking", "no");
     session.setConfig(config);
     session.connect();
     logger.debug("Host connected.");
     channel = session.openChannel("sftp");
     channel.connect();
     logger.debug("sftp channel opened and connected.");
     channelSftp = (ChannelSftp) channel;
     if (path != null) {
       channelSftp.cd(path);
     }
     File f = new File(filename);
     data = content.getDataAsStream();
     channelSftp.put(data, f.getName());
     logger.info("File transfered successfully to host.");
   } catch (Exception ex) {
     throw new IOException("SFTP problem", ex);
   } finally {
     if (data != null) {
       try {
         data.close();
       } catch (IOException e) {
       }
     }
     if (channelSftp != null) {
       channelSftp.exit();
     }
     logger.info("sftp Channel exited.");
     if (channel != null) {
       channel.disconnect();
     }
     logger.info("Channel disconnected.");
     if (session != null) {
       session.disconnect();
     }
     logger.info("Host Session disconnected.");
   }
 }
示例#8
0
  public void disconnect() {
    if (connected) {
      if (channel != null) {
        channel.disconnect();
        channel = null;
      }

      if (session != null) {
        session.disconnect();
        session = null;
      }

      connected = false;
    }
  }
 public void destroy() {
   if (channel != null) {
     channel.disconnect();
   }
   if (expect != null) {
     try {
       expect.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   if (session != null) {
     session.disconnect();
   }
 }
  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 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();
     }
   }
 }
 // Removing the Files from Error and completed folder
 public static boolean deleteFileFromSftp(
     String sftpCompleted, Session session, String sftpError) {
   Channel chFileRemove = null;
   ChannelSftp channelSftp = null;
   Properties prop = null;
   boolean isFileRemoved = false;
   boolean isFileComp = false;
   boolean isFileError = false;
   try {
     session.connect();
     prop = PropertyReader.getPropeties("OMS");
     // sftpCompleted=prop.getProperty(sftpCompleted);
     chFileRemove = session.openChannel("sftp");
     chFileRemove.connect();
     channelSftp = (ChannelSftp) chFileRemove;
     channelSftp.cd(sftpCompleted);
     Vector<ChannelSftp.LsEntry> filelist = channelSftp.ls(sftpCompleted);
     // System.out.println("befre filelist-------->"+filelist.size());
     for (ChannelSftp.LsEntry filelistComp : filelist) {
       if (!filelistComp.getAttrs().isDir()) {
         channelSftp.rm(filelistComp.getFilename());
       }
     }
     filelist = channelSftp.ls(sftpError);
     for (ChannelSftp.LsEntry filelistError : filelist) {
       if (!filelistError.getAttrs().isDir()) {
         channelSftp.rm(filelistError.getFilename());
       }
     }
     isFileRemoved = true;
   } catch (Exception e) {
     isFileRemoved = false;
     e.printStackTrace();
   } finally {
     chFileRemove.disconnect();
   }
   return isFileRemoved;
 }
  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";
    }
  }
示例#14
0
  /**
   * Carry out the transfer.
   *
   * @throws IOException on i/o errors
   * @throws JSchException on errors detected by scp
   */
  public void execute() throws IOException, JSchException {
    String command = "scp -f ";
    if (isRecursive) {
      command += "-r ";
    }
    command += remoteFile;
    Channel channel = openExecChannel(command);
    try {
      // get I/O streams for remote scp
      OutputStream out = channel.getOutputStream();
      InputStream in = channel.getInputStream();

      channel.connect();

      sendAck(out);
      startRemoteCpProtocol(in, out, localFile);
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
    log("done\n");
  }
示例#15
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();
    }
  }
  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) {
      }
    }
  }
  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) {
      }
    }
  }
示例#18
0
  /*
   * (non-Javadoc)
   *
   * @see com.sysfera.godiet.Utils.RemoteAccess#copy(java.io.File,
   * java.lang.String)
   */
  @Override
  public void copy(ConfigurationFile localFile, String remotePath, Path path)
      throws RemoteAccessException {
    InputStream fis = null;

    Channel channel = null;
    try {
      channel = channelManager.getExecChannel(path);
      // exec 'scp -t rfile' remotely
      String command = "scp -p -t " + remotePath + "/";
      ((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) {
        throw new RemoteAccessException("Unable to scp");
        // on : " + user+ "@" + host + ":" + port);
      }

      // send "C0644 filesize filename", where filename should not include
      // '/'
      long filesize = localFile.getContents().getBytes().length;
      String localFileName = localFile.getAbsolutePath();
      command = "C0644 " + filesize + " ";
      if (localFileName.lastIndexOf('/') > 0) {
        command += localFileName.substring(localFileName.lastIndexOf('/') + 1);
      } else {
        command += localFileName;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        throw new RemoteAccessException("Unable to scp ");
        // + user + "@" + host + ":" + port + "Command: " + command);
      }

      // send a content of lfile
      fis = new ByteArrayInputStream(localFile.getContents().getBytes());
      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) {
        throw new RemoteAccessException("Error when close connection ");
        // + user +"@" + host + ":" + port + "Command: " + command);
      }
      out.close();
      channel.disconnect();
    } catch (Exception e) {
      throw new RemoteAccessException("Unable to scp"); // on :
      // " + user + "@"
      // + host + ":" + port, e);
    } finally {
      try {
        if (channel != null) {
          channel.disconnect();
        }
        try {
          if (fis != null) {
            fis.close();
          }
        } catch (Exception ee) {
        }
      } catch (Exception e) {
        log.error("SSH disconnect error", e);
      }
    }
  }
  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 "";
  }
示例#20
0
 public void channelCleanup() {
   if (channel != null) channel.disconnect();
 }
示例#21
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;
  }
  /**
   * 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();
  }
示例#23
0
  public void uploadFile(
      String pathLocalFile, String remoteFile, String host, String user, String pass) {
    System.out.println("++++++Start Upload File");
    FileInputStream fis = null;
    try {
      // String lfile =
      // "C:\\Users\\Dee\\AISTunerconfig\\Tuner\\var\\temp\\smf.E00.x.0";
      // String user = "******";
      // String host = "10.239.23.178";
      // String rfile = "/Users/test/equinox.conf/Config/smf.E00.x.0";

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

      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.connect();

      boolean ptimestamp = true;

      // exec 'scp -t rfile' remotely
      String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteFile;
      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(pathLocalFile);

      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 (pathLocalFile.lastIndexOf('/') > 0) {
        command += pathLocalFile.substring(pathLocalFile.lastIndexOf('/') + 1);
      } else {
        command += pathLocalFile;
      }
      command += "\n";
      out.write(command.getBytes());
      out.flush();
      if (checkAck(in) != 0) {
        System.exit(0);
      }

      // send a content of lfile
      fis = new FileInputStream(pathLocalFile);
      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.out.println("++++++Upload File Suscess");
      // System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
    }
  }
示例#24
0
  private static void testDownloadStp() throws JSchException, SftpException {
    Channel channel = null;
    Session session = null;
    OutputStream os = null;
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    try {
      JSch jsch = new JSch();

      // jsch.setKnownHosts("/home/foo/.ssh/known_hosts");

      String user = "******";
      String host = "10.238.226.75";

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

      String passwd = "sdpuser";
      session.setPassword(passwd);

      UserInfo ui =
          new MyUserInfo() {
            public void showMessage(String message) {
              //	          JOptionPane.showMessageDialog(null, message);
            }

            public boolean promptYesNo(String message) {
              //	          Object[] options={ "yes", "no" };
              //	          int foo=JOptionPane.showOptionDialog(null,
              //	                                               message,
              //	                                               "Warning",
              //	                                               JOptionPane.DEFAULT_OPTION,
              //	                                               JOptionPane.WARNING_MESSAGE,
              //	                                               null, options, options[0]);
              return true;
            }

            // If password is not given before the invocation of Session#connect(),
            // implement also following methods,
            //   * UserInfo#getPassword(),
            //   * UserInfo#promptPassword(String message) and
            //   * UIKeyboardInteractive#promptKeyboardInteractive()

          };

      session.setUserInfo(ui);

      // It must not be recommended, but if you want to skip host-key check,
      // invoke following,
      // session.setConfig("StrictHostKeyChecking", "no");

      // session.connect();
      session.connect(30000); // making a connection with timeout.

      channel = session.openChannel("sftp");

      channel.connect(3 * 1000);

      ChannelSftp sftp = (ChannelSftp) channel;

      sftp.cd("/var/opt/fds/logs");
      byte[] buffer = new byte[1024];
      bis = new BufferedInputStream(sftp.get("TTMonitor.log"));
      File newFile = new File("D:/Doneeeeeeeee.java");
      os = new FileOutputStream(newFile);
      bos = new BufferedOutputStream(os);
      int readCount;
      System.out.println("Getting: the file");
      while ((readCount = bis.read(buffer)) > 0) {
        System.out.println("Writing ");
        bos.write(buffer, 0, readCount);
      }

      System.out.println("Done :) ");
      //		    System.out.println(sftp.getHome());
      //		    for (Object o : sftp.ls("")) {
      //		        System.out.println(((ChannelSftp.LsEntry)o).getFilename());
      //		    }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      //	      Session session=jsch.getSession("usersdp","10.238.226.75",22);

      try {
        if (os != null) {
          os.close();
        }
        if (bis != null) {
          bis.close();
        }
        if (bos != null) {
          bos.close();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      channel.disconnect();
      session.disconnect();
    }
  }
示例#25
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;
    }
  }
示例#26
0
 /**
  * Close a channel
  *
  * @param channel channel; can be null
  */
 protected void closeChannel(Channel channel) {
   if (channel != null) {
     channel.disconnect();
   }
 }
示例#27
0
  private static void testUploadStp() throws JSchException, SftpException {
    Channel channel = null;
    Session session = null;

    try {
      JSch jsch = new JSch();

      // jsch.setKnownHosts("/home/foo/.ssh/known_hosts");

      String user = "******";
      String host = "10.238.226.75";

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

      String passwd = "sdpuser";
      session.setPassword(passwd);

      UserInfo ui =
          new MyUserInfo() {
            public void showMessage(String message) {
              //	          JOptionPane.showMessageDialog(null, message);
            }

            public boolean promptYesNo(String message) {
              //	          Object[] options={ "yes", "no" };
              //	          int foo=JOptionPane.showOptionDialog(null,
              //	                                               message,
              //	                                               "Warning",
              //	                                               JOptionPane.DEFAULT_OPTION,
              //	                                               JOptionPane.WARNING_MESSAGE,
              //	                                               null, options, options[0]);
              return true;
            }

            // If password is not given before the invocation of Session#connect(),
            // implement also following methods,
            //   * UserInfo#getPassword(),
            //   * UserInfo#promptPassword(String message) and
            //   * UIKeyboardInteractive#promptKeyboardInteractive()

          };

      session.setUserInfo(ui);

      // It must not be recommended, but if you want to skip host-key check,
      // invoke following,
      // session.setConfig("StrictHostKeyChecking", "no");

      // session.connect();
      session.connect(30000); // making a connection with timeout.

      channel = session.openChannel("sftp");

      channel.connect(3 * 1000);

      ChannelSftp sftp = (ChannelSftp) channel;

      sftp.cd("/var/opt/fds/logs");
      File f = new File("D:/Doneeeeeeeee.java");
      FileInputStream uploadStream = new FileInputStream(f);
      sftp.put(uploadStream, f.getName());

      System.out.println("Done :) ");
      //		    System.out.println(sftp.getHome());
      //		    for (Object o : sftp.ls("")) {
      //		        System.out.println(((ChannelSftp.LsEntry)o).getFilename());
      //		    }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      //	      Session session=jsch.getSession("usersdp","10.238.226.75",22);

      channel.disconnect();
      session.disconnect();
    }
  }
  public static boolean fileTransfer(
      String ifile[],
      String rfile[],
      Session session,
      String inFile1,
      String inFile2,
      String testName) {
    FileInputStream fis = null;
    Properties prop = null;
    String command = "";
    OutputStream out = null;
    InputStream in = null;
    Vector filelist = null;
    Channel chFileProcess = null;
    ChannelSftp channelSftp = null;
    ChannelSftp channelSftpcomp = null;
    long filesize = 0;
    String sftpMonitor = testName + "_SFTP_MONITOR";
    String sftpCompleted = testName + "_SFTP_COMPLETED";
    boolean isFileProcessed = false;
    prop = PropertyReader.getPropeties("OMS");
    sftpMonitor = prop.getProperty(sftpMonitor);
    sftpCompleted = prop.getProperty(sftpCompleted);
    try {
      System.out.println("Connection to the Remote Server succeeded");
      System.out.println("------------------------------------------------------");
      Channel chFilesTransfer = null;
      // session.connect();
      for (int iloop = 0; iloop < ifile.length; iloop++) {
        boolean ptimestamp = true;
        command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile[iloop];
        chFilesTransfer = session.openChannel("exec");
        ((ChannelExec) chFilesTransfer).setCommand(command);
        // get I/O streams for remote scp
        out = chFilesTransfer.getOutputStream();
        in = chFilesTransfer.getInputStream();
        chFilesTransfer.connect();
        System.out.println("Channel opened for file transfer of " + ifile[iloop]);
        System.out.println("------------------------------------------------------");
        if (checkAck(in) != 0) {
          System.exit(0);
        }
        File _lfile = new File(ifile[iloop]);
        if (ptimestamp) {
          command = "T " + (_lfile.lastModified() / 1000) + " 0";
          command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
          out.write(command.getBytes());
          out.flush();
          if (checkAck(in) != 0) {
            System.exit(0);
          }
        }
        filesize = _lfile.length();
        command = "C0644 " + filesize + " ";
        if (ifile[iloop].lastIndexOf('/') > 0) {
          command += ifile[iloop].substring(ifile[iloop].lastIndexOf('/') + 1);
        } else {
          command += ifile[iloop];
        }
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
        fis = new FileInputStream(ifile[iloop]);
        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();
        out.close();
        if (checkAck(in) != 0) {
          System.exit(0);
        }
      }
      chFilesTransfer.disconnect();
      try {
        Thread.sleep(10000);
        chFileProcess = session.openChannel("sftp");
        chFileProcess.connect();
        channelSftp = (ChannelSftp) chFileProcess;
        channelSftp.cd(sftpMonitor);
        filelist = channelSftp.ls(sftpMonitor);
        Thread.sleep(10000);
        for (int i = 0; i < filelist.size(); i++) {
          // System.out.println("filelist.get(i).toString()---------->"+filelist.get(i).toString());
          Thread.sleep(10000);
          if (filelist.get(i).toString().contains(inFile1)) break;
        }
        channelSftpcomp = (ChannelSftp) chFileProcess;
        channelSftpcomp.cd(sftpCompleted);
        Thread.sleep(50000);
        Vector<ChannelSftp.LsEntry> filelistcomp =
            channelSftp.ls(sftpCompleted); // Thread.sleep(5000);
        StringBuffer sb = new StringBuffer(inFile1);

        for (int icounter = 0; icounter < 10; icounter++) {
          // System.out.println("inside loop");
          // System.out.println("filelist.get(icounter).toString()------>"+filelistcomp.get(icounter).toString());
          for (ChannelSftp.LsEntry filelist1 : filelistcomp) {
            if (!filelist1.getAttrs().isDir()) {
              // String s=filelist1.getFilename();
              // s.contains("test");
              // System.out.println("filelist1.getFilename()--------->"+filelist1.getFilename());
              if (filelist1.getFilename().contains(sb)) {
                isFileProcessed = true;
                break;
              } else {
                Thread.sleep(8000);
              }
            }
            if (isFileProcessed) {
              break;
            }
          }
        }
        if (isFileProcessed) {
          System.out.println("-------------------------------------------");
          System.out.println("File is processes and move to completed folder");
        } else {
          System.out.println("-------------------------------------------");
          System.out.println("File is not processes");
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fis != null) fis.close();
      } catch (Exception ee) {
      }
      // System.exit(0);
    }
    return isFileProcessed;
  }
示例#29
0
  /**
   * copy a file from remote host to local
   *
   * @param rfile
   * @param lfile
   */
  public String scpFrom(String rfile, String lfile) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    FileOutputStream fos = null;
    // When get a rfile which with regular expression, to save the file with the same name as it get
    // from the remote server[add by phoebe]
    String completeLfile = lfile;

    try {
      // 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();

        // When get a rfile which with regular expression, to save the file with the same name as it
        // get from the remote server[add by phoebe]
        if (completeLfile.contains("*")) {
          completeLfile = completeLfile.substring(0, completeLfile.lastIndexOf("/")) + "/" + file;
        }

        // read a content of lfile
        fos = new FileOutputStream(completeLfile);
        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) {
          throw new ActionFailedException("Failed to get Ack, Copy may fail!");
        }

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

    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
    return completeLfile;
  }
示例#30
0
  /**
   * execute the given command in the remote host
   *
   * @param command
   * @return - command output in the remote host
   */
  public String exec(String command) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    StringBuffer data = new StringBuffer();
    OutputStream out = null;
    InputStream in = null;
    try {
      Channel channel;

      boolean channel_connected = false;
      int count = 0;
      while (!channel_connected) {

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

          out = channel.getOutputStream();
          in = channel.getInputStream();
          channel.connect();
          channel_connected = true;
        } catch (Exception e) {
          count++;
          String msg = e.getMessage();
          if (count < 5) {
            AutomationLogger.getInstance()
                .warn(
                    "Failed to connect to SSH server due to "
                        + msg
                        + ". Will try again in 1 second");
            if (msg.startsWith("session is down")) {
              AutomationLogger.getInstance().info("Try to re-connect session");
              connect();
            }
            Timer.sleep(1000);
          } else {
            throw new ActionFailedException("Failed to connect to SSH server due to " + e);
          }
        }
      }

      byte[] buf = new byte[1024];

      // read
      count = 0;
      while ((count = in.read(buf)) > 0) {
        data.append(new String(buf, 0, count));
      }

    } catch (Exception e) {
      AutomationLogger.getInstance().warn(e);
    } finally {
      try {
        in.close();
      } catch (Exception e) {
      }
      try {
        out.close();
      } catch (Exception e) {
      }

      if (channel != null) {
        channel.disconnect();
      }
    }
    return data.toString();
  }