首页 Java Java利用JSch实现sftp通过ssh上传下载删除文件及配置代码

Java利用JSch实现sftp通过ssh上传下载删除文件及配置代码

1、JSch的引用

1)项目中导入jsch-0.1.53.jar包

下载地址https://sourceforge.net/projects/jsch/files/jsch/0.1.53/jsch-0.1.53.zip/download

2)Maven中引用的pom.xml配置

<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>

2、JSch连接配置代码

public >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;
    }


}
public static void getConnect(SFTP s) throws Exception {
                /** 密钥的密码  */ 
//      String privateKey ="key";
//        /** 密钥文件路径  */ 
//      String passphrase ="path";
        /** 主机 */ 
        String host ="127.0.0.1"; 
        /** 端口 */ 
        int port =22; 
        /** 用户名 */ 
        String username ="test";
        /** 密码 */ 
        String password ="test";
        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();   
        }
        channel = session.openChannel("sftp");   
        try {
            channel.connect();   
        } catch (Exception e) {   
            if (channel.isConnected())   
                channel.disconnect();   
        }
        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;
        }
    }

3、使用JSch上传下载删除文件代码

1)上传文件代码

/**
     * 上传文件
     * @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);
        }
    }

2)下载文件代码

/**
     * 下载文件
     * @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);
        }
    }

3)删除文件代码

/**
     * 删除文件
     * @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);
        }
    }
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。