jsch远程读取linux系统上的文件

  • java程序远程linux服务器有两个框架分别是:jsch与ganymed-ssh2框架。
  • 推荐使用jsch框架因为ganymed-ssh2框架不支持麒麟服务器的连接原因是openssl版本过高,ganymed-ssh框架不维护了所以不支持。

一、导入相关依赖

    com.jcraft    jsch    0.1.54

二、封装远程登录服务器的工具类

@Componentpublic class SftpUtils {    private Logger logger = LoggerFactory.getLogger(SftpUtils.class);    //远程ip    private static String ip;    //远程用户名    private static String userName;    //远程密码    private static String password;    //连接的端口    private static int port;    @Value("${remote.dfIp}")    public void setIp(String ip) {        SftpUtils.ip = ip;    }    @Value("${remote.dfUserName}")    public void setUserName(String userName) {        SftpUtils.userName = userName;    }    @Value("${remote.dfPassword}")    public void setPassword(String password) {        SftpUtils.password = password;    }    @Value("${remote.dfPort}")    public void setPort(String port) {        SftpUtils.port = Integer.valueOf(port);    }      public ChannelSftp connectSftp(Session sshSession) {        ChannelSftp sftp ;        try {            Channel channel = sshSession.openChannel("sftp");            channel.connect();            sftp = (ChannelSftp) channel;        } catch (Exception e) {            e.printStackTrace();            sftp = null;        }        return sftp;    }/***获取会话*/    public Session getSession() {        Session sshSession = null;        try {            JSch jsch = new JSch();            jsch.getSession(userName,ip , port);            sshSession = jsch.getSession(userName, ip, port);            System.out.println("Session created.");            sshSession.setPassword(password);            Properties sshConfig = new Properties();            sshConfig.put("StrictHostKeyChecking", "no");            sshSession.setConfig(sshConfig);            sshSession.connect();            System.out.println("Session connected.");            System.out.println("Opening Channel.");        } catch (Exception e) {            e.printStackTrace();        }        return sshSession;    }    /***  关闭连接*/    public static void closeConnect(Session session, ChannelSftp sftp) {        try {            sftp.getSession().disconnect();            session.disconnect();            sftp.quit();        } catch (JSchException e) {            e.printStackTrace();        }    }}

构建连接,获取会话

关闭连接

三、实现获取文件内容

import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.Session;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import org.springframework.util.StringUtils;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.lang.reflect.Field;import java.util.Vector;@Slf4j@Componentpublic class StpClientUtil {    /**设置文件的编码格式*/    @Value("${fileEncoding}")    private String fileEncoding;    /***注入创建的连接工具类*/    @Autowired    private SftpUtils sf;    /**获取文件内容*/    public String getContent(String remotePath, String inputFileName) {        Session session = sf.getSession();        ChannelSftp sftp = sf.connectSftp(session);        InputStream in;        try {            Class<?> cl = ChannelSftp.class;            //反射修改server_version的默认值,解决设置编码版本不兼容问题            Field f = cl.getDeclaredField("server_version");            f.setAccessible(true);            f.set(sftp, 2);            //GBK            sftp.setFilenameEncoding(fileEncoding);            //进入源目录            sftp.cd("/");            //获取该目录下匹配的文件            Vector vector = sftp.ls(remotePath);            for (ChannelSftp.LsEntry lsEntry : vector) {                String fileName = lsEntry.getFilename();                // 解决文件名乱码读取不到的问题                sftp.cd(remotePath);                in = sftp.get(fileName);                //获取缓存字符流                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));            String line;                while ((line = bufferedReader.readLine()) != null) {                    //-------------------                  //获取文件内容,逻辑操作                  //--------------------                    System.out.println(line);                }                bufferedReader.close();            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (!StringUtils.isEmpty(sftp)) {                sftp.disconnect();                sf.closeConnect(session, sftp);            }        }        return "";    }}

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章