public static void main(String[] args) { SFTPGetTest test = new SFTPGetTest(); Map<String, String> sftpDetails = new HashMap<String, String>(); // 设置主机ip,用户名,密码,端口 sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, IP); sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, PORT); sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, USERNAME); sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, PASSWOED); // 创建下载通道。以及超时时长,单位是毫秒 SFTPChannel channel = test.getSFTPChannel(); ChannelSftp chSftp = null; try { chSftp = channel.getChannel(sftpDetails, delayTime); } catch (JSchException e1) { System.out.println("error:创建下载通道失败!failed to creat a channel!"); e1.printStackTrace(); } SftpATTRS attr = null; try { attr = chSftp.stat(FILE_PATH_SFTP); } catch (SftpException e1) { System.out.println("error:获取文件大小失败失败!failed to get the size of the file!"); e1.printStackTrace(); } long fileSize = attr.getSize(); System.out.println("fileSize=" + fileSize); try { chSftp.get(FILE_PATH_SFTP, DESTINATION_LOCAL, new MyProgressMonitor(fileSize)); // 代码段1 // OutputStream out = new FileOutputStream(DESTINATION_LOCAL);//这是采用文件输入流方式下载文件 // chSftp.get(FILE_PATH_SFTP, out, new FileProgressMonitor(fileSize)); // 代码段2 /** * 代码段3 * * <p>OutputStream out = new FileOutputStream(DESTINATION_LOCAL);//这是采用文件输入流方式下载文件 InputStream * is = chSftp.get(FILE_PATH_SFTP, new MyProgressMonitor()); byte[] buff = new byte[1024 * 2]; * int read; if (is != null) { System.out.println("Start to read input stream"); do { read = * is.read(buff, 0, buff.length); if (read > 0) { out.write(buff, 0, read); } out.flush(); } * while (read >= 0); System.out.println("input stream read done."); } */ } catch (Exception e) { e.printStackTrace(); } finally { chSftp.quit(); try { channel.closeChannel(); } catch (Exception e) { System.out.println("error:关闭下载通道失败!failed to close the channel!"); e.printStackTrace(); } } }
static SftpATTRS getATTR(Buffer buf) { SftpATTRS attr = new SftpATTRS(); attr.flags = buf.getInt(); if ((attr.flags & SSH_FILEXFER_ATTR_SIZE) != 0) { attr.size = buf.getLong(); } if ((attr.flags & SSH_FILEXFER_ATTR_UIDGID) != 0) { attr.uid = buf.getInt(); attr.gid = buf.getInt(); } if ((attr.flags & SSH_FILEXFER_ATTR_PERMISSIONS) != 0) { attr.permissions = buf.getInt(); } if ((attr.flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0) { attr.atime = buf.getInt(); } if ((attr.flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0) { attr.mtime = buf.getInt(); } if ((attr.flags & SSH_FILEXFER_ATTR_EXTENDED) != 0) { int count = buf.getInt(); if (count > 0) { attr.extended = new String[count * 2]; for (int i = 0; i < count; i++) { attr.extended[i * 2] = Util.byte2str(buf.getString()); attr.extended[i * 2 + 1] = Util.byte2str(buf.getString()); } } } return attr; }
private void setLastModified(File localFile) throws JSchException { SftpATTRS fileAttributes = null; String remotePath = null; ChannelSftp channel = openSftpChannel(); channel.connect(); try { fileAttributes = channel.lstat(remoteDir(remoteFile) + localFile.getName()); } catch (SftpException e) { throw new JSchException("failed to stat remote file", e); } FileUtils.getFileUtils() .setFileLastModified(localFile, ((long) fileAttributes.getMTime()) * 1000); }
private ExternalResourceMetaData toMetaData(URI uri, SftpATTRS attributes) { long lastModified = -1; long contentLength = -1; if ((attributes.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) != 0) { lastModified = attributes.getMTime() * 1000; } if ((attributes.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_SIZE) != 0) { contentLength = attributes.getSize(); } return new DefaultExternalResourceMetaData(uri, lastModified, contentLength); }
private void mkdirs(String directory, ChannelSftp c) throws IOException, SftpException { try { SftpATTRS att = c.stat(directory); if (att != null) { if (att.isDir()) { return; } } } catch (SftpException ex) { if (directory.indexOf('/') != -1) { mkdirs(directory.substring(0, directory.lastIndexOf('/')), c); } c.mkdir(directory); } }
public boolean folderExists(String foldername) { boolean retval = false; try { SftpATTRS attrs = c.stat(foldername); if (attrs == null) { return false; } if ((attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0) { throw new KettleJobException("Unknown permissions error"); } retval = attrs.isDir(); } catch (Exception e) { // Folder can not be found! } return retval; }
public FileType getFileType(String filename) throws KettleJobException { try { SftpATTRS attrs = c.stat(filename); if (attrs == null) { return FileType.IMAGINARY; } if ((attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0) { throw new KettleJobException("Unknown permissions error"); } if (attrs.isDir()) { return FileType.FOLDER; } else { return FileType.FILE; } } catch (Exception e) { throw new KettleJobException(e); } }
/** * This method is similar to getResource, except that the returned resource is fully initialized * (resolved in the sftp repository), and that the given string is a full remote path * * @param path the full remote path in the repository of the resource * @return a fully initialized resource, able to answer to all its methods without needing any * further connection */ public Resource resolveResource(String path) { try { ChannelSftp c = getSftpChannel(path); Collection r = c.ls(getPath(path)); if (r != null) { for (Iterator iter = r.iterator(); iter.hasNext(); ) { Object obj = iter.next(); if (obj instanceof LsEntry) { LsEntry entry = (LsEntry) obj; SftpATTRS attrs = entry.getAttrs(); return new BasicResource( path, true, attrs.getSize(), attrs.getMTime() * MILLIS_PER_SECOND, false); } } } } catch (Exception e) { Message.debug("Error while resolving resource " + path, e); // silent fail, return unexisting resource } return new BasicResource(path, false, 0, 0, false); }
@Test(groups = "spring") public void testCantWriteToCwd() throws SftpException { SftpATTRS attrs = sftpChannel.stat("."); assert attrs.getPermissionsString().contains("r"); assert attrs.getPermissionsString().contains("w"); }
@Test(groups = "spring") public void testCannotWriteNonFolderObject() throws SftpException { SftpATTRS attrs = sftpChannel.stat("HUMAN"); assert attrs.getPermissionsString().contains("r"); assert !attrs.getPermissionsString().contains("w"); }
@Test(groups = "spring") public void testCannotWriteExistingFile() throws SftpException { SftpATTRS attrs = sftpChannel.stat("Test Folder/Subfile"); assert attrs.getPermissionsString().contains("r"); assert !attrs.getPermissionsString().contains("w"); }
@Test public void testIntegration() throws Exception { final JSch mockJsch = mock(JSch.class); final Session mockSession = mock(Session.class); final ChannelSftp mockSftp = mock(ChannelSftp.class); final int port = 28; final int timeout = 3000; final BapSshHostConfiguration testHostConfig = new BapSshHostConfiguration( "testConfig", "testHostname", "testUsername", "", "/testRemoteRoot", port, timeout, false, "", "", false) { @Override public JSch createJSch() { return mockJsch; } }; final BapSshCommonConfiguration commonConfig = new BapSshCommonConfiguration("passphrase", "key", "", false); new JenkinsTestHelper().setGlobalConfig(commonConfig, testHostConfig); final String dirToIgnore = "target"; final int execTimeout = 10000; final BapSshTransfer transfer = new BapSshTransfer( "**/*", null, "sub-home", dirToIgnore, false, false, "", execTimeout, false, false, false, null); final BapSshPublisher publisher = new BapSshPublisher( testHostConfig.getName(), false, new ArrayList<BapSshTransfer>(Collections.singletonList(transfer)), false, false, null, null, null); final BapSshPublisherPlugin plugin = new BapSshPublisherPlugin( new ArrayList<BapSshPublisher>(Collections.singletonList(publisher)), false, false, false, "master", null); final FreeStyleProject project = createFreeStyleProject(); project.getPublishersList().add(plugin); final String buildDirectory = "build-dir"; final String buildFileName = "file.txt"; project .getBuildersList() .add( new TestBuilder() { @Override public boolean perform( final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { final FilePath dir = build.getWorkspace().child(dirToIgnore).child(buildDirectory); dir.mkdirs(); dir.child(buildFileName).write("Helloooooo", "UTF-8"); build.setResult(Result.SUCCESS); return true; } }); when(mockJsch.getSession( testHostConfig.getUsername(), testHostConfig.getHostname(), testHostConfig.getPort())) .thenReturn(mockSession); when(mockSession.openChannel("sftp")).thenReturn(mockSftp); final SftpATTRS mockAttrs = mock(SftpATTRS.class); when(mockAttrs.isDir()).thenReturn(true); when(mockSftp.stat(anyString())).thenReturn(mockAttrs); assertBuildStatusSuccess(project.scheduleBuild2(0).get()); verify(mockJsch) .addIdentity("TheKey", BapSshUtil.toBytes("key"), null, BapSshUtil.toBytes("passphrase")); verify(mockSession).connect(timeout); verify(mockSftp).connect(timeout); verify(mockSftp).cd(transfer.getRemoteDirectory()); verify(mockSftp).cd("build-dir"); verify(mockSftp).put((InputStream) anyObject(), eq(buildFileName)); }