java操做jsch的工具类记录一下

public class SFTPUtil {
     private static final Logger log = LoggerFactory.getLogger(SFTPUtil.class);
    /**
     * 连接ftp/sftp服务器
     * @param SFTP类
     */
    public static void getConnect(SFTP s) throws Exception {

                /** 密钥的密码  */ 
//      String privateKey ="key";
//        /** 密钥文件路径  */ 
//      String passphrase ="path";
        /** 主机 */ 
        String host ="192.168.1.105"; 
        /** 端口 */ 
        int port =22; 
        /** 用户名 */ 
        String username ="root";
        /** 密码 */ 
        String password ="yf_05191006";

        Session session = null;   
        Channel channel = null;   
        ChannelSftp sftp = null;// sftp操作类  

        JSch jsch = new JSch();   


        //设置密钥和密码  
        //支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了  
//      if (privateKey != null && !"".equals(privateKey)) {  
//             if (passphrase != null && "".equals(passphrase)) {  
//              //设置带口令的密钥  
//                 jsch.addIdentity(privateKey, passphrase);  
//             } else {  
//              //设置不带口令的密钥  
//                 jsch.addIdentity(privateKey);  
//             }  
//      }  
        session = jsch.getSession(username, host, port);   
        session.setPassword(password);   
        Properties config = new Properties();   
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey    
        session.setConfig(config);   
        try {
            session.connect();   
        } catch (Exception e) {
            if (session.isConnected())   
                session.disconnect();   
            log.error("连接服务器失败,请检查主机[" + host + "],端口[" + port   
                    + "],用户名[" + username + "],端口[" + port   
                    + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");   
        }
        channel = session.openChannel("sftp");   
        try {
            channel.connect();   
        } catch (Exception e) {   
            if (channel.isConnected())   
                channel.disconnect();   
            log.error("连接服务器失败,请检查主机[" + host + "],端口[" + port   
                    + "],用户名[" + username + "],密码是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");   
        }
        sftp = (ChannelSftp) channel;   

        s.setChannel(channel);
        s.setSession(session);
        s.setSftp(sftp);

    }
    /**
     * 断开连接
     * 
     */
    public static void disConn(Session session,Channel channel,ChannelSftp sftp)throws Exception{
        if(null != sftp){
            sftp.disconnect();
            sftp.exit();
            sftp = null;
        }
        if(null != channel){
            channel.disconnect();
            channel = null;
        }
        if(null != session){
            session.disconnect();
            session = null;
        }
    }
    /**
     * 上传文件
     * @param directory 上传的目录-相对于SFPT设置的用户访问目录,
     * 为空则在SFTP设置的根目录进行创建文件(除设置了服务器全磁盘访问)
     * @param uploadFile 要上传的文件全路径
     */
    public static void upload(String directory,String uploadFile) throws Exception {

        SFTP s=new SFTP();
        getConnect(s);//建立连接
        Session session = s.getSession();   
        Channel channel = s.getChannel();   
        ChannelSftp sftp = s.getSftp();// sftp操作类  
        try {
            try{
                 sftp.cd(directory); //进入目录
            }catch(SftpException sException){
                 if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){ //指定上传路径不存在
                     sftp.mkdir(directory);//创建目录
                     sftp.cd(directory);  //进入目录
                 }
            }


            
            File file = new File(uploadFile);
            InputStream in= new FileInputStream(file);
            sftp.put(in, file.getName());
            in.close();

        } catch (Exception e) {
            throw new Exception(e.getMessage(),e); 
        } finally {
            disConn(session,channel,sftp);
        }
    }
/**
 * 下载文件
 * @param directory 下载目录 根据SFTP设置的根目录来进行传入
 * @param downloadFile  下载的文件 
 * @param saveFile  存在本地的路径 
 */
public static void download(String directory, String downloadFile,String saveFile) throws Exception {
    SFTP s=new SFTP();
    getConnect(s);//建立连接
    Session session = s.getSession();   
    Channel channel = s.getChannel();   
    ChannelSftp sftp = s.getSftp();// sftp操作类  
    try {

        sftp.cd(directory); //进入目录
        File file = new File(saveFile);
        boolean bFile;
        bFile = false;
        bFile = file.exists();
        if (!bFile) {
            bFile = file.mkdirs();//创建目录
        }
        OutputStream out=new FileOutputStream(new File(saveFile,downloadFile));

        sftp.get(downloadFile, out);

        out.flush();
        out.close();

    } catch (Exception e) {
        throw new Exception(e.getMessage(),e); 
    } finally {
        disConn(session,channel,sftp);
    }
}
/**
 * 删除文件
 * @param directory 要删除文件所在目录 
 * @param deleteFile 要删除的文件
 */
public static void delete(String directory, String deleteFile) throws Exception {
    SFTP s=new SFTP();
    getConnect(s);//建立连接
    Session session = s.getSession();   
    Channel channel = s.getChannel();   
    ChannelSftp sftp = s.getSftp();// sftp操作类  
    try {
        sftp.cd(directory); //进入的目录应该是要删除的目录的上一级
        sftp.rm(deleteFile);//删除目录
    } catch (Exception e) {
        throw new Exception(e.getMessage(),e); 
    } finally {
        disConn(session,channel,sftp);
    }
}
/** 
 * 列出目录下的文件 
 * @param directory  要列出的目录            
 * @return list 文件名列表 
 * @throws Exception 
 */ 
 public static List<String> listFiles(String directory) throws Exception { 
     SFTP s=new SFTP();
     getConnect(s);//建立连接
     Session session = s.getSession();   
     Channel channel = s.getChannel();   
     ChannelSftp sftp = s.getSftp();// sftp操作类  
     Vector fileList=null; 
     List<String> fileNameList = new ArrayList<String>(); 
     fileList = sftp.ls(directory); //返回目录下所有文件名称
     disConn(session,channel,sftp);

     Iterator it = fileList.iterator(); 

     while(it.hasNext()) { 

         String fileName = ((LsEntry)it.next()).getFilename(); 
         if(".".equals(fileName) || "..".equals(fileName)){ 
             continue; 
          } 
         fileNameList.add(fileName); 

     } 

     return fileNameList; 
 }
 /**
  * 删除目录下所有文件
  * @param directory 要删除文件所在目录 
  */
 public static void deleteAllFile(String directory) throws Exception{
     SFTP s=new SFTP();
     getConnect(s);//建立连接
     Session session = s.getSession();   
     Channel channel = s.getChannel();   
     ChannelSftp sftp = s.getSftp();// sftp操作类     
     try {
         List <String> files=listFiles(directory);//返回目录下所有文件名称
         sftp.cd(directory); //进入目录

         for (String deleteFile : files) {
             sftp.rm(deleteFile);//循环一次删除目录下的文件
         }
     } catch (Exception e) {
         throw new Exception(e.getMessage(),e); 
     } finally {
         disConn(session,channel,sftp);
     }

 }
 /**
  * 删除目录 (删除的目录必须为空)
  * @param deleteDir 要删除的目录 
  */
 public static void deleteDir(String deleteDir) throws Exception {
     SFTP s=new SFTP();
     getConnect(s);//建立连接
     Session session = s.getSession();   
     Channel channel = s.getChannel();   
     ChannelSftp sftp = s.getSftp();// sftp操作类   
     try {

         sftp.rmdir(deleteDir);

     } catch (Exception e) {
         throw new Exception(e.getMessage(),e); 
     } finally {
         disConn(session,channel,sftp);
     }
 }
 /**
  * 创建目录 
  * @param directory 要创建的目录 位置
  * @param dir 要创建的目录 
  */
    public static void creatDir(String directory,String dir) throws Exception {
        SFTP s=new SFTP();
        getConnect(s);//建立连接
        Session session = s.getSession();   
        Channel channel = s.getChannel();   
        ChannelSftp sftp = s.getSftp();// sftp操作类  
        try {
            sftp.cd(directory); 
            sftp.mkdir(dir);
        } catch (Exception e) {
            throw new Exception(e.getMessage(),e); 
        } finally {
            disConn(session,channel,sftp);
        }
   }
    /** 
     * 更改文件名 
     * @param directory  文件所在目录 
     * @param oldFileNm  原文件名 
     * @param newFileNm 新文件名       
     * @throws Exception      
     */ 
     public static void rename(String directory, String oldFileNm, String newFileNm) throws Exception { 
         SFTP s=new SFTP();
         getConnect(s);//建立连接
         Session session = s.getSession();   
         Channel channel = s.getChannel();   
         ChannelSftp sftp = s.getSftp();// sftp操作类    
         try {
             sftp.cd(directory); 
             sftp.rename(oldFileNm, newFileNm); 
         } catch (Exception e) {
             throw new Exception(e.getMessage(),e); 
         } finally {
             disConn(session,channel,sftp);
         }
     } 
     /**
      * 进入目录
      * @param directory
      * @throws Exception
      */
     public static void cd(String directory)throws Exception { 

         SFTP s=new SFTP();
         getConnect(s);//建立连接
         Session session = s.getSession();   
         Channel channel = s.getChannel();   
         ChannelSftp sftp = s.getSftp();// sftp操作类   
         try {
             sftp.cd(directory); //目录要一级一级进
         } catch (Exception e) {
             throw new Exception(e.getMessage(),e); 
         } finally {
             disConn(session,channel,sftp);
         }
     } 
}

 

