Exemplo n.º 1
0
  private void mkdirs(String path) throws Exception {
    // sftp.cd("/"); //change to the root dir

    // String dirs[] = splitPath(path);

    String cwd = sftp.pwd();
    // System.out.println("CWD: " + cwd);

    while (!path.startsWith(cwd)) {
      System.out.println(cwd + " " + path);
      sftp.cd(".."); // should throw exception if can't cdup
      System.out.println("CDUP!");
      cwd = sftp.pwd();
    }

    String mkPath = path.substring(cwd.length(), path.length());
    System.out.println("DIRS TO MAKE: " + mkPath);

    String dirs[] = splitPath(mkPath);

    for (int i = 0; i < dirs.length; i++) {
      System.out.println("mkdir " + dirs[i]);
      logger.info("mkdir " + dirs[i]);
      // swallow exception that results from trying to
      // make a dir that already exists
      try {
        sftp.mkdir(dirs[i]);
      } catch (Exception ex) {
      }

      // change to the new dir
      // throws an exception if something went wrong
      sftp.cd(dirs[i]);
    }
  }
Exemplo n.º 2
0
  private static void sftpUpload() {
    JSch.setLogger(new JschLogger());
    Session session = null;
    try {
      JSch jsch = new JSch();
      session = jsch.getSession(USERNAME, HOST, PORT);
      session.setPassword(PASSWORD);
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.connect();

      Channel channel = session.openChannel(PROTOCOL_SFTP);
      channel.connect();

      BufferedInputStream in = new BufferedInputStream(new FileInputStream(SOURCE));
      ChannelSftp channelSftp = (ChannelSftp) channel;
      channelSftp.cd(TARGET);
      channelSftp.put(in, FILE_NAME);

    } catch (JSchException | SftpException | FileNotFoundException ex) {
      Logger.getLogger(JschDemo.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (session != null) {
        session.disconnect();
      }
    }
  }
Exemplo n.º 3
0
 public void chdir(String dirToChangeTo) throws KettleJobException {
   try {
     c.cd(dirToChangeTo);
   } catch (SftpException e) {
     throw new KettleJobException(e);
   }
 }
 @Test
 public void testCreateClientFailsIfPwdReturnsRelativePath() throws Exception {
   final String remoteRoot = "some/directory/in/my/home/dir";
   hostConfig = createWithOverrideUsernameAndPassword(mockJSch);
   getHostConfig().setRemoteRootDir(remoteRoot);
   final BapSshCommonConfiguration commonConfiguration =
       new BapSshCommonConfiguration("Ignore me", null, null, false);
   getHostConfig().setCommonConfig(commonConfiguration);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(TEST_PASSPHRASE);
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   expect(mockSftp.pwd()).andReturn("home/bap/" + remoteRoot);
   expect(mockSftp.isConnected()).andReturn(false);
   expect(mockSession.isConnected()).andReturn(false);
   assertCreateClientThrowsException("home/bap/" + remoteRoot);
 }
 @Test
 public void testCreateClientWillUseKeyIfKeyAndKeyPathPresent() throws Exception {
   final String testKey = "MyVeryBigKey";
   final BapSshCommonConfiguration defaultKeyInfo =
       new BapSshCommonConfiguration(
           TEST_PASSPHRASE, testKey, "/this/file/will/not/be/used", false);
   hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo);
   getHostConfig().setPassword("Ignore me");
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockJSch.addIdentity(
       isA(String.class),
       aryEq(BapSshUtil.toBytes(testKey)),
       (byte[]) isNull(),
       aryEq(BapSshUtil.toBytes(TEST_PASSPHRASE)));
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   assertCreateClient();
 }
 @Test
 public void testCreateClientWithOverrideKeyPath() throws Exception {
   final String testKeyFilename = "myPrivateKey";
   final RandomFile theKey = new RandomFile(jenkinsHome.getRoot(), testKeyFilename);
   hostConfig =
       createWithOverrideUsernameAndPassword(mockJSch, TEST_PASSPHRASE, testKeyFilename, "");
   final BapSshCommonConfiguration commonConfiguration =
       new BapSshCommonConfiguration("Ignore me", null, null, false);
   getHostConfig().setCommonConfig(commonConfiguration);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockJSch.addIdentity(
       isA(String.class),
       aryEq(theKey.getContents()),
       (byte[]) isNull(),
       aryEq(BapSshUtil.toBytes(TEST_PASSPHRASE)));
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   assertCreateClient();
 }
 private BapSshClient assertCreateClientWithDefaultKey(final boolean disableExec)
     throws Exception {
   final String testKey = "MyVeryBigKey";
   final BapSshCommonConfiguration defaultKeyInfo =
       new BapSshCommonConfiguration(TEST_PASSPHRASE, testKey, null, disableExec);
   hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo);
   getHostConfig().setPassword("Ignore me");
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockJSch.addIdentity(
       isA(String.class),
       aryEq(BapSshUtil.toBytes(testKey)),
       (byte[]) isNull(),
       aryEq(BapSshUtil.toBytes(defaultKeyInfo.getPassphrase())));
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   return assertCreateClient();
 }
