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)
    }
}

 

posted @ 2021-08-25 16:20  salami_china  阅读(86)  评论(0编辑  收藏  举报