当前位置: 首页 > 工具软件 > osquery > 使用案例 >

【系统审计】 采集osquery输出发送到kafka

洪凯定
2023-12-01
/*
参考github地址
https://github.com/segmentio/kafka-go
https://github.com/kolide/osquery-go
脚本启动示例:go run testQuery.go /root/.osquery/shell.em "select * from sudoers;"
*/


package main

import (
        "fmt"
        "context"
        "os"
        "time"
        "log"
        "encoding/json"
        "github.com/kolide/osquery-go"
        "github.com/segmentio/kafka-go"
        osquery2 "github.com/kolide/osquery-go/gen/osquery"
)



func main(){
    data :=  getData()
    for key,_  := range data  {
                stringtest := mapToString(data[key])
                fmt.Println(stringtest)
                sendKafka(stringtest)
        }
}




func getData()(data osquery2.ExtensionPluginResponse ) {
        if len(os.Args) != 3 {
                log.Fatalf("Usage: %s SOCKET_PATH QUERY", os.Args[0])
        }

        client, err := osquery.NewClient(os.Args[1], 2*time.Second)
        if err != nil {
                log.Fatalf("Error creating Thrift client: %v", err)
        }
        defer client.Close()

        resp, err := client.Query(os.Args[2])
        if err != nil {
                log.Fatalf("Error communicating with osqueryd: %v",err)
        }
        if resp.Status.Code != 0 {
                log.Fatalf("osqueryd returned error: %s", resp.Status.Message)
        }

        return resp.Response
}




func mapToString(param map[string]string) string {
	dataType ,_ := json.Marshal(param)
	dataString := string(dataType)
	return dataString
}


func sendKafka(para string) {
	topic := "my-topic"
	partition := 0

	conn, err := kafka.DialLeader(context.Background(), "tcp", "192.168.244.143:9092", topic, partition)
	if err != nil {
		log.Fatal("failed to dial leader:", err)
	}

	conn.SetWriteDeadline(time.Now().Add(10*time.Second))
	_, err = conn.WriteMessages(
		kafka.Message{Value: []byte(para)},
	)
	if err != nil {
		log.Fatal("failed to write messages:", err)
	}

	if err := conn.Close(); err != nil {
		log.Fatal("failed to close writer:", err)
	}
}

 

 类似资料: