Java使用Sftp实现对跨服务器上传、下载、打包、写入相关操作

Wesley13
• 阅读 566

1、Maven引入jar

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

2、Test类

package com.tandaima.pub;


import java.io.*;
import java.util.Properties;

import com.jcraft.jsch.*;


/**
 * User  longpizi
 * Date: 2019/10/30
 * Time: 14:40
 */
public class SftpUtil {
    public static final String CHANNELTYPE_SFTP="sftp";
    public static final String CHANNELTYPE_EXEC="exec";
    private Session session;//会话
    private Channel channel;//连接通道
    private ChannelSftp sftp;// sftp操作类
    private JSch jsch;
    protected static String host=getLinuxParam()[0];
    protected static String port=getLinuxParam()[1];
    protected static String user=getLinuxParam()[2];
    protected static String password=getLinuxParam()[3];

    private static String[] getLinuxParam(){
        Properties props=new Properties();//读取文件类型创建对象。
        try {
            ClassLoader classLoader = SftpUtil.class.getClassLoader();// 读取属性文件
            InputStream in = classLoader.getResourceAsStream("linux.properties");
            props.load(in); /// 加载属性列表
            if(in!=null){
                in.close();
            }
        } catch (Exception e) {
            System.out.println("Linux连接参数异常:"+e.getMessage());
        }
        String[] str={"","","",""};
        str[0]=props.getProperty("file.host");
        str[1]=props.getProperty("file.port");
        str[2]=props.getProperty("file.user");
        str[3]=props.getProperty("file.password");
        return str;
    }
    /**
     * 断开连接
     */
    public static void closeConnect(Session session, Channel channel, ChannelSftp sftp){
        if (null != sftp) {
            sftp.disconnect();
            sftp.exit();
            sftp = null;
        }
        if (null != channel) {
            channel.disconnect();
            channel = null;
        }
        if (null != session) {
            session.disconnect();
            session = null;
        }
        System.out.println("连接已关闭");
    }