Exemplo n.º 8
0
  /* (non-Javadoc)
   * @see net.sf.thingamablog.transport.PublishTransport#publishFile(java.lang.String, java.io.File, net.sf.thingamablog.transport.TransportProgress)
   */
  public boolean publishFile(String pubPath, File file, TransportProgress tp) {
    if (sftp == null) {
      failMsg = "SFTP Client not initialized!";
      return false;
    }

    if (!isConnected()) {
      failMsg = "Not Connected!!!";
      return false;
    }

    if (tp.isAborted()) {
      failMsg = "Aborted";
      return false;
    }

    if (!pubPath.endsWith("/")) pubPath += "/"; // append a trailing slash if needed

    try {
      String cwd = sftp.pwd();
      if (!cwd.endsWith("/")) cwd += "/";
      if (!pubPath.equals(cwd)) {
        boolean changedDir = false;
        try {
          sftp.cd(pubPath); // try to change to the pub path
          changedDir = true; // changed dir OK
          System.out.println("Changed to " + pubPath);
        } catch (Exception cdEx) {
          logger.log(Level.WARNING, "Problem changing SFTP dir", cdEx);
        }

        if (!changedDir) {
          // was unable to change dir. the dir likely does not exist
          // so we'll try making the dir structure of pubPath
          mkdirs(pubPath);
          // sftp.cd(pubPath);
        }
      }

      int mode = ChannelSftp.OVERWRITE;
      // String dest = pubPath + file.getName();
      InputStream is = new FileInputStream(file);
      sftp.put(is, file.getName(), new MyProgressMonitor(tp), mode);
      is.close();

      return true;
    } catch (Exception ex) {
      failMsg = "Error publishing file to " + pubPath;
      failMsg += "\n" + ex.getMessage();
      logger.log(Level.WARNING, failMsg, ex);
      ex.printStackTrace();
    }

    return false;
  }
Exemplo n.º 9
0
 private void doChangeDirectory(String path) {
   if (path == null || ".".equals(path) || ObjectHelper.isEmpty(path)) {
     return;
   }
   LOG.trace("Changing directory: {}", path);
   try {
     channel.cd(path);
   } catch (SftpException e) {
     throw new GenericFileOperationFailedException("Cannot change directory to: " + path, e);
   }
 }
Exemplo n.º 10
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.");
   }
 }
Exemplo n.º 11
0
  private static boolean goToServerDirectory() {
    try {
      System.out.println("Accessing ServerDirectory : " + serverDirectory);
      sftpChannel.cd(serverDirectory);
      System.out.println("Accessing ServerDirectory Completed.");
      return true;
    } catch (Exception e) {
      System.out.println(
          "Exception in goToServerDirectory(" + serverDirectory + "): " + e.toString());
      errorMessage +=
          "Exception in goToServerDirectory(" + serverDirectory + "): " + e.toString() + "\n";
    }

    return false;
  }
Exemplo n.º 12
0
  public boolean buildDirectory(String directory, boolean absolute)
      throws GenericFileOperationFailedException {
    // must normalize directory first
    directory = endpoint.getConfiguration().normalizePath(directory);

    LOG.trace("buildDirectory({},{})", directory, absolute);
    // ignore absolute as all dirs are relative with FTP
    boolean success = false;

    String originalDirectory = getCurrentDirectory();
    try {
      // maybe the full directory already exists
      try {
        channel.cd(directory);
        success = true;
      } catch (SftpException e) {
        // ignore, we could not change directory so try to create it instead
      }

      if (!success) {
        LOG.debug("Trying to build remote directory: {}", directory);

        try {
          channel.mkdir(directory);
          success = true;
        } catch (SftpException e) {
          // we are here if the server side doesn't create intermediate folders
          // so create the folder one by one
          success = buildDirectoryChunks(directory);
        }
      }
    } catch (IOException e) {
      throw new GenericFileOperationFailedException("Cannot build directory: " + directory, e);
    } catch (SftpException e) {
      throw new GenericFileOperationFailedException("Cannot build directory: " + directory, e);
    } finally {
      // change back to original directory
      if (originalDirectory != null) {
        changeCurrentDirectory(originalDirectory);
      }
    }

    return success;
  }
