java远程读取linux文件

  • java程序远程linux服务器有两个框架分别是:jsch与ganymed-ssh2框架。
  • 目前ganymed-ssh框架不维护了,同时不支持openssl的版本
  • 下篇更新jsch的文章

一、导入相关依赖包

       ch.ethz.ganymed       ganymed-ssh2       262  

二、实现相关的工具类

/** * 远程获取execl文件的工具类 */@Componentpublic class ScpClientUtil {   //日志记录工具private static final Logger logger = LoggerFactory.getLogger(ScpClientUtil.class);//远程ipprivate static String ip; //远程用户名private static String userName;//远程密码private static String password;//连接的端口private static int port;  //设置编码格式private static String  charset;@Value("${auth.ip}")public void setIp(String ip) {this.ip = ip;}@Value("${auth.userName}")public void setUserName(String userName) {this.userName = userName;}@Value("${auth.password}")public void setPassword(String password) {this.password = password;}@Value("${auth.port}")public void setPort(String port) {this.port = Integer.valueOf(port);}@Value("${file.charset}")public void setEncoding(String charset) {this.charset=charset;}/** 获取连接 */public static Connection getConnect(String hostName, String username, String password, int port) {Connection conn = new Connection(hostName, port);try {// 连接到主机conn.connect();// 使用用户名和密码校验boolean isconn = conn.authenticateWithPassword(username, password);if (!isconn) {conn=null;logger.info("用户名称或者是密码不正确");} else {logger.info("服务器连接成功.");return conn;}} catch (Exception e) {conn=null;e.printStackTrace(); }return conn;}/** * 读取文件内容 */public static void getFileContent(Connection conn, String remotePath){BufferedReader bufferedReader=null;try {SFTPv3Client sft = new SFTPv3Client(conn);// 设置编码格式,可以获取到中文文件sft.setCharset("GBk");List list = sft.ls(remotePath);SCPClient scpClient = conn.createSCPClient();scpClient.setCharset("GBK");String line;for (int i = 0; i < list.size(); i++) {String mkdir=list.get(i).filename;//不允许访问根目录if(!mkdir.startsWith(".")){List mkdirFiles = sft.ls(remotePath+mkdir+"/");for(int k=0;k

创建服务连接

获取到连接

执行相关的业务代码

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

相关文章

推荐文章