Exemple #1
0
 @Test(groups = "spring")
 public void testDelete() throws SftpException {
   final Iterable<?> iterable = sftpChannel.ls(".");
   for (Object object : iterable) {
     com.jcraft.jsch.ChannelSftp.LsEntry entry = (LsEntry) object;
     System.out.println(entry.getFilename());
   }
   // assert sftpChannel.lstat("to_delete") == null;
   sftpChannel.put(new ByteArrayInputStream("Hello World!".getBytes()), "to_delete");
   assert sftpChannel.lstat("to_delete") != null;
   sftpChannel.rm("to_delete"); // Will throw exception if fails
 }
  public static void main(String[] s) throws IOException, JSchException, SftpException {
    JSch jsch = new JSch();
    Session session = null;
    session = jsch.getSession("username", "machineIp/hostname", 22);
    session.setPassword("userpass");
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    ChannelSftp channel = null;
    channel = (ChannelSftp) session.openChannel("sftp");
    channel.connect();
    String destinationPath = "C:\\logs\\";
    channel.cd("/home/username/");
    Vector<ChannelSftp.LsEntry> list = channel.ls("*.txt");
    for (ChannelSftp.LsEntry entry : list) {
      channel.get(entry.getFilename(), destinationPath + entry.getFilename());
    }

    channel.disconnect();
    session.disconnect();
  }
  /**
   * Executes a the given command inside a short-lived channel in the session.
   *
   * <p>Performance could be likely improved by reusing a single channel, though the gains would be
   * minimal compared to sharing the Session.
   *
   * @param session Session in which to create the channel
   * @return All standard output from the command
   * @throws JSchException
   * @throws SftpException
   * @throws IOException
   */
  private String doFileTransfer(Session session, String src, String dst, SampleResult res)
      throws JSchException, SftpException, IOException {
    StringBuilder sb = new StringBuilder();
    ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");

    res.sampleStart();
    channel.connect();

    if (SFTP_COMMAND_GET.equals(action)) {

      if (!printFile) {
        channel.get(src, dst);
      } else {
        BufferedReader br = new BufferedReader(new InputStreamReader(channel.get(src)));
        for (String line = br.readLine(); line != null; line = br.readLine()) {
          sb.append(line);
          sb.append("\n");
        }
      }

    } else if (SFTP_COMMAND_PUT.equals(action)) {
      channel.put(src, dst);
    } else if (SFTP_COMMAND_LS.equals(action)) {
      List<ChannelSftp.LsEntry> ls = channel.ls(src);
      for (ChannelSftp.LsEntry line : ls) {
        sb.append(line.getLongname());
        sb.append("\n");
      }
    } else if (SFTP_COMMAND_RM.equals(action)) {
      channel.rm(src);
    } else if (SFTP_COMMAND_RMDIR.equals(action)) {
      channel.rmdir(src);
    } else if (SFTP_COMMAND_RENAME.equals(action)) {
      channel.rename(src, dst);
    }

    res.sampleEnd();

    channel.disconnect();
    return sb.toString();
  }
