Java-sftptool_第1页
Java-sftptool_第2页
Java-sftptool_第3页
Java-sftptool_第4页
Java-sftptool_第5页
已阅读5页,还剩12页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、import java.io.File;   import java.io.FileInputStream;   import java.io.IOException;   import java.io.InputStream;   import java.io.OutputStream;   import java.util.ArrayList;   import java.util.List; 

2、0; import java.util.Vector;     import com.jcraft.jsch.Channel;   import com.jcraft.jsch.ChannelSftp;   import com.jcraft.jsch.JSch;   import com.jcraft.jsch.JSchException;   import com.jcraft.jsch.Session

3、;   import com.jcraft.jsch.SftpException;   import mon.util.log.EventLog;     /*   * In order for SSH2 tunneling to function correctly one must ensure that the   *&#

4、160;following line is uncommented in /etc/ssh/sshd_config :   * -CUT-   * # Change to yes to enable tunnelled clear text passwords   * PasswordAuthentication yes   *

5、 -CUT-   * Otherwise the initiation of the tunnel will fail with   * "SSH Initialization failed, try again?   * com.jcraft.jsch.JSchException: Auth fail"   *

6、60;author aimer.xu   *   */  public class SftpHelper extends Thread        private static EventLog log = new EventLog(SftpHelper.class);         

7、     private String host;       private String username;       private String password;       private String location;     &#

8、160; private int port;       private String knowHosts;              private String osName;              private

9、0;List<String> filenames = new ArrayList<String>();              public SftpHelper(String host, String username, String password, int port)     

