Exemple #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 void init() {
   otherHostInfo = getOtherHostInfo();
   JSch jSch = new JSch();
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   try {
     session = jSch.getSession(hostInfo.getUser(), hostInfo.getIp(), hostInfo.getPort());
     session.setConfig(config);
     session.setPassword(hostInfo.getPassword());
     session.connect(5000);
     System.out.println(hostInfo.getIp() + "已连接...");
     channel = session.openChannel("shell");
     channel.connect();
     expect =
         new ExpectBuilder()
             .withOutput(channel.getOutputStream())
             .withInputs(channel.getInputStream(), channel.getExtInputStream())
             .withEchoInput(System.out)
             .withEchoOutput(System.err)
             .withInputFilters(removeColors(), removeNonPrintable())
             .withExceptionOnFailure()
             .withTimeout(80000, TimeUnit.SECONDS)
             .withAutoFlushEcho(true)
             .withCombineInputs(true)
             .build();
     System.out.println(expect.getClass().getName());
   } catch (JSchException | IOException e) {
     e.printStackTrace();
     destroy();
     throw new RuntimeException("无法连接" + hostInfo.getIp() + ":" + hostInfo.getPort());
   }
 }
Exemple #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();
    }
  }
Exemple #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();
      }
    }
  }
 public static ChannelTunnel connect(final Channel channel) throws SshException {
   try {
     final InputStream in = channel.getInputStream();
     final OutputStream out = channel.getOutputStream();
     channel.connect();
     if (!checkAck(in)) {
       throw new SshException("Invalid acknowledgement received");
     }
     return new ChannelTunnel(in, out);
   } catch (IOException e) {
     throw new SshException(e);
   } catch (JSchException e) {
     throw new SshException(e);
   }
 }
Exemple #6
0
 public boolean getStreams() {
   try {
     in = channel.getInputStream();
   } catch (IOException e) {
     NeptusLog.pub().error(this + " :: Could not getInputStream.", e);
     execResponse += "\n :: Could not getInputStream. " + e.getMessage();
     return false;
   }
   try {
     out = channel.getOutputStream();
   } catch (IOException e) {
     NeptusLog.pub().error(this + " :: Could not getOutputStream.", e);
     execResponse += "\n :: Could not getOutputStream. " + e.getMessage();
     return false;
   }
   ((ChannelExec) channel).setErrStream(System.err);
   return true;
 }
  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);
    }
  }
  /*
   * (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);
    }
  }
  /**
   * Creates a channel for shell type in the current session channel types = shell, sftp, exec(X
   * forwarding), direct-tcpip(stream forwarding) etc
   *
   * @param sshContact ID of SSH Contact
   */
  public void createShellChannel(ContactSSH sshContact) throws IOException {
    try {
      Channel shellChannel = sshContact.getSSHSession().openChannel("shell");

      // initalizing the reader and writers of ssh contact
      sshContact.initializeShellIO(shellChannel.getInputStream(), shellChannel.getOutputStream());

      ((ChannelShell) shellChannel)
          .setPtyType(sshContact.getSSHConfigurationForm().getTerminalType());

      // initializing the shell
      shellChannel.connect(1000);

      sshContact.setShellChannel(shellChannel);

      sshContact.sendLine("export PS1=");
    } catch (JSchException ex) {
      sshContact.setSSHSession(null);
      throw new IOException("Unable to create shell channel to remote" + " server");
    }
  }
Exemple #10
0
 public String sendCommandShellChannel(Session session, List<String> lstCommand, String expected) {
   StringBuilder result = new StringBuilder();
   try {
     Channel channel = session.openChannel("shell");
     Expect expect = new Expect(channel.getInputStream(), channel.getOutputStream());
     expect.setDefault_timeout(30);
     channel.connect();
     for (String command : lstCommand) {
       Pattern p = Pattern.compile("ssh\\s\\w*@\\d*.\\d*.\\d*.\\d*");
       Matcher m = p.matcher(command);
       int start = 0;
       int end = 0;
       while (m.find()) {
         start = m.start();
         end = m.end();
       }
       if (start == 0 && end == 0) { // khong chay command ssh mtc@...
         expect.expect(expected);
         expect.send(command + "\n");
         expect.expect(expected);
         expect.send(command + "\n");
         expect.expect(expected);
         result.append(expect.before + expect.match);
       } else { // chay command ssh mtc@...
         expect.expect("$"); // dang dung o 137
         expect.send(command + "\n"); // send ssh mtc@...
         expect.expect(":");
         result.append(expect.before + expect.match);
         expect.send(passwd); // send passwd
         expect.expect(expected); // send expected cua mtc
         result.append(expect.before + expect.match);
       }
     }
     expect.close();
     return result.toString();
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Exemple #11
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";
    }
  }
Exemple #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");
  }
Exemple #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();
    }
  }