Exemple #4
0
  public boolean existsFile(String name) throws GenericFileOperationFailedException {
    LOG.trace("existsFile({})", name);
    if (endpoint.isFastExistsCheck()) {
      return fastExistsFile(name);
    }
    // check whether a file already exists
    String directory = FileUtil.onlyPath(name);
    if (directory == null) {
      // assume current dir if no path could be extracted
      directory = ".";
    }
    String onlyName = FileUtil.stripPath(name);

    try {
      @SuppressWarnings("rawtypes")
      Vector files = channel.ls(directory);
      // can return either null or an empty list depending on FTP servers
      if (files == null) {
        return false;
      }
      for (Object file : files) {
        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) file;
        String existing = entry.getFilename();
        LOG.trace("Existing file: {}, target file: {}", existing, name);
        existing = FileUtil.stripPath(existing);
        if (existing != null && existing.equals(onlyName)) {
          return true;
        }
      }
      return false;
    } catch (SftpException e) {
      // or an exception can be thrown with id 2 which means file does not exists
      if (ChannelSftp.SSH_FX_NO_SUCH_FILE == e.id) {
        return false;
      }
      // otherwise its a more serious error so rethrow
      throw new GenericFileOperationFailedException(e.getMessage(), e);
    }
  }
  public static boolean downloadFromSftp(
      String inputFile, String outPutFile, Session session, String testName) {
    Channel chFileDownload = null;
    ChannelSftp channelSftp = null;
    Properties prop = null;
    boolean isFileDownloaded = false;
    String sftpCompleted = "_SFTP_COMPLETED";
    try {
      System.out.println("inside download");
      System.out.println("------------------------------------");
      prop = PropertyReader.getPropeties("OMS");
      sftpCompleted = testName + sftpCompleted;
      sftpCompleted = prop.getProperty(sftpCompleted);
      chFileDownload = session.openChannel("sftp");
      chFileDownload.connect();
      channelSftp = (ChannelSftp) chFileDownload;
      channelSftp.cd(sftpCompleted);
      Vector<ChannelSftp.LsEntry> filelistcomp = channelSftp.ls(sftpCompleted);
      // System.out.println("inputFile---------->"+inputFile);
      // System.out.println("outPutFile---------->"+outPutFile);
      StringBuffer sb = new StringBuffer(inputFile);
      for (ChannelSftp.LsEntry filelist : filelistcomp) {
        if (!filelist.getAttrs().isDir()) {
          if (filelist.getFilename().contains(sb)) {
            // System.out.println("inside download loop");
            channelSftp.get(filelist.getFilename(), outPutFile);
            String filePath = outPutFile + filelist.getFilename();
            // System.out.println("filePath---------->"+filePath);
            File f = new File(outPutFile + filelist.getFilename());
            File targetFile = new File(outPutFile + inputFile);
            if (f.exists()) {
              // System.out.println("File downloaded");
              isFileDownloaded = true;
            }
            f.renameTo(targetFile);
          }
        }
      }

    } catch (Exception e) {

    }
    return isFileDownloaded;
  }
 // 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 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;
  }
  public String downloadFile(
      String host,
      int port,
      String username,
      String password,
      String filePath,
      String fileFormat,
      String fileType) {
    Session session = null;
    Channel channel = null;
    String homeDirectory = System.getProperty("user.home");
    String localDownloadRootDir = homeDirectory + File.separatorChar + host;
    String localDownloadDir = localDownloadRootDir + File.separatorChar + fileType;
    try {
      JSch jsch = new JSch();
      session = jsch.getSession(username, host, port);
      session.setPassword(password);
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.connect();
      System.out.println("Host connected.");
      channel = session.openChannel("sftp");
      channel.connect();
    } catch (JSchException e) {
      System.out.println("Could not connect: " + e.toString());
    }

    if (channel.isConnected()) {

      int grabCount = 0;
      try {
        ChannelSftp c = (ChannelSftp) channel;
        c.cd(filePath);
        File rootPath = new File(localDownloadRootDir);
        File downloadPath = new File(localDownloadDir);
        if (!rootPath.exists()) {
          rootPath.mkdir();
        }
        if (!downloadPath.exists()) {
          downloadPath.mkdir();
        }
        c.lcd(localDownloadDir);
        System.out.println("lcd " + c.lpwd());

        // Get a listing of the remote directory
        @SuppressWarnings("unchecked")
        Vector<ChannelSftp.LsEntry> list = c.ls(".");

        // iterate through objects in list, identifying specific file names
        for (ChannelSftp.LsEntry oListItem : list) {
          // output each item from directory listing for logs

          if (oListItem.getFilename().contains(fileFormat)) {
            System.out.println(oListItem.toString());
            // If it is a file (not a directory)
            if (!oListItem.getAttrs().isDir()) {
              // Grab the remote file ([remote filename], [local path/filename to write file to])

              System.out.println("get " + oListItem.getFilename());
              c.get(
                  oListItem.getFilename(),
                  oListItem
                      .getFilename()); // while testing, disable this or all of your test files will
                                       // be grabbed

              grabCount++;

              // Delete remote file
              if (!fileFormat.equalsIgnoreCase(".der")) {
                c.rm(
                    oListItem
                        .getFilename()); // Note for SFTP grabs from this remote host, deleting the
                                         // file is unnecessary,
                //   as their system automatically moves an item to the 'downloaded' subfolder
                //   after it has been grabbed.  For other target hosts, un comment this line to
                // remove any downloaded files from the inbox.
              }
            }
          }
        }

        // Report files grabbed to log
        if (grabCount == 0) {
          System.out.println("Found no new files to grab.");
        } else {
          System.out.println("Retrieved " + grabCount + " new files.");
        }
      } catch (SftpException e) {
        System.out.println(e.toString());
      } finally {
        // disconnect session.  If this is not done, the job will hang and leave log files locked
        session.disconnect();
        System.out.println("Session Closed");
      }
    }
    return localDownloadDir;
  }