10、0;      this(host, username, password, port, "");                     public SftpHelper(String host, String username, String&

11、#160;password, int port, String location)            this.host = host;           this.username = username;         

12、  this.password = password;           this.port = port;           osName = System.getProperty("");        &#

13、160;  if (osName.toUpperCase().indexOf("WINDOWS") > -1)                this.knowHosts = "c:known_hosts"           

14、60;   if(location = null | location.length() = 0)                   this.location = "c:"          &#

15、160;                else                this.knowHosts = "/root/.ssh/known_hosts"         

16、      if(location = null | location.length() = 0)                   this.location = "/"        

17、                             this.location = location;                   &#

18、160; public void addFilename(String filename)           filenames.add(filename);                     public void setFilenames(List

19、<String> filenames)           this.filenames = filenames;                public void run()          

20、0;upload();                     /*       * 要上传的文件必须包含完整的路径       *        */     

21、0;public boolean upload()           if(filenames.size() = 0)               return false;           Sessio

22、n session;           Channel channel;           JSch jsch = new JSch();           try      

23、0;         jsch.setKnownHosts(knowHosts);               session = jsch.getSession(username, host, port);           

24、    session.setPassword(password);               session.connect();               channel = session.openChannel("sftp");

25、               channel.connect();               ChannelSftp c = (ChannelSftp)channel;           

26、;    c.cd(location);                              InputStream in = null;         

27、0;     OutputStream out = null;               for(int i=0; i<filenames.size(); i+)                

28、;   String filename = filenames.get(i);                   if(filename = null | "".equals(filename)         

29、60;             log.Debug("", "当前没有要上传的文件!");                       continue;    

30、0;                                 int idx= filename.lastIndexOf(File.separator);         

31、          String uploadname = filename.substring(idx=-1?0:idx+1);                   out = c.put(uploadname);     &#

32、160;             log.Debug("", "sleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeep "+5000+"ms!");                  

33、 sleep(5000);                                      in = new FileInputStream(filename);   &

34、#160;                  /              String suffix = filename.substring(filename.lastIndexOf(".")+1);   /

35、0;             if("gz".equals(suffix)   /                  in = new GZIPInputStream(in);   / &#

36、160;                               byte  b = new byte1024;            

37、       int n;                   while (n = in.read(b) != -1)               

38、         out.write(b);                                         &#

39、160;       out.flush();               out.close();               in.close();         

40、      c.disconnect();               session.disconnect();               sleep(500);        

41、0;      return true;            catch (JSchException e)                e.printStackTrace();      

42、60;     catch (SftpException e)                e.printStackTrace();            catch (IOException e)     

43、           e.printStackTrace();            catch(InterruptedException e)               e.printStackTrace();  &

44、#160;                   return false;                     public static void main(String args)

45、          String username = "root"           String host = "*.*.*.*"           int port =&

46、#160;22;           String password = "*"           String path = "/home/data/download/"           Sf

47、tpHelper helper = new SftpHelper(host, username,password, port,path);           helper.addFilename("c:bcp.sql");           helper.addFilename("c:a.sql"

48、;);   /      helper.upload("c:bcp.sql");           helper.start();                       import java

49、.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import java.util.Vector;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.

50、jcraft.jsch.JSchException;import com.jcraft.jsch.Session;import com.jcraft.jsch.SftpException;import mon.util.log.EventLog;/* * In order for SSH2 tunneling to function correctly one must ensure that the * following line is uncommented in /etc/ssh/sshd_config : * -CUT- * # Change to yes to enable tun

51、nelled clear text passwords * PasswordAuthentication yes * -CUT- * Otherwise the initiation of the tunnel will fail with * "SSH Initialization failed, try again? * com.jcraft.jsch.JSchException: Auth fail" * author aimer.xu * */public class SftpHelper extends Thread private static EventLog

52、 log = new EventLog(SftpHelper.class);private String host;private String username;private String password;private String location;private int port;private String knowHosts;private String osName;private List<String> filenames = new ArrayList<String>();public SftpHelper(String host, String

53、 username, String password, int port) this(host, username, password, port, "");public SftpHelper(String host, String username, String password, int port, String location) this.host = host;this.username = username;this.password = password;this.port = port;osName = System.getProperty("o

54、");if (osName.toUpperCase().indexOf("WINDOWS") > -1) this.knowHosts = "c:known_hosts" if(location = null | location.length() = 0) this.location = "c:" else this.knowHosts = "/root/.ssh/known_hosts" if(location = null | location.length() = 0) this

55、.location = "/" this.location = location;public void addFilename(String filename)filenames.add(filename);public void setFilenames(List<String> filenames)this.filenames = filenames;public void run()upload();/* * 要上传的文件必须包含完整的路径 * */public boolean upload()if(filenames.size() = 0)return

56、 false;Session session;Channel channel;JSch jsch = new JSch();try jsch.setKnownHosts(knowHosts);session = jsch.getSession(username, host, port);session.setPassword(password);session.connect();channel = session.openChannel("sftp");channel.connect();ChannelSftp c = (ChannelSftp)channel;c.cd(

57、location);InputStream in = null;OutputStream out = null;for(int i=0; i<filenames.size(); i+)String filename = filenames.get(i);if(filename = null | "".equals(filename)log.Debug("", "当前没有要上传的文件!");continue;int idx= filename.lastIndexOf(File.separator);String uploadnam

58、e = filename.substring(idx=-1?0:idx+1);out = c.put(uploadname);log.Debug("", "sleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeep "+5000+"ms!");sleep(5000);in = new FileInputStream(filename);/String suffix = filename.substring(filename.lastIndexOf(".")+1);/if("

59、gz".equals(suffix)/in = new GZIPInputStream(in);/byte b = new byte1024;int n;while (n = in.read(b) != -1) out.write(b);out.flush();out.close();in.close();c.disconnect();session.disconnect();sleep(500);return true; catch (JSchException e) e.printStackTrace(); catch (SftpException e) e.printStack

60、Trace(); catch (IOException e) e.printStackTrace(); catch(InterruptedException e)e.printStackTrace();return false;public static void main(String args)String username = "root"String host = "*.*.*.*"int port = 22;String password = "*"String path = "/home/data/downloa

61、d/"SftpHelper helper = new SftpHelper(host, username,password, port,path);helper.addFilename("c:bcp.sql");helper.addFilename("c:a.sql");/helper.upload("c:bcp.sql");helper.start(); 请注意类的注释部分,known_hosts文件的内容如下:Java代码 90 ssh-rsa AAAAB3NzaC1yc2

62、EAAAABIwAAAIEA6tHmMBQwcSieFneaObnDyzthMSn1FyWFp/TCMV4rt+ZEtOZo49GK0kdM3tYy1IQD8hZz016JG5uOIbrBN+O0BtzY89y3uIwo0hsYQtP/LKAR5BU+pT3R20ltVbcEGzrSpKiSClObD9MbiOt0899Du9bG89/BiMvxUxj/Rhg33l0=  90 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEA6tHmMBQwcSieFneaObnDyzthMSn1FyWFp/TCMV4rt+ZEtOZo49GK0k

63、dM3tYy1IQD8hZz016JG5uOIbrBN+O0BtzY89y3uIwo0hsYQtP/LKAR5BU+pT3R20ltVbcEGzrSpKiSClObD9MbiOt0899Du9bG89/BiMvxUxj/Rhg33l0=  写道附:产生此文件的简单方法:可以在Linux中用ssh命令登录一次,这样便在/root/.ssh(假如使用root用户登录到Linux)目录下生成known_hosts文件。 /* * */package com.test.tool;import mons.vfs.FileObject; import mons.vfs.FileSyst

64、emException; import mons.vfs.FileSystemOptions; import mons.vfs.Selectors; import mons.vfs.cache.DefaultFilesCache; import mons.vfs.impl.DefaultFileSystemManager; import vider.local.DefaultLocalFileProvider; import vider.sftp.SftpFileProvider; import vider.sftp.Sf

65、tpFileSystemConfigBuilder; import vider.zip.ZipFileProvider; import mons.logging.*;/* 15. * author myao Update:2006-7-1810:40:46 16. */ public class AutoChecker private String _sourceroot = "C:/vfsroot" private String _targetroot = "sftp:/odpuser:odpuser1:22/doc

66、-root/myaoVfstest/" / b1:f1:ef:26:3e:5f:a5:0d:70:fa:5e:df:d9:6b:55:41 private FileObject localfs, targetfs; private DefaultFileSystemManager vfsmgr; private Log log = LogFactory.getLog(AutoChecker.class); AutoChecker() try init(); catch (FileSystemException e) e.printStackTrace(); void init() t

67、hrows FileSystemException vfsmgr = getDefaultFileSystemManager(); void moveFile(String sourcePath, String targetPath) throws FileSystemException localfs = vfsmgr.resolveFile(sourcePath); if (!localfs.exists() localfs.createFolder(); / localfs. / vfsmgr. FileSystemOptions opts = new FileSystemOptions

68、(); SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking( opts, "no"); targetfs = vfsmgr.resolveFile(targetPath, opts); if (!targetfs.exists() targetfs.createFolder(); try long startTime = System.currentTimeMillis(); / System.out.println("Source File:" + source.getC

69、hildren().length); targetfs.copyFrom(localfs, Selectors.SELECT_FILES); / System.out.println("Target File:" + target.getChildren().length); / TODO 要想办法用遍历的方法来拷贝文件,否则无法留下拷贝的细节。 /正在装载数据 / FileObject flist = localfs.getChildren(); / for (int i = 0; i < flist.length; i+) / FileObject tmp = v

70、fsmgr.resolveFile(targetfs, flisti.getName() / .getBaseName(); / if (!tmp.exists() / tmp.createFile(); / / / VfsMutiMove t = new VfsMutiMove(flisti, tmp); / t.run(); / / tmp.copyFrom(flisti, Selectors.SELECT_SELF); / long endTime = System.currentTimeMillis(); System.out.println(this.getClass().getNa

71、me(); System.out.println("Cost time(ms:):" + (endTime - startTime); catch (FileSystemException e) e.printStackTrace(); private DefaultFileSystemManager getDefaultFileSystemManager() DefaultFileSystemManager mgr = new DefaultFileSystemManager(); / SFTP 供应者 SftpFileProvider fp = new SftpFile

72、Provider(); FileSystemOptions t = new FileSystemOptions(); / ZIP 供应者 ZipFileProvider zp = new ZipFileProvider(); / 缺省本地文件供应者 DefaultLocalFileProvider lf = new DefaultLocalFileProvider(); try / common-vfs 中 文件管理器的使用范例 mgr.addProvider("sftp", fp); mgr.addProvider("zip", zp); mgr.ad

73、dProvider("file", lf); mgr.setFilesCache(new DefaultFilesCache(); mgr.init(); catch (FileSystemException e) / 此处应该改为log e.printStackTrace(); return mgr; void getWorkspaceFromProperties() /* * Properties tmpProperties; File tmpfile = new * File("perties"); */ /* 138.

74、* param args 139. * throws Exception 140. */ public static void main(String args) throws Exception AutoChecker op =new AutoChecker(); op.moveFile("C:/downloads", "sftp:/odpuser:odpuser1:22/etc/services"); VFSTest.javaimport java.io.IOException;import mons.vfs.FileConte

75、nt;import mons.vfs.FileObject;import mons.vfs.FileSystemManager;import mons.vfs.FileType;import mons.vfs.VFS;public class VFSTest     public static void main(String args) throws IOException                 FileSyste

76、mManager fsManager = VFS.getManager();        FileObject fo = fsManager.resolveFile("ftp:/ftpusername:ftppassword:21/dir/dir1/");        FileObject children = fo.getChildren();/得到远程文件列表    

77、       for ( int i = 0; i < children.length; i+ )                            FileObject f = children i ;     

78、60;              FileContent c = f.getContent();                          File localFile = new File(f.getName().get

79、BaseName();                   FileOutputStream out = new FileOutputStream(localFile);                   mons.io.IOUtils.

80、copy(c.getInputStream(), out);/写入本地/或使用写入                FileObject obj = fileSystemManager.resolveFile(this.getTargetResourceURL()+f.getName().getBaseName();           &

81、#160;                   if(!obj.exists()                    obj.createFile();       &

82、#160;            obj.copyFrom(f, Selectors.SELECT_SELF);                              final long size = ( f.ge

83、tType() = FileType.FILE ) ? c.getSize() : -1;            final long date = ( f.getType() = FileType.FILE ) ? c.getLastModifiedTime() : -1;            System.out.println( f.getName().getPath(

84、)+ " date:" + date + " Size:" + size  );            连接SFTPFileSystemManager fsManager = VFS.getManager();    FileSystemOptions opts = new FileSystemOptions();            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论