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; /** * 讀取服務(wù)器文件內(nèi)容 * * @author ** * @date 2022-**-** */ public class PythonFileUtil { private Logger log = LoggerFactory.getLogger(getClass()); private static Session session; /** * 方法描述: 連接到服務(wù)器 * */ public static void connect(String ipUrl, int pythonPort, String username, String password) throws JSchException { // 創(chuàng)建JSch對象 JSch jsch = new JSch(); // 根據(jù)用戶名,主機ip,端口獲取一個Session對象 session = jsch.getSession(username, ipUrl, pythonPort); // 設(shè)置密碼 session.setPassword(password); // 設(shè)置timeout時間 session.setTimeout(20000); // 為Session對象設(shè)置properties Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 通過Session建立鏈接 session.connect(); } /** * 讀取Linux服務(wù)器某路徑下文件 * * @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("連接遠程服務(wù)異常"); } // 打開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()); // 關(guān)閉通道 JschUtil.close(channelSftp); JschUtil.close(session); } catch (Exception e) { e.printStackTrace(); log.info(e.getMessage()); throw new BaseException("目錄/文件不存在"); }
//得到的結(jié)果轉(zhuǎn)換‘換行\(zhòng)n’,‘縮進\t’字符,返回到頁面展示 return fileInfo.replaceAll("\t"," ").replaceAll("(\\n\\r|\\n|\\r\\n)","<br/>"); }
}
浙公網(wǎng)安備 33010602011771號