package com.aa.dataadmin.common.utils; import cn.hutool.extra.ssh.JschUtil; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.xy.common.exception.base.BaseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Properties; /** * 读取服务器文件内容 * * @author ** * @date 2022-**-** */ public class PythonFileUtil { private Logger log = LoggerFactory.getLogger(getClass()); private static Session session; /** * 方法描述: 连接到服务器 * */ public static void connect(String ipUrl, int pythonPort, String username, String password) throws JSchException { // 创建JSch对象 JSch jsch = new JSch(); // 根据用户名,主机ip,端口获取一个Session对象 session = jsch.getSession(username, ipUrl, pythonPort); // 设置密码 session.setPassword(password); // 设置timeout时间 session.setTimeout(20000); // 为Session对象设置properties Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 通过Session建立链接 session.connect(); } /** * 读取Linux服务器某路径下文件 * * @param ipUrl ip地址 * @param username 用户名 * @param password 密码 * @param path 文件路径 * @param fileName 文件名(带后缀) * @return * @throws IOException */ public String messageToPythonFile(String ipUrl, int pythonPort, String username, String password, String path, String fileName) throws Exception { try { connect(pythonUrl, pythonPort, username, password); } catch (JSchException e) { e.printStackTrace(); log.info(e.getMessage()); throw new BaseException("连接远程服务异常"); } // 打开SFTP通道 ChannelSftp channelSftp = null; String fileInfo = ""; try { channelSftp = (ChannelSftp) session.openChannel("sftp"); // 建立SFTP通道的连接 channelSftp.connect(); } catch (Exception e) { e.printStackTrace(); log.info(e.getMessage()); throw new BaseException("建立远程通道链接异常"); } try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); channelSftp.get(physicsUrl + "/" + fileName, outputStream); fileInfo = new String(outputStream.toByteArray()); // 关闭通道 JschUtil.close(channelSftp); JschUtil.close(session); } catch (Exception e) { e.printStackTrace(); log.info(e.getMessage()); throw new BaseException("目录/文件不存在"); }
    //得到的结果转换‘换行\n’,‘缩进\t’字符,返回到页面展示 return fileInfo.replaceAll("\t","&nbsp;").replaceAll("(\\n\\r|\\n|\\r\\n)","<br/>"); }
}

  

 

posted on 2022-11-16 16:33  茫无所知  阅读(74)  评论(0编辑  收藏  举报