通过jsch和linux服务器进行文件的上传下载删除

jsch 是ssh2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器


一般连接到服务器有两种方式:

1、通过用户名和密码连接,缺点(出于安全需要,一般服务器的密码会定期修改,程序部署后将不得不经常更新配置文件中的密    码。)

2、通过用户名和ssh private key file连接,缺点(因为Java程序必须和private key file在同一台机器上,将服务器的private key file复制到本地后,本地机器的安全措施可能会使private key file被窃取,威胁服务器安全。)


  jsch官网地址为http://www.jcraft.com/jsch/,实现jsch功能需要添加一个jsch-0.1.51.jar包,官网有一些例子可直接下载参考。

maven的配置为:

[html]  view plain  copy
  1. <dependency>  
  2.             <groupId>com.jcraft</groupId>  
  3.             <artifactId>jsch</artifactId>  
  4.             <version>0.1.51</version>  
  5. </dependency>  


1、jsch连接到linux的基本原理和用ssh一样,需要ip地址,端口(一般为22),用户名,密码,为了方便配置,可以把静态变量初始化在配置文件中:

 

[html]  view plain  copy
  1. #jsch配置  
  2. host.ip=192.168.1.1  
  3. host.user=root  
  4. host.port=22  
  5. host.password=123456  
  6. host.connect.timeout=5000     

获取配置文件变量的工具类:

