专业的JAVA编程教程与资源

网站首页 > java教程 正文

java远程读取linux文件

temp10 2024-11-19 11:25:45 java教程 13 ℃ 0 评论
  • java程序远程linux服务器有两个框架分别是:jsch与ganymed-ssh2框架。
  • 目前ganymed-ssh框架不维护了,同时不支持openssl的版本
  • 下篇更新jsch的文章

一、导入相关依赖包

<dependency>
       <groupId>ch.ethz.ganymed</groupId>
       <artifactId>ganymed-ssh2</artifactId>
       <version>262</version>
  </dependency>

二、实现相关的工具类

java远程读取linux文件

/**
 * 远程获取execl文件的工具类
 */
@Component
public class ScpClientUtil {
	   //日志记录工具
		private static final Logger logger = LoggerFactory.getLogger(ScpClientUtil.class);
		//远程ip
		private 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<SFTPv3DirectoryEntry> 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<SFTPv3DirectoryEntry> mkdirFiles = sft.ls(remotePath+mkdir+"/");
						for(int k=0;k<mkdirFiles.size();k++){
							//获取相关的文件名
							String fileName=mkdirFiles.get(i).filename;
							String localPath="---要读取的路径---"+fileName;
							SCPInputStream in = scpClient.get(localPath.replace("\\", "//"));
							bufferedReader = new BufferedReader(new InputStreamReader(in,ScpClientUtil.charset));
							while((line=bufferedReader.readLine())!=null) {
                //---------------------
                //要执行的业务代码块
                //---------------------
								System.out.println(line);
							}
						}
					}
				}
			}catch (Exception e) {
				e.printStackTrace();
			}finally {
				if(bufferedReader!=null) {
					try {
						bufferedReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

		}

		/***创建连接服务器*/
		public static Connection createConection() {
			//不同平台存放数据
			Connection conn = getConnect(ip, userName, password, port); 
			logger.info(ip);
			logger.info(userName);
			logger.info(password);
			logger.info(String.valueOf(port));
			return conn;
		}
}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表