Exemplo n.º 13
0
  // src原文件; dst 目标目录
  public static void putDirectory(String src, String dst, ChannelSftp chSftp, String contain)
      throws SftpException {
    // 如果服务器目录不存在,需要创建目录
    try {
      chSftp.cd(dst);
    } catch (SftpException sException) {
      // sException.printStackTrace();
      if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) {
        chSftp.mkdir(dst);
      }
    }
    //
    File file = new File(src);
    File[] dir = file.listFiles();
    // file是文件
    if (dir == null) {

      String f_type = getFileType(src);
      // 匹配上传文件类型
      if (contain.indexOf(f_type) > -1) {
        System.out.println(src + " >>> " + dst);
        // 上传
        // long fileSize = file.length();
        // chSftp.put(src, dst, new FileProgressMonitor(fileSize),
        // ChannelSftp.OVERWRITE);
        chSftp.put(src, dst, ChannelSftp.OVERWRITE);
      }
      return;
    }
    // 目录
    for (int i = 0; i < dir.length; i++) {
      File sub_file = dir[i];
      File[] sub_dir = sub_file.listFiles();
      // 文件
      if (sub_dir == null) {
        putDirectory(sub_file.getPath(), dst, chSftp, contain);
        continue;
      }
      // 目录 需要取目录名
      String sub_name = sub_file.getName();
      putDirectory(src + sub_name + "\\", dst + sub_name + "/", chSftp, contain);
      // System.out.println("subDitr:"+subDir);
    }
  }
  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;
  }
Exemplo n.º 15
0
  /**
   * @param filename The complete filename which will be after receiving file
   * @param user
   * @param host
   * @param password
   * @param remotFolder
   * @return
   */
  public static int getFileSFTP(
      String filename, String user, String host, String password, String remotFolder) {
    ResourceBundle rb = ResourceBundle.getBundle(EzLinkConstant.PATH_CONFIG_PROPERTY_FILE_NAME);
    File f = new File(filename);
    logger.error("SFTP file receive start");
    JSch jsch = new JSch();
    Session session = null;
    int error = 0;
    try {
      session = jsch.getSession(user, host, 22);
      session.setConfig("StrictHostKeyChecking", "no");
      session.setPassword(password);
      //		    UserInfo ui=new MyUserInfo();
      //		      session.setUserInfo(ui);
      session.connect();

      Channel channel = session.openChannel("sftp");
      channel.connect();
      ChannelSftp sftpChannel = (ChannelSftp) channel;
      logger.debug("receiving file:" + f.getAbsolutePath());
      SftpProgressMonitor monitor = new MyProgressMonitor();
      sftpChannel.cd(remotFolder);
      sftpChannel.lcd(f.getParent());
      sftpChannel.get(f.getName(), f.getName(), monitor, ChannelSftp.OVERWRITE);
      sftpChannel.exit();
      //		    session.disconnect();
      logger.error("SFTP file receive successfully");
    } catch (JSchException e) {
      logger.error(
          "File transfer Exception",
          e); // To change body of catch statement use File | Settings | File Templates.
      error = -1;
    } catch (SftpException e) {
      logger.error("SFTP Exception", e);
      error = -2;
      //		} catch (FileNotFoundException e) {
      //			logger.error("File not found to transfer"+filename);
    } finally {

      session.disconnect();
    }
    return error;
  }
  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();
  }
 @Test
 public void testCreateClientWithDefaultPassword() throws Exception {
   final BapSshCommonConfiguration defaultKeyInfo =
       new BapSshCommonConfiguration(TEST_PASSPHRASE, null, null, false);
   hostConfig = createWithDefaultKeyInfo(mockJSch, defaultKeyInfo);
   getHostConfig().setPassword("Ignore me");
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(defaultKeyInfo.getPassphrase());
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   assertCreateClient();
 }
 private BapSshClient assertCreateWithDefaultInfo(final String responseFromPwd)
     throws JSchException, SftpException {
   final BapSshCommonConfiguration commonConfiguration =
       new BapSshCommonConfiguration("Ignore me", null, null, false);
   getHostConfig().setCommonConfig(commonConfiguration);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(getHostConfig().getPassword());
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   if (responseFromPwd != null) expect(mockSftp.pwd()).andReturn(responseFromPwd);
   return assertCreateClient();
 }
 // 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;
 }