Exemple #16
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();
  }
  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) {
      }
    }
  }
  @Override
  public void run() {
    String monitoredMachineAddress = null;
    String user = null;
    String password = null;
    String host = null;

    for (String metric : getProvidedMetrics()) {
      try {
        if (dcAgent.shouldMonitor(
            new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId()), metric)) {
          Map<String, String> parameters = dcAgent.getParameters(metric);

          monitoredMachineAddress = parameters.get("monitoredMachineAddress");
          user = parameters.get("user");
          password = parameters.get("password");
          host = parameters.get("host");
        }
      } catch (ConfigurationException e) {
        e.printStackTrace();
      }
    }

    JSch jsch = new JSch();

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

      session.setPassword(password);

      session.setConfig("StrictHostKeyChecking", "no");

      session.connect(10 * 1000);

      long startTime = 0;

      while (!fmt.isInterrupted()) {
        if (System.currentTimeMillis() - startTime > 60000) {

          for (String metric : getProvidedMetrics()) {
            if (dcAgent.shouldMonitor(
                new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId()), metric)) {
              Map<String, String> parameters = dcAgent.getParameters(metric);

              period = Integer.valueOf(parameters.get("samplingTime"));
              samplingProb = Double.valueOf(parameters.get("samplingProbability"));
            }
          }

          startTime = System.currentTimeMillis();
        }

        boolean isSent = false;
        if (Math.random() < samplingProb) {
          isSent = true;
        }
        channel = session.openChannel("exec");

        String command =
            "snmpwalk -c public -v 1 " + monitoredMachineAddress + " .1.3.6.1.4.1.2021.51";
        // command = "ls -l";
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        channel.setOutputStream(System.out);
        InputStream in = channel.getInputStream();

        channel.connect();

        BufferedReader buf = new BufferedReader(new InputStreamReader(in));
        String line = "";

        int count = 0;
        boolean isFirst = true;
        String metricName = null;

        while ((line = buf.readLine()) != null) {
          Pattern p = Pattern.compile("\"([^\"]*)\"");
          Matcher m = p.matcher(line);

          while (m.find()) {
            if (isFirst) {
              if (m.group(1).equals("NodeID")) {
                count++;
                metricName = "NodeID";
                System.out.println("NodeID");
                isFirst = false;
              }
              continue;
            } else {
              if (count % 2 == 1) {
                try {
                  if (isSent) {
                    logger.info("Sending datum: {} {} {}", m.group(1), metricName, monitoredTarget);
                    dcAgent.send(
                        new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId()),
                        metricName,
                        m.group(1));
                  }
                } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
                // sendMonitoringDatum(Double.valueOf(m.group(1)),
                // ResourceFactory.createResource(MC.getURI() + metricName), monitoredResourceURL,
                // monitoredResource);
                // System.out.println(metricName+"   "+m.group(1));
                count++;
              } else {
                metricName = m.group(1);
                count++;
              }
            }
          }
        }

        Thread.sleep(period);
      }

    } catch (JSchException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ConfigurationException e) {
      e.printStackTrace();
    }
  }
  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) {
      }
    }
  }
  /*
   * (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);
      }
    }
  }
Exemple #21
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 copyRemoteFile(Session session, String command, String fileLocation)
      throws JSchException, IOException {
    FileOutputStream fos = null;
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    OutputStream out = channel.getOutputStream();
    InputStream in = channel.getInputStream();
    channel.connect();
    bufs = new byte[Constants.ONE_ZERO_TWO_FOUR];

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

    while (true) {
      int c = checkAck(in);
      if (c != 'C') {
        break;
      }

      // read '0644 '
      in.read(bufs, 0, Constants.FIVE);

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

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

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

      // read a content of file
      fos = new FileOutputStream(fileLocation == null ? fileLocation : fileLocation + file);
      filesize = readFile(fos, in, filesize);
      fos.close();
      if (checkAck(in) != 0) {
        System.exit(0);
      }
      // send '\0'
      bufs[0] = 0;
      out.write(bufs, 0, 1);
      out.flush();
    }
  }
  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;
  }
  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 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 "";
  }
Exemple #26
0
  public static void main(String[] arg) {
    if (arg.length != 2) {
      System.err.println("usage: java ScpFrom user@remotehost:file1 file2");
      System.exit(-1);
    }

    FileOutputStream fos = null;
    try {

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

      String prefix = null;
      if (new File(lfile).isDirectory()) {
        prefix = lfile + File.separator;
      }

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

      // 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;
          }
        }

        // System.out.println("filesize="+filesize+", file="+file);

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

        // read a content of lfile
        fos = new FileOutputStream(prefix == null ? lfile : prefix + file);
        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) {
          System.exit(0);
        }

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

      session.disconnect();

      System.exit(0);
    } catch (Exception e) {
      System.out.println(e);
      try {
        if (fos != null) fos.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) {
      }
    }
  }
Exemple #28
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;
  }