zoukankan      html  css  js  c++  java
  • go tail 使用

    git 仓库:https://github.com/hpcloud/tail.git

    package main
    
    import (
        "fmt"
        "github.com/hpcloud/tail"
        "strings"
    )
    
    type InfoData struct {
        InIntf   string
        OutIntf  string
        SrcAddr  string
        DstAddr  string
        Protocol string
        SrcPort  string
        DstPort  string
        DateTime string
    }
    
    func main() {
        t, err := tail.TailFile("/var/log/iptables.log", tail.Config{
            Location:  &tail.SeekInfo{0, 2},
            Follow:    true,
            MustExist: true,
            Logger:    tail.DiscardingLogger,
        })
        if err != nil {
            fmt.Println(err.Error())
            return
        }
        defer t.Stop()
    
        for line := range t.Lines {
            data := InfoData{
                DateTime: line.Time.Format("2006-01-02 15:04:05"),
            }
    
            fmt.Println(line)
            fmt.Println(line.Time)
            fmt.Println(line.Text)
    
            n1 := strings.Split(line.Text, "iptables:")
            fmt.Println(n1)
    
            n2 := strings.Fields(n1[1])
            for n := range n2 {
                s := strings.Split(n2[n], "=")
    
                switch s[0] {
                case "IN":
                    data.InIntf = s[1]
                case "OUT":
                    data.OutIntf = s[1]
                case "SRC":
                    data.SrcAddr = s[1]
                case "DST":
                    data.DstAddr = s[1]
                case "SPT":
                    data.SrcPort = s[1]
                case "DPT":
                    data.DstPort = s[1]
                case "PROTO":
                    data.Protocol = s[1]
                }
            }
    
            fmt.Println(data)
        }
    }
  • 相关阅读:
    设计模式之_6大设计原则(转)
    Django-ORM多表操作(进阶)
    03-django模型(1)
    02-Django基础知识
    web开篇
    body标签中的相关标签
    01-前端初识
    Flask简述
    浅析设计模式
    Python的单例模式
  • 原文地址:https://www.cnblogs.com/wangjq19920210/p/15185606.html
Copyright © 2011-2022 走看看