您的位置:首页 > 编程语言 > Java开发

JAVA SSH 实时获取服务器日志信息

2019-02-26 17:39 78 查看

本人使用场景:获取服务器上的日志信息 并分析出有用数据

第一步,

首先加入依赖:

     <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
          <dependency>
              <groupId>ch.ethz.ganymed</groupId>
              <artifactId>ganymed-ssh2</artifactId>
              <version>262</version>
          </dependency>

   主要使用依赖包中的几个对象;

                1.import ch.ethz.ssh2.Connection;
                2.import ch.ethz.ssh2.Session;
                3.import ch.ethz.ssh2.StreamGobbler;

第二步:直接上代码 讲解(鼓掌吧!!)

            1.连接到服务器

    /**
     * 用途:获取服务器连接
     * @param hostName IP地址
     * @param username 用户名
     * @param password 密码
     * @param port     端口号
     * @return
     */
    public static Connection getConnection(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) {
            System.out.println("用户名称或者是密码不正确");
        } else {
            System.out.println("服务器连接成功.");
            return conn;
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

     2.获取日志文件流

/**
   * 用途获取日志文件的输入流
   * @param ss
   * @param conn
   * @param txtPath 文本路径
   * @param sourceName 资源名称
   * @return
   */

private InputStream getInputStream(Session ss, Connection conn,
             String txtPath,String sourceName,String keyWord) {
         InputStream is1 = null;
         ss = conn.openSession();
         Object o = redisTemplate.opsForValue().get(UPX_LOG_TIME); //UPX_LOG_TIME存时间段的redisKey
         if(o == null){
             //将最后一行的时间存入redis 作为下一次查询的开始时间
             redisTemplate.opsForValue().set(UPX_LOG_TIME, this.getLastLine(ss,txtPath));
             String linuxCommand = "cat -n ".concat(txtPath+" | grep "+keyWord);
             is1 = getInputStreamOne(ss,linuxCommand,conn);
         }else{
             //根据时间段获取文件流
             String startTime = o.toString();
             String endTime =  this.getLastLine(ss,txtPath);
             if(StringUtils.isEmpty(endTime)){
                 return is1;
             }
             redisTemplate.opsForValue().set(UPX_LOG_TIME, endTime);
             String timeQuantum = "'/"+startTime+"/,/"+endTime+"/p'";
             String linuxCommand = "sed -n "+timeQuantum+" ".concat(txtPath+" | grep "+keyWord);
             is1 = getInputStreamOne(ss,linuxCommand,conn);
             logger.info("UPX模块日志,查询时间段为:{}",startTime+" - "+endTime);
         }
         return is1;
    }

/**
     * 用途:获取InputStream对象   这个方法是上方者个方法中提取出来的公共代码
     * @param ss 
     * @param commandStr linux命令
     * @return
     */
    public InputStream getInputStreamOne(Session ss,String linuxCommand,Connection conn){
         try {
            ss = conn.openSession();
            ss.execCommand(linuxCommand);
            InputStream is1 = new StreamGobbler(ss.getStdout());
            return is1;
        } catch (IOException e) {
            logger.info("用途获取日志文件的输入流异常");
        }
        return null;
    }

 /**
     * 用途:获取日志最后一行的时间点 这个是获取日志文件最后一行时间点的方法 以便下次查询使用
     * @param ss
     * @param txtPath
     * @return
     */
    public String getLastLine(Session ss,String txtPath){
        try {
            ss.execCommand("tail -n 1 ".concat(txtPath));
            InputStream is1 = new StreamGobbler(ss.getStdout());
            BufferedReader brs = new BufferedReader(new InputStreamReader(is1));
            String line = brs.readLine();
            return line.substring(0, 19);
        } catch (Exception e) {
            return "";
        }
    }

第三步,读取流文件  相关代码

InputStream is = this.getInputStream(ss,conn,txtPath,sourceName,keyWord);

BufferedReader brs = new BufferedReader(new InputStreamReader(is));
 String line = brs.readLine();

while (line != null) {
                    if (line.contains(keyWord)) {
                        this.CarInfoProcess(line,sourceName);//此方法是对获取信息进行处理的这里就不进行展示了
                        line = brs.readLine();
                    } 
                }

以上总结于工作中,可能还有些许不足 欢迎指正!!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: