System.out.println("preparing the host information for sftp."); try { JSch jsch = new JSch(); session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT); session.setPassword(SFTPPASS); 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"); System.out.println("sftp channel opened and connected."); channelSftp = (ChannelSftp) channel; channelSftp.cd(SFTPWORKINGDIR); File f = new File(fileName); channelSftp.put(new FileInputStream(f), f.getName()); log.info("File transfered successfully to host."); } catch (Exception ex) { channelSftp.exit(); System.out.println("sftp Channel exited."); channel.disconnect();
JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); System.out.println("Establishing Connection..."); session.connect(); System.out.println("Connection established."); System.out.println("Crating SFTP Channel."); ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); System.out.println("SFTP Channel created."); out= sftpChannel.get(remoteFile); BufferedReader br = new BufferedReader(new InputStreamReader(out)); String line;
public synchronized void close() throws IOException { if (closed) { return; } super.close(); closed = true; if (!channel.isConnected()) { throw new IOException(E_CLIENT_NOTCONNECTED); } try { Session session = channel.getSession(); channel.disconnect(); session.disconnect(); } catch (JSchException e) { throw new IOException(StringUtils.stringifyException(e)); } } }
JSch jsch = new JSch(); jsch.setKnownHosts( knownHostsFilename ); Session session = jsch.getSession( "remote-username", "remote-host" ); session.setUserInfo(ui); session.setPassword( "remote-password" ); session.connect(); Channel channel = session.openChannel( "sftp" ); sftpChannel.get("remote-file", "local-file" ); InputStream in = sftpChannel.get( "remote-file" ); sftpChannel.exit(); session.disconnect();
import com.jcraft.jsch.*; public class TestJSch { public static void main(String args[]) { JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession("username", "127.0.0.1", 22); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword("password"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.get("remotefile.txt", "localfile.txt"); sftpChannel.exit(); session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } } }
@Override public long getFileSize(String filePath) throws FileBasedHelperException { try { ChannelSftp channelSftp = getSftpChannel(); long fileSize = channelSftp.lstat(filePath).getSize(); channelSftp.disconnect(); return fileSize; } catch (SftpException e) { throw new FileBasedHelperException( String.format("Failed to get size for file at path %s due to error %s", filePath, e.getMessage()), e); } }
public String[] dir() throws KettleJobException { String[] fileList = null; try { java.util.Vector<?> v = c.ls( "." ); java.util.Vector<String> o = new java.util.Vector<String>(); if ( v != null ) { for ( int i = 0; i < v.size(); i++ ) { Object obj = v.elementAt( i ); if ( obj != null && obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry ) { LsEntry lse = (com.jcraft.jsch.ChannelSftp.LsEntry) obj; if ( !lse.getAttrs().isDir() ) { o.add( lse.getFilename() ); } } } } if ( o.size() > 0 ) { fileList = new String[o.size()]; o.copyInto( fileList ); } } catch ( SftpException e ) { throw new KettleJobException( e ); } return fileList; }
FileCopyUtils.copy((InputStream) invocation.getArgument(0), new FileOutputStream(file)); return null; }).when(channel).put(Mockito.any(InputStream.class), Mockito.anyString()); file.renameTo(renameToFile); return null; }).when(channel).rename(Mockito.anyString(), Mockito.anyString()); Vector<LsEntry> sftpEntries = new Vector<LsEntry>(); for (String fileName : files) { LsEntry lsEntry = mock(LsEntry.class); when(lsEntry.getAttrs()).thenReturn(attributes); when(lsEntry.getFilename()).thenReturn(fileName); sftpEntries.add(lsEntry); when(channel.ls("remote-test-dir/")).thenReturn(sftpEntries); when(jschSession.openChannel("sftp")).thenReturn(channel); return SftpTestSessionFactory.createSftpSession(jschSession);
Path workDir; try { workDir = new Path(client.pwd()); } catch (SftpException e) { throw new IOException(e); sftpFiles = (Vector<LsEntry>) client.ls(absolute.toUri().getPath()); } catch (SftpException e) { throw new IOException(e); for (int i = 0; i < sftpFiles.size(); i++) { LsEntry entry = sftpFiles.get(i); String fname = entry.getFilename();
public void put(InputStream src, String dst, SftpProgressMonitor monitor, int mode) throws SftpException{ try{ dst=remoteAbsolutePath(dst); Vector v=glob_remote(dst); int vsize=v.size(); if(vsize!=1){ if(vsize==0){ if(isPattern(dst)) throw new SftpException(SSH_FX_FAILURE, dst); else dst=Util.unquote(dst); } throw new SftpException(SSH_FX_FAILURE, v.toString()); } else{ dst=(String)(v.elementAt(0)); } if(isRemoteDir(dst)){ throw new SftpException(SSH_FX_FAILURE, dst+" is a directory"); } _put(src, dst, monitor, mode); } catch(Exception e){ if(e instanceof SftpException) throw (SftpException)e; if(e instanceof Throwable) throw new SftpException(SSH_FX_FAILURE, e.toString(), (Throwable)e); throw new SftpException(SSH_FX_FAILURE, e.toString()); } }
public SftpFile[] ls(String path) throws SshException { Vector paths; try { paths = channel.ls(path); } catch (SftpException e) { throw new net.sf.sshapi.sftp.SftpException(e.id, e.getLocalizedMessage(), e); } List files = new ArrayList(); for (Enumeration e = paths.elements(); e.hasMoreElements();) { ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) e.nextElement(); SftpFile file = new SftpFile(convertType(entry.getAttrs()), entry.getFilename(), entry.getAttrs().getSize(), convertIntDate(entry.getAttrs().getMTime()), 0, convertIntDate(entry.getAttrs().getATime()), entry.getAttrs() .getGId(), entry.getAttrs().getUId(), entry.getAttrs().getPermissions()); files.add(file); } return (SftpFile[]) files.toArray(new SftpFile[paths.size()]); }
@Signature @SuppressWarnings("unchecked") public Memory ls(Environment env, String path, @Nullable Invoker lsSelector) throws SftpException { Vector<ChannelSftp.LsEntry> ls = new Vector<>(); ArrayMemory result = ArrayMemory.createListed(10); getWrappedObject().ls(path, new ChannelSftp.LsEntrySelector() { @Override public int select(ChannelSftp.LsEntry l) { ArrayMemory entry = ArrayMemory.createHashed(); entry.put("name", l.getFilename()); entry.put("longname", l.getLongname()); entry.put("attrs", ArrayMemory.ofNullableBean(env, l.getAttrs())); if (lsSelector != null && lsSelector.callAny(entry).toBoolean()) { return ChannelSftp.LsEntrySelector.BREAK; } result.add(entry); return ChannelSftp.LsEntrySelector.CONTINUE; } }); return result.toConstant(); }
@Override public LsEntry[] list(String path) throws IOException { Assert.state(this.channel != null, "session is not connected"); try { Vector<?> lsEntries = this.channel.ls(path); if (lsEntries != null) { LsEntry[] entries = new LsEntry[lsEntries.size()]; for (int i = 0; i < lsEntries.size(); i++) { Object next = lsEntries.get(i); Assert.state(next instanceof LsEntry, "expected only LsEntry instances from channel.ls()"); entries[i] = (LsEntry) next; } return entries; } } catch (SftpException e) { throw new NestedIOException("Failed to list files", e); } return new LsEntry[0]; }
@Override public Set<String> getAllFilesInDir(String dir, String prefixFileName) { Set<String> allFilesWithPointedPrefix = new HashSet<String>(); try { this.printWorkingDirectory(); @SuppressWarnings("rawtypes") Vector allFiles = this.channelSftp.ls(dir); LOG.debug(String.format("ls: %s", JSON.toJSONString(allFiles, SerializerFeature.UseSingleQuotes))); for (int i = 0; i < allFiles.size(); i++) { LsEntry le = (LsEntry) allFiles.get(i); String strName = le.getFilename(); if (strName.startsWith(prefixFileName)) { allFilesWithPointedPrefix.add(strName); } } } catch (SftpException e) { String message = String .format("获取path:[%s] 下文件列表时发生I/O异常,请确认与ftp服务器的连接正常,拥有目录ls权限, errorMessage:%s", dir, e.getMessage()); LOG.error(message); throw DataXException.asDataXException( FtpWriterErrorCode.COMMAND_FTP_IO_EXCEPTION, message, e); } return allFilesWithPointedPrefix; }
@Test public void shouldCatchAndRethrowExceptionIfCaught() throws SftpException { expectedException.expect(FTPException.class); expectedException.expectMessage(equalTo("Unable to delete file on remote server")); when(mockChannel.ls("/some/directory/file.name/")).thenReturn(new Vector<LsEntry>()); FTPFile file = new FTPFile("file.name", 0, "/some/directory", 0, true); doThrow(new SftpException(0, "")).when(mockChannel).rmdir("/some/directory/file.name"); sftpConnection.deleteRemoteFile(file); }
@Test public void shouldDeleteRemoteDirectory() throws SftpException { when(mockChannel.ls("/some/directory/file.name/")).thenReturn(new Vector<LsEntry>()); FTPFile file = new FTPFile("file.name", 0, "/some/directory", 0, true); sftpConnection.deleteRemoteFile(file); verify(mockChannel).rmdir("/some/directory/file.name"); }
@Override public SftpSession getSession() { if (this.sftpEntries.size() == 0) { this.init(); } try { ChannelSftp channel = mock(ChannelSftp.class); String[] files = new File("remote-test-dir").list(); for (String fileName : files) { when(channel.get("remote-test-dir/" + fileName)) .thenReturn(new FileInputStream("remote-test-dir/" + fileName)); } when(channel.ls("remote-test-dir")).thenReturn(sftpEntries); when(jschSession.openChannel("sftp")).thenReturn(channel); return SftpTestSessionFactory.createSftpSession(jschSession); } catch (Exception e) { throw new RuntimeException("Failed to create mock sftp session", e); } }
@SuppressWarnings("unchecked") @Override public Collection<FileAbstractModel> getFiles(String dir) throws Exception { logger.debug("Listing local files from {}", dir); Vector<ChannelSftp.LsEntry> ls; ls = sftp.ls(dir); if (ls == null) return null; Collection<FileAbstractModel> result = new ArrayList<>(ls.size()); // Iterate other files // We ignore here all files like . and .. result.addAll(ls.stream().filter(file -> !".".equals(file.getFilename()) && !"..".equals(file.getFilename())) .map(file -> toFileAbstractModel(dir, file)) .collect(Collectors.toList())); logger.debug("{} local files found", result.size()); return result; }
protected boolean fastExistsFile(String name) throws GenericFileOperationFailedException { LOG.trace("fastExistsFile({})", name); try { @SuppressWarnings("rawtypes") Vector files = channel.ls(name); if (files == null) { return false; } return files.size() >= 1; } 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); } }
protected ChannelSftp getChannel(final FlowFile flowFile) throws IOException { if (sftp != null) { String sessionhost = session.getHost(); String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue(); if (sessionhost.equals(desthost)) { proxyHTTP.setUserPasswd(proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword()); session.setProxy(proxyHTTP); break; case SOCKS: proxySOCKS5.setUserPasswd(proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword()); session.setProxy(proxySOCKS5); break; jsch.setKnownHosts(hostKeyVal); sftp = (ChannelSftp) session.openChannel("sftp"); sftp.connect(connectionTimeoutMillis); session.setTimeout(ctx.getProperty(FileTransfer.DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); if (!ctx.getProperty(USE_KEEPALIVE_ON_TIMEOUT).asBoolean()) { this.homeDir = sftp.getHome(); } catch (SftpException e) { logger.debug("Failed to retrieve {} home directory due to {}", new Object[]{username, e.getMessage()});