package myjschtest;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;

public class SFTP{

    private Session session;//会话 
    private Channel channel;//连接通道   
    private ChannelSftp sftp;// sftp操作类   


    public Session getSession() {
        return session;
    }
    public void setSession(Session session) {
        this.session = session;
    }
    public Channel getChannel() {
        return channel;
    }
    public void setChannel(Channel channel) {
        this.channel = channel;
    }
    public ChannelSftp getSftp() {
        return sftp;
    }
    public void setSftp(ChannelSftp sftp) {
        this.sftp = sftp;
    }


}

 

下面的是单例的并发量不好

package com.personal.core.utils;

import com.jcraft.jsch.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
/**
 * 注释
 *
 * @Author: coding99
 * @Date: 16-9-2
 * @Time: 下午7:33
 */
public class JschUtil {
 
    private static final Logger logger = LoggerFactory.getLogger(JschUtil.class);
 
    private String charset = "UTF-8"; // 设置编码格式,可以根据服务器的编码设置相应的编码格式
    private JSch jsch;
    private Session session;
    Channel channel = null;
    ChannelSftp chSftp = null;
 
 
    //初始化配置参数
    private String jschHost = "192.168.1.105";
    private int jschPort = 22;
    private String jschUserName = "root";
    private String jschPassWord ="yf_05191006";
    private int jschTimeOut = 3000006;
 
 
 