    /**
     * 连接ftp/sftp服务器
     *
     * @param sftpUtil 类
     */
    public static void getConnect(SftpUtil sftpUtil,String openChannelType) throws Exception {
        Session session = null;
        Channel channel = null;

        JSch jsch = new JSch();
        session = jsch.getSession(user, host, Integer.parseInt(port));
        session.setPassword(password);
        // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
        // 不验证 HostKey
        session.setConfig("StrictHostKeyChecking", "no");
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected())
                session.disconnect();
            System.out.println("连接服务器失败");
        }
        channel = session.openChannel(openChannelType);
        try {
            channel.connect();
        } catch (Exception e) {
            if (channel.isConnected())
                channel.disconnect();
            System.out.println("连接服务器失败");
        }
        sftpUtil.setJsch(jsch);
        if(openChannelType.equals(CHANNELTYPE_SFTP)){
            sftpUtil.setSftp((ChannelSftp) channel);
        }
        sftpUtil.setChannel(channel);
        sftpUtil.setSession(session);

    }


    /**
     * 上传文件
     *
     * @param directory  上传的目录-相对于SFPT设置的用户访问目录
     * @param uploadFile 要上传的文件全路径
     */
    public static boolean upload(String directory, String uploadFile) {
        boolean resultState=false;
        SftpUtil sftpUtil = new SftpUtil();
        try{
            getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
            Session session = sftpUtil.getSession();
            Channel channel = sftpUtil.getChannel();
            ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类
            try {
                sftp.cd(directory); //进入目录
            } catch (SftpException sException) {
                if (ChannelSftp.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();
            closeConnect(session, channel, sftp);
            resultState=true;
        }catch (Exception e){
            System.out.println("上传文件异常");
        }
        return resultState;
    }

    /**
     * 获取已连接的Sftp
     * @return SftpUtil
     */
    public static SftpUtil getConnectSftp(){
        SftpUtil sftpUtil=new SftpUtil();
        try {
            getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
          return sftpUtil;
        }catch (Exception e){
            System.out.println("下载文件异常");
        }
        return null;
    }

    /**
     * 删除文件
     * @param directory 要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public static boolean delete(String directory, String deleteFile){
        boolean resultState=false;
        SftpUtil sftpUtil=new SftpUtil();
        try {
            getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
            Session session = sftpUtil.getSession();
            Channel channel = sftpUtil.getChannel();
            ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类
            sftp.cd(directory); //进入的目录应该是要删除的目录的上一级
            sftp.rm(deleteFile);//删除目录
            closeConnect(session,channel,sftp);
            resultState=true;
        }catch (Exception e){
            System.out.println("删除文件异常");
        }
        return resultState;
    }

    /**
     JSch有三种文件传输模式:
     (1)OVERWRITE:完全覆盖模式。JSch的默认文件传输模式,传输的文件将覆盖目标文件。
     (2)APPEND:追加模式。如果目标文件已存在,则在目标文件后追加。
     (3)RESUME:恢复模式。如果文件正在传输时,由于网络等原因导致传输中断,则下一次传输相同的文件
     时,会从上一次中断的地方续传。
     */
    /**
     * 追加文件内容
     * @param remoteFile 原文件路径
     * @param in 追加内容
     * @return true成功,false失败
     */
    public static boolean appendFileContent(String remoteFile, InputStream in){
        boolean resultState=false;
        SftpUtil sftpUtil = new SftpUtil();
        try{
            getConnect(sftpUtil,CHANNELTYPE_SFTP);//建立连接
            Session session = sftpUtil.getSession();
            Channel channel = sftpUtil.getChannel();
            ChannelSftp sftp = sftpUtil.getSftp();// sftp操作类
            OutputStream out = sftp.put(remoteFile, ChannelSftp.APPEND);
            int bufferSize=1024;
            byte[] buff = new byte[bufferSize]; // 设定每次传输的数据块大小
            int read;
            if (out != null) {
                do {
                    read = in.read(buff, 0, buff.length);
                    if (read > 0) {
                        out.write(buff, 0, read);
                    }
                    out.flush();
                } while (read >= 0);
            }
            if(out!=null){
                out.close();
            }
            closeConnect(session, channel, sftp);
            resultState=true;
        }catch (Exception e){
            System.out.println("写入文件异常");
        }
        return resultState;
    }

    /**
     * 创建文件
     * @param fileDir 文件路径
     * @param fileName 文件名称
     * @return
     */
    public static boolean createFile(String fileDir,String fileName){
        try{
            execute("mkdir -p "+fileDir+"\n" +
                    "touch "+fileDir+"/"+fileName);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 创建文件夹
     * @param fileDir 文件路径
     * @return true成功/false失败
     */
    public static boolean createFileDir(String fileDir){
        try{
            execute("mkdir -p "+fileDir+"");
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 压缩文件夹为ZIP
     * @param fileDir 文件路径
     * @param fileName 文件名称
     * @param additionalName 压缩附加名
     * @return
     */
    public static boolean zipDir(String fileDir,String fileName,String additionalName){
        try{
            execute("cd "+fileDir+"\n" +
                    "zip  -r "+fileDir+"/"+fileName+additionalName+".zip "+fileName);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 获取文件大小 单位(K)
     * @param fileDir 文件路径
     * @return 文件大小
     */
    public static long getFileSize(String fileDir){
        return Long.parseLong(execute("ls -l "+fileDir+" | awk '{ print $5 }'"));
    }
    /**
     * 执行liunx 命令
     * @param command 命令内容
     * @return 命令输出
     */
    private static String execute(String command){
        SftpUtil sftpUtil=new SftpUtil();
        StringBuffer strBuffer=new StringBuffer();
        try {
            getConnect(sftpUtil,CHANNELTYPE_EXEC);
            // Create and connect session.
            Session session = sftpUtil.getSession();

            // Create and connect channel.
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader(channel
                    .getInputStream()));

            channel.connect();
            System.out.println("命令: " + command);
            // 获取命令的输出
            String line;
            while ((line = input.readLine()) != null) {
                strBuffer.append(line);
            }
            input.close();
            closeConnect(session,channel,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strBuffer.toString();
    }
//    public static void main(String[] args) throws FileNotFoundException {
//        String window_dir="C:\\Users\XXX\\Desktop\\test\\test.txt";
//        String liunx_dir="/usr/local/longpizi";
//        try {
////            System.out.println(upload(liunx_dir,window_dir));
////            System.out.println(download(liunx_dir,"test.txt","C:\\Users\\XXX\\Desktop\\test"));
////            System.out.println(delete(liunx_dir,"test.txt"));
//
////            InputStream inputStream = new ByteArrayInputStream("this is test".getBytes());
////            System.out.println(appendFileContent(liunx_dir+"/test.txt",inputStream));
//
////            String command="touch /usr/local/longlin/longpizi.sh\nmkdir -p sss";
////            System.out.println(execute(command));
//
////            System.out.println(createFile("/usr/local/longlin/test/sfdsfdf","sss.txt"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public JSch getJsch() {
        return jsch;
    }

    public  void setJsch(JSch jsch) {
        this.jsch = jsch;
    }

    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;
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
2年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这