Exemplo n.º 20
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();
    }
  }
Exemplo n.º 21
0
 @Test(groups = "spring")
 public void testMkDir() throws JSchException, SftpException {
   sftpChannel.mkdir("./moodir");
   sftpChannel.cd("./moodir");
 }
Exemplo n.º 22
0
 /**
  * push des fichiers sur serveur return liste des anomalies.
  *
  * @return issues list
  */
 public List<IssueBean> pushFilesOnSent() {
   List<IssueBean> issues = new ArrayList<IssueBean>();
   String path = exportFolder;
   if (path == null) {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error, "path d export is null", Categorie.transportSFTP));
     return issues;
   }
   if (path.isEmpty()) {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error, "path d export is empty", Categorie.transportSFTP));
     return issues;
   }
   File folder = new File(path);
   if (!folder.isDirectory()) {
     if (path.isEmpty()) {
       issues.add(
           new IssueBean(
               IssueBean.Severity.error,
               "path d export n est pas un repertoire:<" + path + ">",
               Categorie.transportSFTP));
       return issues;
     }
   }
   if (!folder.exists()) {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error,
             "folder d export n existe pas:<" + path + ">",
             Categorie.transportSFTP));
     return issues;
   }
   // list files and folder
   File[] files = folder.listFiles();
   if (files != null) {
     if (files.length > 0) {
       try {
         ChannelSftp c = createSession();
         c.cd(workingDirectory);
         try {
           int fileCount = 0;
           for (File f : files) {
             if (f.isFile()) {
               fileCount++;
               FileInputStream fis = new FileInputStream(f);
               try {
                 c.put(fis, f.getName());
               } finally {
                 fis.close();
               }
               // move des fichiers envoyes dans le repertoire
               // d envoi
               StringFileTools.moveFile(f, sentFolder);
             }
           }
           if (fileCount == 0) {
             issues.add(
                 new IssueBean(
                     IssueBean.Severity.error,
                     "aucun fichier trouvé dans le dossier  dexport:" + path,
                     Categorie.transportSFTP));
           }
         } catch (Exception e) {
           issues.add(
               new IssueBean(
                   IssueBean.Severity.error,
                   "exception in put file:" + e.getMessage(),
                   Categorie.transportSFTP));
         }
         try {
           destroySession(c);
         } catch (Exception exc) {
           issues.add(
               new IssueBean(
                   IssueBean.Severity.error,
                   " Unable to disconnect exception:" + exc.getMessage(),
                   Categorie.transportSFTP));
         }
       } catch (Exception e) {
         LOGGER.error("unable to connect :" + e.getLocalizedMessage());
         issues.add(
             new IssueBean(
                 IssueBean.Severity.error,
                 " Unable to connect with u="
                     + ftpUserName
                     + ",h="
                     + ftpHost
                     + ",wdir="
                     + workingDirectory
                     + " exception:"
                     + e.getMessage(),
                 Categorie.transportSFTP));
       }
     } else {
       issues.add(
           new IssueBean(
               IssueBean.Severity.error,
               "aucun fichier a envoyer par sftp, size=0",
               Categorie.transportSFTP));
     }
   } else {
     issues.add(
         new IssueBean(
             IssueBean.Severity.error,
             "files is null on folder:" + path,
             Categorie.transportSFTP));
   }
   return issues;
 }
  /**
   * This method should only be run when a new version of the Manager will be released. It tries to
   * make the process more automatic. Currently: - Writes in the Version file in LOCAL DISK (Dropbox
   * folder, so Dropbox must be running!) - Uploads the file to the correct folder tree in the
   * SourceForge project, creating all needed folder on the way.
   */
  public static void main(String[] args) throws ZipException, IOException, JSchException {

    /*
     * IMPORTANT
     *
     * Before releasing a new version of the Manager, please, follow these instructions:
     * 0 - Update the Changelog.txt and Version.txt files
     * 1 - Check if the older version is fully compatible with this one after an update. managerOptions.xml shall not be lost by any reasons.
     * 2 - Check if the file paths below are correct.
     * 3 - Clean and build the project, then Package-for-store the Manager.jar
     * 4 - Goto Sourceforge.net and update the LABEL and the OS supported for the new Manager file.
     * 5 - Update in the HoN forums page (changelog, topic title and version in first line)
     */

    // First step is to get the version we want to release.
    String targetVersion = ManagerOptions.getInstance().getVersion();
    // Get the old jar
    File oldJarVersion =
        new File(
            "C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\Manager.jar");
    // And the newly generated one
    File newJarVersion = new File("store\\Manager.jar");
    // Target output for where the differences will be generated
    String verionsFile =
        "C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions.txt";
    File rootVersionsFolder =
        new File("C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\");
    File output = new File(rootVersionsFolder, targetVersion + ".jar");

    System.out.println("Version to be released=" + targetVersion);
    System.out.println("Old version file=" + oldJarVersion.getAbsolutePath());
    System.out.println("New version file=" + newJarVersion.getAbsolutePath());
    System.out.println();

    if (calculate(oldJarVersion, newJarVersion, output.getAbsolutePath())) {
      System.out.println(
          "Output file generated.\nPath="
              + output.getAbsolutePath()
              + "\nSize="
              + output.length() / 1024
              + "KB");

      // Read the current versions file and store it for later
      FileInputStream fis = new FileInputStream(verionsFile);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      copyInputStream(fis, baos);
      String s = baos.toString();
      fis.close();
      baos.close();

      System.out.println(s);

      if (!s.trim().isEmpty()) {
        if (s.contains("\n")) {
          System.out.println("Older version=" + s.substring(0, s.indexOf("\n")));
        } else {
          System.out.println("Older version=" + s);
        }
        s = targetVersion + "\n" + s;
      } else {
        System.out.println("First version!");
        s = targetVersion;
      }

      if (JOptionPane.showConfirmDialog(
              null, "Confirm upload?", "Confirmation", JOptionPane.YES_NO_OPTION)
          != 0) {
        System.exit(0);
      }

      // Write new versions file with the new released version
      FileWriter fw = new FileWriter(verionsFile);
      fw.write(s);
      fw.flush();
      fw.close();
      System.out.println("Versions file written with sucess!");

      fis = new FileInputStream(newJarVersion);
      FileOutputStream fos =
          new FileOutputStream(rootVersionsFolder + File.separator + "Manager.jar");
      copyInputStream(fis, fos);
      fis.close();
      fos.close();
      System.out.println("Manager.jar file written!");

      System.out.println();
    } else {
      System.err.println("No differences file. Output file not generated.");
      System.exit(0);
    }

    JSch jsch = new JSch();
    Session session = null;
    try {
      System.out.println("Connecting to SF");

      session =
          jsch.getSession(
              JOptionPane.showInputDialog("SourceForge Username") + ",all-inhonmodman",
              "frs.sourceforge.net",
              22);
      session.setConfig("StrictHostKeyChecking", "no");
      session.setPassword(JOptionPane.showInputDialog("SourceForge Password"));
      session.connect();

      Channel channel = session.openChannel("sftp");
      channel.connect();
      ChannelSftp sftpChannel = (ChannelSftp) channel;
      System.out.println("Connected!");
      String root = "/home/frs/project/a/al/all-inhonmodman";
      sftpChannel.cd(root);
      StringTokenizer versionTokens = new StringTokenizer(targetVersion, " ");
      boolean flag = true;
      while (versionTokens.hasMoreTokens()) {
        String s = versionTokens.nextToken();
        if (!cdExists(sftpChannel, s)) {
          sftpChannel.mkdir(s);
          flag = false;
        }
        sftpChannel.cd(s);
      }
      if (flag) {
        System.err.println("Version already exists!");
        sftpChannel.exit();
        session.disconnect();
        System.exit(0);
      }
      System.out.println("Uploading file");
      OutputStream out = sftpChannel.put("Manager.jar");
      FileInputStream fis = new FileInputStream(newJarVersion);
      copyInputStream(fis, out);
      out.close();
      fis.close();
      System.out.println("Upload complete");
      sftpChannel.exit();
      session.disconnect();
      System.out.println("SUCESS!");
    } catch (JSchException e) {
      e.printStackTrace();
    } catch (SftpException e) {
      e.printStackTrace();
    }

    System.exit(0);
  }
  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;
  }
Exemplo n.º 25
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;
  }