    /**
     * 静态内部类实现单例模式
     */
    private static class LazyHolder {
        private static final JschUtil INSTANCE = new JschUtil();
    }
 
    private JschUtil() {
 
    }
 
    /**
     * 获取实例
     * @return
     */
    public static final JschUtil getInstance() {
        return LazyHolder.INSTANCE;
    }
 
 
    /**
     * 连接到指定的服务器
     * @return
     * @throws JSchException
     */
    public boolean connect() throws JSchException {
 
        jsch = new JSch();// 创建JSch对象
 
        boolean result = false;
 
        try{
 
            long begin = System.currentTimeMillis();//连接前时间
            logger.debug("Try to connect to jschHost = " + jschHost + ",as jschUserName = " + jschUserName + ",as jschPort =  " + jschPort);
 
            session = jsch.getSession(jschUserName, jschHost, jschPort);// // 根据用户名,主机ip,端口获取一个Session对象
            session.setPassword(jschPassWord); // 设置密码
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);// 为Session对象设置properties
            session.setTimeout(jschTimeOut);//设置连接超时时间
            session.connect();
 
            logger.debug("Connected successfully to jschHost = " + jschHost + ",as jschUserName = " + jschUserName + ",as jschPort =  " + jschPort);
 
            long end = System.currentTimeMillis();//连接后时间
 
            logger.debug("Connected To SA Successful in {} ms", (end-begin));
 
            result = session.isConnected();
 
        }catch(Exception e){
            logger.error(e.getMessage(), e);
        }finally{
            if(result){
                logger.debug("connect success");
            }else{
                logger.debug("connect failure");
            }
        }
 
        if(!session.isConnected()) {
            logger.error("获取连接失败");
        }
 