[java]  view plain  copy
  1. package com.personal.core.constant;  
  2.   
  3.   
  4. import com.personal.core.utils.PropertiesLoader;  
  5. import org.apache.commons.lang.StringUtils;  
  6. import org.springframework.core.io.DefaultResourceLoader;  
  7.   
  8. import java.io.File;  
  9. import java.io.IOException;  
  10. import java.util.HashMap;  
  11. import java.util.Map;  
  12.   
  13. /** 
  14.  * 注释:全局配置类 
  15.  * 
  16.  * @Author: coding99 
  17.  * @Date: 16-9-2 
  18.  * @Time: 下午7:33 
  19.  */  
  20. public class Global {  
  21.   
  22.   
  23.     /** 
  24.      * 当前对象实例 
  25.      */  
  26.     private static Global global = new Global();  
  27.       
  28.     /** 
  29.      * 保存全局属性值 
  30.      */  
  31.     private static Map<String, String> map = new HashMap<String, String>();  
  32.       
  33.     /** 
  34.      * 属性文件加载对象 
  35.      */  
  36.     private static PropertiesLoader loader = new PropertiesLoader("sysConfig.properties");  
  37.   
  38.   
  39.       
  40.     /** 
  41.      * 获取当前对象实例 
  42.      */  
  43.     public static Global getInstance() {  
  44.         return global;  
  45.     }  
  46.       
  47.     /** 
  48.      * 获取配置 
  49.      * @see {fns:getConfig('adminPath')} 
  50.      */  
  51.     public static String getConfig(String key) {  
  52.         String value = map.get(key);  
  53.         if (value == null){  
  54.             value = loader.getProperty(key);  
  55.             map.put(key, value != null ? value : StringUtils.EMPTY);  
  56.         }  
  57.         return value;  
  58.     }/**     * 获取工程路径     * @return     */    public static String getProjectPath(){        // 如果配置了工程路径,则直接返回,否则自动获取。String projectPath = Global.getConfig("projectPath");if (StringUtils.isNotBlank(projectPath)){return projectPath;}try {File file = new DefaultResourceLoader().getResource("").getFile();if (file != null){while(true){File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");if (f == null || f.exists()){break;}if (file.getParentFile() != null){file = file.getParentFile();}else{break;}}projectPath = file.toString();}} catch (IOException e) {e.printStackTrace();}return projectPath;    }}  
  59.       
  60.     /** 
  61.      * 获取工程路径 
  62.      * @return 
  63.      */  
  64.     public static String getProjectPath(){  
  65.         // 如果配置了工程路径,则直接返回,否则自动获取。  
  66.         String projectPath = Global.getConfig("projectPath");  
  67.         if (StringUtils.isNotBlank(projectPath)){  
  68.             return projectPath;  
  69.         }  
  70.         try {  
  71.             File file = new DefaultResourceLoader().getResource("").getFile();  
  72.             if (file != null){  
  73.                 while(true){  
  74.                     File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");  
  75.                     if (f == null || f.exists()){  
  76.                         break;  
  77.                     }  
  78.                     if (file.getParentFile() != null){  
  79.                         file = file.getParentFile();  
  80.                     }else{  
  81.                         break;  
  82.                     }  
  83.                 }  
  84.                 projectPath = file.toString();  
  85.             }  
  86.         } catch (IOException e) {  
  87.             e.printStackTrace();  
  88.         }  
  89.         return projectPath;  
  90.     }  
  91.   
  92.   
  93. }  



2、为了方便脚本配置,统一管理,修改,我们可以把脚本放在一个xml里面,例如:
[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <configuration>  
  3.   
  4.   
  5.     <!--开发环境-->  
  6.     <shell name="ls" env="dev">  
  7.         <description>查看opt文件夹内容</description>  
  8.         <step>ls -ltr /opt</step>  
  9.     </shell>  
  10.   
  11.     <!--开发环境-->  
  12.     <shell name="ls" env="uat">  
  13.         <description>查看opt文件夹内容</description>  
  14.         <step>ls -ltr /opt</step>  
  15.     </shell>  
  16.   
  17.     <!--生产环境-->  
  18.     <shell name="ls" env="pro">  
  19.         <description>查看opt文件夹内容</description>  
  20.         <step>ls -ltr /opt</step>  
  21.     </shell>  
  22.   
  23.   
  24. </configuration>  

3、获取脚本的方法通过一个工具类读取这个配置文件,用dom4j进行解析,获取相应指定shell name的脚本,例如

[java]  view plain  copy
  1. package com.personal.core.utils;  
  2.   
  3. import com.personal.core.constant.Global;  
  4. import org.dom4j.Document;  
  5. import org.dom4j.Element;  
  6. import org.dom4j.io.SAXReader;  
  7.   
  8. import java.io.File;  
  9. import java.util.List;  
  10.   
  11. /** 
  12.  * 注释 
  13.  * 
  14.  * @Author: coding99 
  15.  * @Date: 16-9-2 
  16.  * @Time: 下午9:31 
  17.  */  
  18. public class ShellConfigUtil {  
  19.   
  20.     private static final String SHELL_ENV = Global.getConfig("environment");  
  21.     private static final String DEFAULT_SHELL_CONFIG = ShellConfigUtil.class.getResource("/").getPath()+"shell.xml";  
  22.   
  23.     private ShellConfigUtil() {  
  24.   
  25.     }  
  26.   
  27.   
  28.     /** 
  29.      * 取得脚本 
  30.      * @param shellName 
  31.      * @return 
  32.      * @throws Exception 
  33.      */  
  34.     public static String getShell(String shellName)throws Exception{  
  35.         String shellContent = "";  
  36.   
  37.         List<Element> shells = getShellEelements();  
  38.   
  39.         for(Element shell : shells) {  
  40.             String name = shell.attributeValue("name");  
  41.             String env = shell.attributeValue("env");  
  42.             //把shell数组遍历  
  43.             if(shellName.equals(name) && SHELL_ENV.equals(env)) {  
  44.                 shellContent = getShellResult(shell);  
  45.             }  
  46.   
  47.         }  
  48.         return shellContent;  
  49.     }  
  50.   
  51.     /** 
  52.      * 解析xml 
  53.      * @return 
  54.      * @throws Exception 
  55.      */  
  56.     public static List<Element> getShellEelements() throws Exception{  
  57.         SAXReader saxReader = new SAXReader();//创建读取配置文件的对象  
  58.         Document document = saxReader.read(new File(DEFAULT_SHELL_CONFIG));//开始读取配置文件  
  59.         Element element = document.getRootElement();  
  60.         List<Element> shellElements = element.elements("shell");  
  61.         return shellElements;  
  62.     }  
  63.   
  64.     /** 
  65.      * 获取脚本内容 
  66.      * @param shell 
  67.      * @return 
  68.      */  
  69.     public static String getShellResult(Element shell) {  
  70.         String result = "";  
  71.         List<Element> steps = shell.elements("step");  
  72.         for (Element step : steps) {  
  73.             result = step.getText();  
  74.         }  
  75.         return result;  
  76.     }  
  77.   
  78.   
  79.   
  80.     public static void main(String[] args) throws Exception{  
  81.         ShellConfigUtil.getShell("ls");  
  82.     }  
  83.   
  84. }  

 
 

4、JSCH实现原理:

jsch进行连接服务器连接时可以看做时java的jdbc连接,首先我们需要实例化一个jsch对象,再利用这个对象 根据用户名,主机ip,端口获取一个Session对象,设置好相应的参数后,就进行连接,创建连接后这个session是一直可用的,所以不需要关闭。之后我们需要在session上建立channel通道

Channel的类型可以为如下类型:

shell - ChannelShell exec - ChannelExec  

direct-tcpip - ChannelDirectTCPIP sftp - ChannelSftp subsystem - ChannelSubsystem

 其中,ChannelShell和ChannelExec比较类似,都可以作为执行Shell脚本的Channel类型。它们有一个比较重要的区别:ChannelShell可以看作是执行一个交互式的Shell,而ChannelExec是执行一个Shell脚本。

实现远程命令操作我们需要创建ChannelExec对象。

实现文件上传下载我们需要实现ChannelSftp对象。

ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如:
put():      文件上传
get():      文件下载
cd():       进入指定目录
ls():       得到指定目录下的文件列表
rename():   重命名指定文件或目录
rm():       删除指定文件
mkdir():    创建目录
rmdir():    删除目录下面有个工具类展示
应用实例:
JschUtil.java
[java]  view plain  copy
  1. package com.personal.core.utils;  
  2. import com.jcraft.jsch.*;  
  3. import com.personal.core.constant.Global;  
  4. import org.slf4j.Logger;  
  5. import org.slf4j.LoggerFactory;  
  6.   
  7. import java.io.*;  
  8. import java.nio.charset.Charset;  
  9. import java.util.*;  
  10. /** 
  11.  * 注释 
  12.  * 
  13.  * @Author: coding99 
  14.  * @Date: 16-9-2 
  15.  * @Time: 下午7:33 
  16.  */  
  17. public class JschUtil {  
  18.   
  19.     private static final Logger logger = LoggerFactory.getLogger(JschUtil.class);  
  20.   
  21.     private String charset = "UTF-8"// 设置编码格式,可以根据服务器的编码设置相应的编码格式  
  22.     private JSch jsch;  
  23.     private Session session;  
  24.     Channel channel = null;  
  25.     ChannelSftp chSftp = null;  
  26.   
  27.   
  28.     //初始化配置参数  
  29.     private String jschHost = Global.getConfig("host.ip");  
  30.     private int jschPort = Integer.parseInt(Global.getConfig("host.port"));  
  31.     private String jschUserName = Global.getConfig("host.user");  
  32.     private String jschPassWord = Global.getConfig("host.password");  
  33.     private int jschTimeOut = Integer.parseInt(Global.getConfig("host.connect.timeout"));  
  34.   
  35.   
  36.   
  37.     /** 
  38.      * 静态内部类实现单例模式 
  39.      */  
  40.     private static class LazyHolder {  
  41.         private static final JschUtil INSTANCE = new JschUtil();  
  42.     }  
  43.   
  44.     private JschUtil() {  
  45.   
  46.     }  
  47.   
  48.     /** 
  49.      * 获取实例 
  50.      * @return 
  51.      */  
  52.     public static final JschUtil getInstance() {  
  53.         return LazyHolder.INSTANCE;  
  54.     }  
  55.   
  56.   
  57.     /** 
  58.      * 连接到指定的服务器 
  59.      * @return 
  60.      * @throws JSchException 
  61.      */  
  62.     public boolean connect() throws JSchException {  
  63.   
  64.         jsch = new JSch();// 创建JSch对象  
  65.   
  66.         boolean result = false;  
  67.   
  68.         try{  
  69.   
  70.             long begin = System.currentTimeMillis();//连接前时间  
  71.             logger.debug("Try to connect to jschHost = " + jschHost + ",as jschUserName = " + jschUserName + ",as jschPort =  " + jschPort);  
  72.   
  73.             session = jsch.getSession(jschUserName, jschHost, jschPort);// // 根据用户名,主机ip,端口获取一个Session对象  
  74.             session.setPassword(jschPassWord); // 设置密码  
  75.             Properties config = new Properties();  
  76.             config.put("StrictHostKeyChecking""no");  
  77.             session.setConfig(config);// 为Session对象设置properties  
  78.             session.setTimeout(jschTimeOut);//设置连接超时时间  
  79.             session.connect();  
  80.   
  81.             logger.debug("Connected successfully to jschHost = " + jschHost + ",as jschUserName = " + jschUserName + ",as jschPort =  " + jschPort);  
  82.   
  83.             long end = System.currentTimeMillis();//连接后时间  
  84.   
  85.             logger.debug("Connected To SA Successful in {} ms", (end-begin));  
  86.   
  87.             result = session.isConnected();  
  88.   
  89.         }catch(Exception e){  
  90.             logger.error(e.getMessage(), e);  
  91.         }finally{  
  92.             if(result){  
  93.                 logger.debug("connect success");  
  94.             }else{  
  95.                 logger.debug("connect failure");  
  96.             }  
  97.         }  
  98.   
  99.         if(!session.isConnected()) {  
  100.             logger.error("获取连接失败");  
  101.         }  
  102.   
  103.         return  session.isConnected();  
  104.   
  105.     }  
  106.   
  107.     /** 
  108.      * 关闭连接 
  109.      */  
  110.     public void close() {  
  111.   
  112.         if(channel != null && channel.isConnected()){  
  113.             channel.disconnect();  
  114.             channel=null;  
  115.         }  
  116.   
  117.         if(session!=null && session.isConnected()){  
  118.             session.disconnect();  
  119.             session=null;  
  120.         }  
  121.   
  122.     }  
  123.   
  124.     /** 
  125.      * 脚本是同步执行的方式 
  126.      * 执行脚本命令 
  127.      * @param command 
  128.      * @return 
  129.      */  
  130.     public Map<String,Object> execCmmmand(String command) throws Exception{  
  131.   
  132.   
  133.         Map<String,Object> mapResult = new HashMap<String,Object>();  
  134.   
  135.         logger.debug(command);  
  136.   
  137.         StringBuffer result = new StringBuffer();//脚本返回结果  
  138.   
  139.         BufferedReader reader = null;  
  140.         int returnCode = -2;//脚本执行退出状态码  
  141.   
  142.   
  143.         try {  
  144.   
  145.             channel = session.openChannel("exec");  
  146.             ((ChannelExec) channel).setCommand(command);  
  147.             channel.setInputStream(null);  
  148.             ((ChannelExec) channel).setErrStream(System.err);  
  149.   
  150.             channel.connect();//执行命令 等待执行结束  
  151.   
  152.             InputStream in = channel.getInputStream();  
  153.             reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));  
  154.   
  155.             String res="";  
  156.             while((res=reader.readLine()) != null){  
  157.                 result.append(res+"\n");  
  158.                 logger.debug(res);  
  159.             }  
  160.   
  161.             returnCode = channel.getExitStatus();  
  162.   
  163.             mapResult.put("returnCode",returnCode);  
  164.             mapResult.put("result",result.toString());  
  165.   
  166.         } catch (IOException e) {  
  167.   
  168.             logger.error(e.getMessage(),e);  
  169.   
  170.         } catch (JSchException e) {  
  171.   
  172.             logger.error(e.getMessage(), e);  
  173.   
  174.         } finally {  
  175.             try {  
  176.                 reader.close();  
  177.             } catch (IOException e) {  
  178.                 logger.error(e.getMessage(), e);  
  179.             }  
  180.         }  
  181.   
  182.         return mapResult;  
  183.   
  184.     }  
  185.   
  186.     /** 
  187.      * 上传文件 
  188.      * 
  189.      * @param directory 上传的目录,有两种写法 
  190.      *                  1、如/opt,拿到则是默认文件名 
  191.      *                  2、/opt/文件名,则是另起一个名字 
  192.      * @param uploadFile 要上传的文件 如/opt/xxx.txt 
  193.      */  
  194.     public void upload(String directory, String uploadFile) {  
  195.   
  196.         try {  
  197.   
  198.             logger.debug("Opening Channel.");  
  199.             channel = session.openChannel("sftp"); // 打开SFTP通道  
  200.             channel.connect(); // 建立SFTP通道的连接  
  201.             chSftp = (ChannelSftp) channel;  
  202.             File file = new File(uploadFile);  
  203.             long fileSize = file.length();  
  204.   
  205.             /*方法一*/  
  206.              OutputStream out = chSftp.put(directory, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式  
  207.              byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KB  
  208.              int read;  
  209.              if (out != null) {  
  210.                  logger.debug("Start to read input stream");  
  211.                 InputStream is = new FileInputStream(uploadFile);  
  212.                 do {  
  213.                     read = is.read(buff, 0, buff.length);  
  214.                      if (read > 0) {  
  215.                             out.write(buff, 0, read);  
  216.                      }  
  217.                      out.flush();  
  218.                  } while (read >= 0);  
  219.                  logger.debug("input stream read done.");  
  220.              }  
  221.   
  222.             // chSftp.put(uploadFile, directory, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); //方法二  
  223.             // chSftp.put(new FileInputStream(src), dst, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); //方法三  
  224.             logger.debug("成功上传文件至"+directory);  
  225.   
  226.         } catch (Exception e) {  
  227.             e.printStackTrace();  
  228.         }finally {  
  229.             chSftp.quit();  
  230.   
  231.             if (channel != null) {  
  232.                 channel.disconnect();  
  233.                 logger.debug("channel disconnect");  
  234.             }  
  235.   
  236.         }  
  237.     }  
  238.   
  239.   
  240.     /** 
  241.      * 下载文件 
  242.      * 
  243.      * @param directory 下载的目录,有两种写法 
  244.      *                  1、如/opt,拿到则是默认文件名 
  245.      *                  2、/opt/文件名,则是另起一个名字 
  246.      * @param downloadFile 要下载的文件 如/opt/xxx.txt 
  247.      * 
  248.      */  
  249.   
  250.     public void download(String directory, String downloadFile) {  
  251.         try {  
  252.   
  253.             logger.debug("Opening Channel.");  
  254.             channel = session.openChannel("sftp"); // 打开SFTP通道  
  255.             channel.connect(); // 建立SFTP通道的连接  
  256.             chSftp = (ChannelSftp) channel;  
  257.             SftpATTRS attr = chSftp.stat(downloadFile);  
  258.             long fileSize = attr.getSize();  
  259.   
  260.   
  261.             OutputStream out = new FileOutputStream(directory);  
  262.   
  263.             InputStream is = chSftp.get(downloadFile, new MyProgressMonitor());  
  264.             byte[] buff = new byte[1024 * 2];  
  265.             int read;  
  266.             if (is != null) {  
  267.                 logger.debug("Start to read input stream");  
  268.                 do {  
  269.                     read = is.read(buff, 0, buff.length);  
  270.                     if (read > 0) {  
  271.                         out.write(buff, 0, read);  
  272.                     }  
  273.                     out.flush();  
  274.                 } while (read >= 0);  
  275.                 logger.debug("input stream read done.");  
  276.             }  
  277.   
  278.             //chSftp.get(downloadFile, directory, new FileProgressMonitor(fileSize)); // 代码段1  
  279.             //chSftp.get(downloadFile, out, new FileProgressMonitor(fileSize)); // 代码段2  
  280.   
  281.             logger.debug("成功下载文件至"+directory);  
  282.         } catch (Exception e) {  
  283.             e.printStackTrace();  
  284.         } finally {  
  285.             chSftp.quit();  
  286.             if (channel != null) {  
  287.                 channel.disconnect();  
  288.                 logger.debug("channel disconnect");  
  289.             }  
  290.         }  
  291.     }  
  292.   
  293.   
  294.     /** 
  295.      * 删除文件 
  296.      * @param deleteFile 要删除的文件 
  297.      */  
  298.     public void delete(String deleteFile) {  
  299.   
  300.         try {  
  301.             connect();//建立服务器连接  
  302.             logger.debug("Opening Channel.");  
  303.             channel = session.openChannel("sftp"); // 打开SFTP通道  
  304.             channel.connect(); // 建立SFTP通道的连接  
  305.             chSftp = (ChannelSftp) channel;  
  306.             chSftp.rm(deleteFile);  
  307.             logger.debug("成功删除文件"+deleteFile);  
  308.         } catch (Exception e) {  
  309.             e.printStackTrace();  
  310.         }  
  311.   
  312.     }  
  313.   
  314.   
  315.     public String getCharset() {  
  316.         return charset;  
  317.     }  
  318.   
  319.     public void setCharset(String charset) {  
  320.         this.charset = charset;  
  321.     }  
  322.   
  323.   
  324.   
  325.     public static void main(String[] args) throws Exception{  
  326.   
  327.         JschUtil jschUtil = JschUtil.getInstance();  
  328.   
  329.         boolean isConnected = false;  
  330.         isConnected  = jschUtil.connect();  
  331.   
  332.         if(isConnected == true){  
  333.   
  334.   
  335.             /*上传文件*/  
  336.             jschUtil.upload("/opt/123456.png","/home/sky/Desktop/resizeApi.png");  
  337.   
  338.              /*执行命令*/  
  339.             String command = "ls -ltr /opt";  
  340.            // String command = ShellConfigUtil.getShell("ls");  
  341.             Map<String,Object> result = jschUtil.execCmmmand(command);  
  342.             System.out.println(result.get("result").toString());  
  343.   
  344.             /*下载文件*/  
  345.             jschUtil.download("/opt/123456.png","/opt/123456.png");  
  346.   
  347.             jschUtil.close();  
  348.   
  349.         }  
  350.   
  351.   
  352.     }  
  353. }  





 
  
[java]  view plain  copy
  1. package com.personal.core.utils;  
  2. import java.text.DecimalFormat;  
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import com.jcraft.jsch.SftpProgressMonitor;  
  7. import org.slf4j.Logger;  
  8. import org.slf4j.LoggerFactory;  
  9.   
  10. /** 
  11.  * 注释 
  12.  * 
  13.  * @Author: coding99 
  14.  * @Date: 16-9-2 
  15.  * @Time: 下午8:29 
  16.  */  
  17. public class FileProgressMonitor extends TimerTask implements SftpProgressMonitor {  
  18.   
  19.     private static final Logger logger = LoggerFactory.getLogger(FileProgressMonitor.class);  
  20.       
  21.   
  22.     private long progressInterval = 5 * 1000// 默认间隔时间为5秒  
  23.   
  24.     private boolean isEnd = false// 记录传输是否结束  
  25.   
  26.     private long transfered; // 记录已传输的数据总大小  
  27.   
  28.     private long fileSize; // 记录文件总大小  
  29.   
  30.     private Timer timer; // 定时器对象  
  31.   
  32.     private boolean isScheduled = false// 记录是否已启动timer记时器  
  33.   
  34.     public FileProgressMonitor(long fileSize) {  
  35.         this.fileSize = fileSize;  
  36.     }  
  37.     
  38.     @Override  
  39.     public void run() {  
  40.   
  41.         if (!isEnd()) { // 判断传输是否已结束  
  42.   
  43.             logger.debug("Transfering is in progress.");  
  44.   
  45.             long transfered = getTransfered();  
  46.   
  47.             if (transfered != fileSize) { // 判断当前已传输数据大小是否等于文件总大小  
  48.                 logger.debug("Current transfered: " + transfered + " bytes");  
  49.                 sendProgressMessage(transfered);  
  50.             } else {  
  51.                 logger.debug("File transfering is done.");  
  52.                 setEnd(true); // 如果当前已传输数据大小等于文件总大小,说明已完成,设置end  
  53.             }  
  54.         } else {  
  55.             logger.debug("Transfering done. Cancel timer.");  
  56.             stop(); // 如果传输结束,停止timer记时器  
  57.             return;  
  58.         }  
  59.     }  
  60.   
  61.     public void stop() {  
  62.         logger.debug("Try to stop progress monitor.");  
  63.         if (timer != null) {  
  64.             timer.cancel();  
  65.             timer.purge();  
  66.             timer = null;  
  67.             isScheduled = false;  
  68.         }  
  69.         logger.debug("Progress monitor stoped.");  
  70.     }  
  71.   
  72.     public void start() {  
  73.         logger.debug("Try to start progress monitor.");  
  74.         if (timer == null) {  
  75.             timer = new Timer();  
  76.         }  
  77.         timer.schedule(this1000, progressInterval);  
  78.         isScheduled = true;  
  79.         logger.debug("Progress monitor started.");  
  80.     }  
  81.   
  82.     /** 
  83.      * 打印progress信息 
  84.      * @param transfered 
  85.      */  
  86.     private void sendProgressMessage(long transfered) {  
  87.         if (fileSize != 0) {  
  88.             double d = ((double)transfered * 100)/(double)fileSize;  
  89.             DecimalFormat df = new DecimalFormat( "#.##");  
  90.             logger.debug("Sending progress message: " + df.format(d) + "%");  
  91.         } else {  
  92.             logger.debug("Sending progress message: " + transfered);  
  93.         }  
  94.     }  
  95.   
  96.     /** 
  97.      * 实现了SftpProgressMonitor接口的count方法 
  98.      */  
  99.     public boolean count(long count) {  
  100.         if (isEnd()) return false;  
  101.         if (!isScheduled) {  
  102.             start();  
  103.         }  
  104.         add(count);  
  105.         return true;  
  106.     }  
  107.   
  108.     /** 
  109.      * 实现了SftpProgressMonitor接口的end方法 
  110.      */  
  111.     public void end() {  
  112.         setEnd(true);  
  113.         logger.debug("transfering end.");  
  114.     }  
  115.   
  116.     private synchronized void add(long count) {  
  117.         transfered = transfered + count;  
  118.     }  
  119.   
  120.     private synchronized long getTransfered() {  
  121.         return transfered;  
  122.     }  
  123.   
  124.     public synchronized void setTransfered(long transfered) {  
  125.         this.transfered = transfered;  
  126.     }  
  127.   
  128.     private synchronized void setEnd(boolean isEnd) {  
  129.         this.isEnd = isEnd;  
  130.     }  
  131.   
  132.     private synchronized boolean isEnd() {  
  133.         return isEnd;  
  134.     }  
  135.   
  136.     public void init(int op, String src, String dest, long max) {  
  137.         // Not used for putting InputStream  
  138.     }  
  139. }  


 
  
[java]  view plain  copy
  1. package com.personal.core.utils;  
  2.   
  3.   
  4. import com.jcraft.jsch.SftpProgressMonitor;  
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7.   
  8.   
  9.   
  10.   
  11. /** 
  12.  * 注释 
  13.  * 
  14.  * @Author: coding99 
  15.  * @Date: 16-9-2 
  16.  * @Time: 下午8:36 
  17.  */  
  18.   
  19.   
  20. public class MyProgressMonitor implements SftpProgressMonitor {  
  21.   
  22.   
  23.     private static final Logger logger = LoggerFactory.getLogger(MyProgressMonitor.class);  
  24.   
  25.   
  26.     private long transfered;  
  27.   
  28.   
  29.     @Override  
  30.     public boolean count(long count) {  
  31.         transfered = transfered + count;  
  32.         logger.debug("Currently transferred total size: " + transfered + " bytes");  
  33.         return true;  
  34.     }  
  35.   
  36.   
  37.     @Override  
  38.     public void end() {  
  39.         logger.debug("Transferring done.");  
  40.     }  
  41.   
  42.   
  43.     @Override  
  44.     public void init(int op, String src, String dest, long max) {  
  45.         logger.debug("Transferring begin.");  
  46.     }  
  47.   
  48.   
  49. }  
:工具类主要封装了三个方法 
1、执行脚本命令 
2、文件上传(为了做进度监控,需要用到监控类FileProgressMonitor.java) 
3、文件下载 (为了做进度监控,需要用到监控类MyProgressMonitor.java

JschUtil.java工具类的几个使用步骤如下
1、初始化连接参数
2、调用connect()方法进行连接
3、执行相应的方法,如果是脚本命令,先用ShellConfigUtil.java获取相应的脚本,再执行 (jsch执行脚本的方式是同步,就是要等到脚本执行结束才返回结果,如果没有返回就一直等着,应该不支持交互式命令,比如连接到某个数据库,然后执行相应的操作)
4、最后关闭连接

猜你喜欢

转载自blog.csdn.net/denghonghao/article/details/80771308