private void upload(String filename) { try { JSch jsch = new JSch(); Session session = jsch.getSession(login, server, port); session.setPassword(password); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp channelSftp = (ChannelSftp) channel; channelSftp.cd(workingDirectory); File f = new File(filename); channelSftp.put(new FileInputStream(f), f.getName()); f.delete(); } catch (Exception ex) { ex.printStackTrace(); } }
public static void fileFetch(String host, String user, String keyLocation, String sourceDir, String destDir) { JSch jsch = new JSch(); Session session = null; try { // set up session session = jsch.getSession(user,host); // use private key instead of username/password session.setConfig( "PreferredAuthentications", "publickey,gssapi-with-mic,keyboard-interactive,password"); jsch.addIdentity(keyLocation); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); // copy remote log file to localhost. ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); channelSftp.get(sourceDir, destDir); channelSftp.exit(); } catch (Exception e) { e.printStackTrace(); } finally { session.disconnect(); } }
/** * Send a file to server path via SFTP * @param src * @param path * @throws SftpException */ public void put(final File src, String path) throws SftpException { if (!path.endsWith("/")) path = path.concat("/"); if (path.startsWith("/")) path = path.substring(1); ChannelSftp sftp = (ChannelSftp) channel; SftpProgressMonitor progress = new SftpProgressMonitor() { @Override public void init(int arg0, String arg1, String arg2, long arg3) { System.out.println("File transfer begin.."); } @Override public void end() { Out.print(LOG_LEVEL.INFO, "Upload of file "+ src.getName() +" succeeded."); ready = true; } @Override public boolean count(long i) { return false; } }; sftp.put(src.getAbsolutePath(), initRemDir+path+src.getName(), progress); }
@Override public boolean renameFile(String fromFilePath, String toFilePath, boolean closeSession) { ChannelSftp sftp = null; try { // Get a reusable channel if the session is not auto closed. sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1); sftp.cd(basePath); sftp.rename(fromFilePath, toFilePath); return true; } catch (Exception e) { return false; } finally { if (closeSession) { close(); } } }
/** * Creates a new file on the remote host using the input content. * * @param from the byte array content to be uploaded * @param fileName the name of the file for which the content will be saved into * @param toPath the path of the file for which the content will be saved into * @param isUserHomeBased true if the path of the file is relative to the user's home directory * @param filePerm file permissions to be set * @throws Exception exception thrown */ public void upload(InputStream from, String fileName, String toPath, boolean isUserHomeBased, String filePerm) throws Exception { ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp"); channel.connect(); String absolutePath = isUserHomeBased ? channel.getHome() + "/" + toPath : toPath; String path = ""; for (String dir : absolutePath.split("/")) { path = path + "/" + dir; try { channel.mkdir(path); } catch (Exception ee) { } } channel.cd(absolutePath); channel.put(from, fileName); if (filePerm != null) { channel.chmod(Integer.parseInt(filePerm), absolutePath + "/" + fileName); } channel.disconnect(); }
@SuppressWarnings("unchecked") public static Vector<LsEntry> getRemoteFileList(String user, String password, String addr, int port, String cwd) throws JSchException, SftpException, Exception { Session session = getSession(user, password, addr, port); Vector<LsEntry> lsVec=null; Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; try { lsVec=(Vector<LsEntry>)sftpChannel.ls(cwd); //sftpChannel.lpwd() } catch (Exception e) { e.printStackTrace(); throw e; } finally { sftpChannel.exit(); channel.disconnect(); session.disconnect(); } return lsVec; }
@Override public void copyFile(String fromFilePath, String toFilePath, boolean closeSession) { ChannelSftp uploadSftp = null; InputStream inputStream = null; try { // Get a reusable channel if the session is not auto closed. uploadSftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1); uploadSftp.cd(basePath); inputStream = getInputStream(fromFilePath, true); uploadSftp.put(inputStream, toFilePath); } catch (Exception e) { throw new IoException("Error copying file. Error %s", e.getMessage()); } finally { if (closeSession) { close(); } } }
@Override public void copyToDir(String fromFilePath, String toDirPath, boolean closeSession) { ChannelSftp uploadSftp = null; FileInfo fileInfo = new FileInfo(fromFilePath, false, new java.util.Date().getTime(), -1); InputStream inputStream = null; try { // Get a reusable channel if the session is not auto closed. uploadSftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1); uploadSftp.cd(basePath); if (!toDirPath.endsWith("/")) { toDirPath += "/"; } inputStream = getInputStream(fromFilePath, true); uploadSftp.put(inputStream, toDirPath + fileInfo.getName()); } catch (Exception e) { throw new IoException("Error copying directory. Error %s", e.getMessage()); } finally { if (closeSession) { close(); } } }
@Override public void moveToDir(String fromFilePath, String toDirPath, boolean closeSession) { ChannelSftp sftp = null; FileInfo fileInfo = new FileInfo(fromFilePath, false, new java.util.Date().getTime(), -1); try { // Get a reusable channel if the session is not auto closed. sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1); sftp.cd(basePath); if (!toDirPath.endsWith("/")) { toDirPath += "/"; } sftp.rename(fromFilePath, toDirPath + fileInfo.getName()); } catch (Exception e) { throw new IoException("Error moving (renaming) directory. Error %s", e.getMessage()); } finally { if (closeSession) { close(); } } }
/** * Lists directory files on remote server. * @throws URISyntaxException * @throws JSchException * @throws SftpException */ private void listFiles() throws URISyntaxException, JSchException, SftpException { JSch jsch = new JSch(); JSch.setLogger(new JschLogger()); setupSftpIdentity(jsch); URI uri = new URI(sftpUrl); Session session = jsch.getSession(sshLogin, uri.getHost(), 22); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); System.out.println("Connected to SFTP server"); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; Vector<LsEntry> directoryEntries = sftpChannel.ls(uri.getPath()); for (LsEntry file : directoryEntries) { System.out.println(String.format("File - %s", file.getFilename())); } sftpChannel.exit(); session.disconnect(); }
/** * Perform the specified SSH file download. * * @param from source remote file URI ({@code ssh} protocol) * @param to target local folder URI ({@code file} protocol) */ private static void download(URI from, URI to) { File out = new File(new File(to), getName(from.getPath())); try (SessionHolder<ChannelSftp> session = new SessionHolder<>(ChannelType.SFTP, from); OutputStream os = new FileOutputStream(out); BufferedOutputStream bos = new BufferedOutputStream(os)) { LOG.info("Downloading {} --> {}", session.getMaskedUri(), to); ChannelSftp channel = session.getChannel(); channel.connect(); channel.cd(getFullPath(from.getPath())); channel.get(getName(from.getPath()), bos); } catch (Exception e) { throw new RemoteFileDownloadFailedException("Cannot download file", e); } }
private void delete(String path, ChannelSftp c) throws Exception { String sessionLocalPath = extractSessionPath(path); try { if (c.stat(sessionLocalPath).isDir()) { List<FileEntry> contents = listFiles(path, c); for (FileEntry fe: contents) { delete(fe.path, c); } c.rmdir(sessionLocalPath); } else { c.rm(sessionLocalPath); } } catch (Exception e) { tryDisconnect(c); throw convertException(e); } }
public SftpClient init() { try { String host = PropertiesUtil.getString("sftp.host"); int port = PropertiesUtil.getInt("sftp.port"); String userName = PropertiesUtil.getString("sftp.user.name"); String password = PropertiesUtil.getString("sftp.user.password"); Integer timeout = PropertiesUtil.getInt("sftp.timeout"); Integer aliveMax = PropertiesUtil.getInt("sftp.aliveMax"); JSch jsch = new JSch(); // 创建JSch对象 session = jsch.getSession(userName, host, port); // 根据用户名,主机ip,端口获取一个Session对象 if (password != null) { session.setPassword(password); // 设置密码 } session.setConfig("StrictHostKeyChecking", "no"); // 为Session对象设置properties if (timeout != null) session.setTimeout(timeout); // 设置timeout时间 if (aliveMax != null) session.setServerAliveCountMax(aliveMax); session.connect(); // 通过Session建立链接 channel = (ChannelSftp)session.openChannel("sftp"); // 打开SFTP通道 channel.connect(); // 建立SFTP通道的连接 logger.info("SSH Channel connected."); } catch (JSchException e) { throw new FtpException("", e); } return this; }
@Override public boolean rename(String newName){ Channel channel = null; try { channel = SFTPSession.getInstance().getSFTPChannel(mUri); ((ChannelSftp)channel).rename(mUri.getPath(), new File(new File(mUri.getPath()).getParentFile(), newName).getAbsolutePath()); channel.disconnect(); return true; } catch (Exception e) { e.printStackTrace(); }finally { if(channel!=null&&channel.isConnected()) channel.disconnect(); } return false; }
@Override public boolean move(Uri uri) { if(!mUri.getScheme().equals(uri.getScheme())|| !mUri.getHost().equals(uri.getHost())||mUri.getPort()!=uri.getPort()) return false; Channel channel = null; try { channel = SFTPSession.getInstance().getSFTPChannel(mUri); ((ChannelSftp)channel).rename(mUri.getPath(),uri.getPath()); channel.disconnect(); return true; } catch (Exception e) { e.printStackTrace(); }finally { if(channel!=null&&channel.isConnected()) channel.disconnect(); } return false; }
@Override public boolean exists() { Channel channel = null; try { channel = SFTPSession.getInstance().getSFTPChannel(mUri); SftpATTRS attrs = ((ChannelSftp)channel).stat(mUri.getPath()); channel.disconnect(); return attrs !=null; } catch (Exception e) { if(channel!=null&&channel.isConnected()) channel.disconnect(); e.printStackTrace(); }finally { if(channel!=null&&channel.isConnected()) channel.disconnect(); } return false; }
/** * Opens a new SFTP channel over this SSH session. * * @throws JSchException * @throws SftpException * @see JSchSftpChannel */ public JSchSftpChannel openSftpChannel() throws JSchException, SftpException { ChannelSftp chan = (ChannelSftp) session.openChannel("sftp"); chan.connect(timeout); if (url.getPath().isPresent()) { String dir = url.getPath().get(); try { chan.cd(dir); } catch (SftpException e) { logger.warning(e.toString()); mkdirs(chan, dir); chan.cd(dir); } } return new JSchSftpChannel(chan); }
public synchronized List<ChannelSftp.LsEntry> listFiles(String path) throws GenericFileOperationFailedException { LOG.trace("listFiles({})", path); if (ObjectHelper.isEmpty(path)) { // list current directory if file path is not given path = "."; } try { final List<ChannelSftp.LsEntry> list = new ArrayList<ChannelSftp.LsEntry>(); @SuppressWarnings("rawtypes") Vector files = channel.ls(path); // can return either null or an empty list depending on FTP servers if (files != null) { for (Object file : files) { list.add((ChannelSftp.LsEntry) file); } } return list; } catch (SftpException e) { throw new GenericFileOperationFailedException("Cannot list directory: " + path, e); } }
/** * 文件重命名 * @param oldpath * @param newpath * @return boolean */ public boolean rename(String oldpath,String newpath) { boolean flag=false; ChannelSftp channel=getChannel(); try { channel.rename(oldpath, newpath); log.info("重命名文件"+oldpath+"成功"); log.info("更新后的文件名为:"+newpath); flag=true; } catch (SftpException e) { log.error("重命名文件"+oldpath+"失败"); log.error(e.getMessage()); }finally { //channel.quit(); } return flag; }
@Override public void moveFile(String fromFilePath, String toFilePath, boolean closeSession) { ChannelSftp sftp = null; try { // Get a reusable channel if the session is not auto closed. sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1); sftp.cd(basePath); sftp.rename(fromFilePath, toFilePath); } catch (Exception e) { throw new IoException("Error moving (renaming) file. Error %s", e.getMessage()); } finally { if (closeSession) { close(); } } }
@Override public InputStream getInputStream(String relativePath, boolean mustExist, boolean closeSession) { Session session = null; ChannelSftp sftp = null; try { session = openSession(); // Get a reusable channel if the session is not auto closed. sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_IN); sftp.cd(basePath); if (mustExist && !fileExists(sftp, relativePath)) { throw new IoException("Could not find endpoint '%s' that was configured as MUST EXIST",relativePath); } return new CloseableInputStream(sftp.get(relativePath), session, sftp, closeSession); } catch (Exception e) { if (e instanceof IoException || (e instanceof SftpException && ((SftpException) e).id != 2)) { throw new IoException("Error getting the input stream for sftp endpoint. Error %s", e.getMessage()); } else { return null; } } }
private void sendDirectoryToRemote(final ChannelSftp channel, final Directory directory) throws IOException, SftpException { final String dir = directory.getDirectory().getName(); try { channel.stat(dir); } catch (final SftpException e) { // dir does not exist. if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) { channel.mkdir(dir); channel.chmod(getDirMode(), dir); } } channel.cd(dir); sendDirectory(channel, directory); channel.cd(".."); }
private void getDir(final ChannelSftp channel, final String remoteFile, final File localFile) throws IOException, SftpException { String pwd = remoteFile; if (remoteFile.lastIndexOf('/') != -1) { if (remoteFile.length() > 1) { pwd = remoteFile.substring(0, remoteFile.lastIndexOf('/')); } } channel.cd(pwd); if (!localFile.exists()) { localFile.mkdirs(); } @SuppressWarnings("unchecked") final List<ChannelSftp.LsEntry> files = channel.ls(remoteFile); for (ChannelSftp.LsEntry le : files) { final String name = le.getFilename(); if (le.getAttrs().isDir()) { if (".".equals(name) || "..".equals(name)) { continue; } getDir(channel, channel.pwd() + "/" + name + "/", new File(localFile, le.getFilename())); } else { getFile(channel, le, localFile); } } channel.cd(".."); }
public boolean startSession(String file, String host) throws JSchException, SftpException { String path = BioNimbusConfig.get().getDataFolder(); try { session = jsch.getSession(USER, host, PORT); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(PASSW); session.connect(); channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; LOGGER.info("Downloading file"); sftpChannel.get(path + file, path); sftpChannel.exit(); session.disconnect(); } catch (JSchException | SftpException e) { return false; } return true; }
/** * Downloads the content of a file from the remote host as a String. * * @param fileName the name of the file for which the content will be downloaded * @param fromPath the path of the file for which the content will be downloaded * @param isUserHomeBased true if the path of the file is relative to the user's home directory * @return the content of the file * @throws Exception exception thrown */ public String download(String fileName, String fromPath, boolean isUserHomeBased) throws Exception { ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp"); channel.connect(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BufferedOutputStream buff = new BufferedOutputStream(outputStream); String absolutePath = isUserHomeBased ? channel.getHome() + "/" + fromPath : fromPath; channel.cd(absolutePath); channel.get(fileName, buff); channel.disconnect(); return outputStream.toString(); }
protected void work() throws IOException, CancellationException, JSchException, SftpException, ExecutionException, InterruptedException { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} started", getTraceName()); } ChannelSftp cftp = getChannel(); RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("download", srcFileName); // NOI18N try { cftp.get(srcFileName, dstFileName); } catch (SftpException e) { if (MiscUtils.mightBrokeSftpChannel(e)) { cftp.quit(); } throw decorateSftpException(e, srcFileName); } finally { releaseChannel(cftp); RemoteStatistics.stopChannelActivity(activityID, new File(dstFileName).length()); } }
@Override public StatInfo call() throws Exception { StatInfo result = null; SftpException exception = null; if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} started", getTraceName()); } String threadName = Thread.currentThread().getName(); Thread.currentThread().setName(PREFIX + ": " + getTraceName()); // NOI18N RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("move", from); // NOI18N ChannelSftp cftp = null; try { cftp = getChannel(); cftp.rename(from, to); } catch (SftpException e) { exception = e; if (e.id == SftpIOException.SSH_FX_FAILURE) { if (MiscUtils.mightBrokeSftpChannel(e)) { cftp.quit(); } } } finally { RemoteStatistics.stopChannelActivity(activityID); releaseChannel(cftp); Thread.currentThread().setName(threadName); } if (exception != null) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} failed", getTraceName()); } throw decorateSftpException(exception, from + " to " + to); //NOI18N } if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} finished", new Object[] {getTraceName()}); } return result; }
private StatInfo createStatInfo(String dirName, String baseName, SftpATTRS attrs, ChannelSftp cftp) throws SftpException { String linkTarget = null; if (attrs.isLink()) { String path = dirName + '/' + baseName; RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("readlink", path); // NOI18N try { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "performing readlink {0}", path); } linkTarget = cftp.readlink(path); } finally { RemoteStatistics.stopChannelActivity(activityID); } } Date lastModified = new Date(attrs.getMTime() * 1000L); StatInfo result = new FileInfoProvider.StatInfo(baseName, attrs.getUId(), attrs.getGId(), attrs.getSize(), attrs.isDir(), attrs.isLink(), linkTarget, attrs.getPermissions(), lastModified); return result; }
@Override public FileEntry getFileEntry(String filename) throws Exception { ChannelSftp c = init(filename); try { FileEntry fileEntry = new FileEntry(); String sessionPath = extractSessionPath(filename); SftpATTRS attr = c.stat(sessionPath); setFromAttrs(fileEntry, attr); fileEntry.path = filename; fileEntry.displayName = getFilename(sessionPath); tryDisconnect(c); return fileEntry; } catch (Exception e) { logDebug("Exception in getFileEntry! " + e); tryDisconnect(c); throw convertException(e); } }
ChannelSftp init(String filename) throws JSchException, UnsupportedEncodingException { jsch = new JSch(); ConnectionInfo ci = splitStringToConnectionInfo(filename); Session session = jsch.getSession(ci.username, ci.host, ci.port); UserInfo ui = new SftpUserInfo(ci.password); session.setUserInfo(ui); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp c = (ChannelSftp) channel; logDebug("success: init Sftp"); return c; }
/** * Convert the file information in LsEntry to a {@link FileStatus} object. * * * @param sftpFile * @param parentPath * @return file status * @throws IOException */ private FileStatus getFileStatus(ChannelSftp channel, LsEntry sftpFile, Path parentPath) throws IOException { SftpATTRS attr = sftpFile.getAttrs(); long length = attr.getSize(); boolean isDir = attr.isDir(); boolean isLink = attr.isLink(); if (isLink) { String link = parentPath.toUri().getPath() + "/" + sftpFile.getFilename(); try { link = channel.realpath(link); Path linkParent = new Path("/", link); FileStatus fstat = getFileStatus(channel, linkParent); isDir = fstat.isDirectory(); length = fstat.getLen(); } catch (Exception e) { throw new IOException(e); } } int blockReplication = 1; // Using default block size since there is no way in SFTP channel to know of // block sizes on server. The assumption could be less than ideal. long blockSize = DEFAULT_BLOCK_SIZE; long modTime = attr.getMTime() * 1000; // convert to milliseconds long accessTime = 0; FsPermission permission = getPermissions(sftpFile); // not be able to get the real user group name, just use the user and group // id String user = Integer.toString(attr.getUId()); String group = Integer.toString(attr.getGId()); Path filePath = new Path(parentPath, sftpFile.getFilename()); return new FileStatus(length, isDir, blockReplication, blockSize, modTime, accessTime, permission, user, group, filePath.makeQualified( this.getUri(), this.getWorkingDirectory())); }
synchronized ChannelSftp getFromPool(ConnectionInfo info) throws IOException { Set<ChannelSftp> cons = idleConnections.get(info); ChannelSftp channel; if (cons != null && cons.size() > 0) { Iterator<ChannelSftp> it = cons.iterator(); if (it.hasNext()) { channel = it.next(); idleConnections.remove(info); return channel; } else { throw new IOException("Connection pool error."); } } return null; }
private Vector<LsEntry> listEntries(final ChannelSftp channelSftp, final String path) throws SftpException { final Vector<LsEntry> vector = new Vector<LsEntry>(); LsEntrySelector selector = new LsEntrySelector() { public int select(LsEntry entry) { final String filename = entry.getFilename(); if (filename.equals(".") || filename.equals("..")) { return CONTINUE; } if (entry.getAttrs().isLink()) { vector.addElement(entry); } else if (entry.getAttrs().isDir()) { if (keepDirectory(filename)) { vector.addElement(entry); } } else { if (keepFile(filename)) { vector.addElement(entry); } } return CONTINUE; } }; channelSftp.ls(path, selector); return vector; }
private List<String> listFiles(String path, List<String> list, String prefix, boolean root) { Vector<ChannelSftp.LsEntry> children = util.ls(path); if(null != children) { for (ChannelSftp.LsEntry entry : children) { if(entry.getAttrs().isDir()) { listFiles(path + "/" + entry.getFilename(), list, root ? entry.getFilename() : (prefix + "/" + entry.getFilename()), false); } else { String ret = FilterChain.filter(entry.getFilename()); if(null != ret) { list.add(root ? ret : prefix + "/" + ret); } } } } return list; }
/** * 本地檔案放到遠端SFTP上 * * @param user * @param password * @param addr * @param port * @param localFile * @param remoteFile * @throws JSchException * @throws SftpException * @throws Exception */ public static void put(String user, String password, String addr, int port, List<String> localFile, List<String> remoteFile) throws JSchException, SftpException, Exception { Session session = getSession(user, password, addr, port); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; try { for (int i=0; i<localFile.size(); i++) { String rf=remoteFile.get(i); String lf=localFile.get(i); logger.info("put local file: " + lf + " write to " + addr + " :" + rf ); sftpChannel.put(lf, rf); logger.info("success write to " + addr + " :" + rf); } } catch (Exception e) { e.printStackTrace(); throw e; } finally { sftpChannel.exit(); channel.disconnect(); session.disconnect(); } }
/** * * @param sourceFilePath * @param destinationFilePath * @param destinationHost * @param destinationPort * @param destinationUserName * @param destinationUserPassword * @param destinationPrivateKeyFilePath * @param destinationPrivateKeyPassphrase * @throws IOException * @throws JSchException * @throws SftpException */ public static void copyFile( String sourceFilePath, String destinationFilePath, String destinationHost, String destinationPort, String destinationUserName, String destinationUserPassword, String destinationPrivateKeyFilePath, String destinationPrivateKeyPassphrase) throws IOException, JSchException, SftpException { JSch jsch = new JSch(); if (!StringUtils.isEmptyOrNull(destinationPrivateKeyFilePath)) { jsch.addIdentity(destinationPrivateKeyFilePath, destinationPrivateKeyPassphrase); } int destinationPortNumber = 22; if (!StringUtils.isEmptyOrNull(destinationPort)) { destinationPortNumber = Integer.parseInt(destinationPort); } Session session = jsch.getSession(destinationUserName, destinationHost, destinationPortNumber); if (!StringUtils.isEmptyOrNull(destinationUserPassword)) { session.setPassword(destinationUserPassword); } // Properties config = new Properties(); // config.put("StrictHostKeyChecking", "no"); // session.setConfig(config); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp channelSftp = (ChannelSftp)channel; File destinationFile = new File(destinationFilePath); channelSftp.cd(destinationFile.getPath()); channelSftp.put(new FileInputStream(sourceFilePath), destinationFile.getName()); }
public SshToolInvocation(ToolDescription desc, SshNode workerNodeA, AskUserForPw askUserForPwA, CredentialManager credentialManager) throws JSchException, SftpException { this.workerNode = workerNodeA; this.credentialManager = credentialManager; setRetrieveData(workerNodeA.isRetrieveData()); this.askUserForPw = askUserForPwA; usecase = desc; ChannelSftp sftp = SshPool.getSftpPutChannel(workerNode, askUserForPw); synchronized (getNodeLock(workerNode)) { logger.info("Changing remote directory to " + workerNode.getDirectory()); sftp.cd(workerNode.getDirectory()); Random rnd = new Random(); while (true) { tmpname = "usecase" + rnd.nextLong(); try { sftp.lstat(workerNode.getDirectory() + tmpname); continue; } catch (Exception e) { // file seems to not exist :) } sftp.mkdir(workerNode.getDirectory() + tmpname); sftp.cd(workerNode.getDirectory() + tmpname); break; } } }
@Override public boolean delete(String relativePath, boolean closeSession) { ChannelSftp sftp = null; try { // Get a reusable channel if the session is not auto closed. sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1); sftp.cd(basePath); sftp.rm(relativePath); return true; } catch (Exception e) { return false; } finally { if (closeSession) { close(); } } }