        return  session.isConnected();
 
    }
 
    /**
     * 关闭连接
     */
    public void close() {
 
        if(channel != null && channel.isConnected()){
            channel.disconnect();
            channel=null;
        }
 
        if(session!=null && session.isConnected()){
            session.disconnect();
            session=null;
        }
 
    }
 
    /**
     * 脚本是同步执行的方式
     * 执行脚本命令
     * @param command
     * @return
     */
    public Map<String,Object> execCmmmand(String command) throws Exception{
 
 
        Map<String,Object> mapResult = new HashMap<String,Object>();
 
        logger.debug(command);
 
        StringBuffer result = new StringBuffer();//脚本返回结果
 
        BufferedReader reader = null;
        int returnCode = -2;//脚本执行退出状态码
 
 
        try {
 
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);
 
            channel.connect();//执行命令 等待执行结束
 
            InputStream in = channel.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
 
            String res="";
            while((res=reader.readLine()) != null){
                result.append(res+"\n");
                logger.debug(res);
            }
 
            returnCode = channel.getExitStatus();
 
            mapResult.put("returnCode",returnCode);
            mapResult.put("result",result.toString());
 
        } catch (IOException e) {
 
            logger.error(e.getMessage(),e);
 
        } catch (JSchException e) {
 
            logger.error(e.getMessage(), e);
 
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
 
        return mapResult;
 
    }
 
    /**
     * 上传文件
     *
     * @param directory 上传的目录,有两种写法
     *                  1、如/opt,拿到则是默认文件名
     *                  2、/opt/文件名,则是另起一个名字
     * @param uploadFile 要上传的文件 如/opt/xxx.txt
     */
    public void upload(String directory, String uploadFile) {
 
        try {
 
            logger.debug("Opening Channel.");
            channel = session.openChannel("sftp"); // 打开SFTP通道
            channel.connect(); // 建立SFTP通道的连接
            chSftp = (ChannelSftp) channel;
            File file = new File(uploadFile);
            long fileSize = file.length();
 
            /*方法一*/
             OutputStream out = chSftp.put(directory, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式
             byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KB
             int read;
             if (out != null) {
                 logger.debug("Start to read input stream");
                InputStream is = new FileInputStream(uploadFile);
                do {
                    read = is.read(buff, 0, buff.length);
                     if (read > 0) {
                            out.write(buff, 0, read);
                     }
                     out.flush();
                 } while (read >= 0);
                 logger.debug("input stream read done.");
             }
 
            // chSftp.put(uploadFile, directory, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); //方法二
            // chSftp.put(new FileInputStream(src), dst, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); //方法三
            logger.debug("成功上传文件至"+directory);
 
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            chSftp.quit();
 
            if (channel != null) {
                channel.disconnect();
                logger.debug("channel disconnect");
            }
 
        }
    }
 
 
    /**
     * 下载文件
     *
     * @param directory 下载的目录,有两种写法
     *                  1、如/opt,拿到则是默认文件名
     *                  2、/opt/文件名,则是另起一个名字
     * @param downloadFile 要下载的文件 如/opt/xxx.txt
     *
     */
 
    public void download(String directory, String downloadFile) {
        try {
 
            logger.debug("Opening Channel.");
            channel = session.openChannel("sftp"); // 打开SFTP通道
            channel.connect(); // 建立SFTP通道的连接
            chSftp = (ChannelSftp) channel;
            SftpATTRS attr = chSftp.stat(downloadFile);
            long fileSize = attr.getSize();
 
 
            OutputStream out = new FileOutputStream(directory);
 
            InputStream is = chSftp.get(downloadFile, new MyProgressMonitor());
            byte[] buff = new byte[1024 * 2];
            int read;
            if (is != null) {
                logger.debug("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);
                logger.debug("input stream read done.");
            }
 
            //chSftp.get(downloadFile, directory, new FileProgressMonitor(fileSize)); // 代码段1
            //chSftp.get(downloadFile, out, new FileProgressMonitor(fileSize)); // 代码段2
 
            logger.debug("成功下载文件至"+directory);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            chSftp.quit();
            if (channel != null) {
                channel.disconnect();
                logger.debug("channel disconnect");
            }
        }
    }
 
 
    /**
     * 删除文件
     * @param deleteFile 要删除的文件
     */
    public void delete(String deleteFile) {
 
        try {
            connect();//建立服务器连接
            logger.debug("Opening Channel.");
            channel = session.openChannel("sftp"); // 打开SFTP通道
            channel.connect(); // 建立SFTP通道的连接
            chSftp = (ChannelSftp) channel;
            chSftp.rm(deleteFile);
            logger.debug("成功删除文件"+deleteFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
 
    public String getCharset() {
        return charset;
    }
 
    public void setCharset(String charset) {
        this.charset = charset;
    }
 
 
 
    public static void main(String[] args) throws Exception{
 
        JschUtil jschUtil = JschUtil.getInstance();
 
        boolean isConnected = false;
        isConnected  = jschUtil.connect();
 
        if(isConnected == true){
 
 
            /*上传文件*/
            jschUtil.upload("/opt/123456.png","/home/sky/Desktop/resizeApi.png");
 
             /*执行命令*/
            String command = "ls -ltr /opt";
           // String command = ShellConfigUtil.getShell("ls");
            Map<String,Object> result = jschUtil.execCmmmand(command);
            System.out.println(result.get("result").toString());
 
            /*下载文件*/
            jschUtil.download("/opt/123456.png","/opt/123456.png");
 
            jschUtil.close();
 
        }
 
 
    }

}
 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值