日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

詳解Go程序添加遠程調用tcpdump功能_Golang

作者:superpigwin ? 更新時間: 2022-07-20 編程語言

最近開發的telemetry采集系統上線了。聽起來高大上,簡單來說就是一個grpc/udp服務端,用戶的機器(路由器、交換機)將它們的各種統計數據上報采集、整理后交后端的各類AI分析系統分析。目前華為/思科的大部分設備支持。

上線之后,各類用戶開始找來要求幫忙定位問題,一般是上報的數據在后端系統中不存在等等。

在一通抓包分析后,百分之99都是用戶自己的問題。但頻繁的抓包定位問題,嚴重的壓縮了我摸魚的時間。而且,這套系統采用多實例方式部署在騰X云多個容器中,一個個的登錄抓包,真的很煩。

這讓我萌生了一個需求:

  • 主動給采集器下發抓包任務。
  • 將抓包的信息返回。
  • 將抓包的文件暫存,以備進一步定位問題。

方法1

使用fabric等ssh運維工具,編寫腳本自動化登錄機器后執行tcpdump,然后進一步處理。
很可惜的是,并沒有容器母機ssh的權限。只能通過一個web命令行觀察容器。這條路玩不轉。

方法2

  • 在采集器中添加一個接口,用以下發tcpdump命令
  • 采集器執行tcpdump命令,并獲取返回的信息(比如captured xxx pacs),保存相關文件。
  • 將獲取的抓包信息以某種方式反發給命令下發人。

使用tcpdump定時抓取并保存信息

首先需要解決tcpdump定時的問題,以免tcpdump無限期的執行抓包,經過一通谷歌,命令如下:

timeout 30 tcpdump -i eth0 host 9.123.123.111 and port 6651 -w /tmp/log.cap

timeout 30 指抓取30秒,超時后tcpdump會直接退出
-i 指定抓取的端口
host xxx 源IP
port xxx 源端口

編寫tcpdump函數

下面到了我最喜歡的寫代碼階段,為了簡單,直接使用os/exec庫。不要笑,很多大廠的很多系統其實都是包命令行工具,解決問題最重要。

// TcpDump 執行tcpdump命令,并返回抓到的包數
func TcpDump(sudo bool, timeout int, eth string, host string, port int) (caps int, err error) {
	portStr := ""
	if port != 0 {
		portStr = fmt.Sprintf("and port %v", port)
	}
	tcpdumpCmd := fmt.Sprintf("timeout %v tcpdump -i %v host %v %v -w /tmp/log.cap",
		timeout, eth, host, portStr)
	if sudo {
		tcpdumpCmd = "sudo " + tcpdumpCmd
	}
	logrus.Infof("call %v", tcpdumpCmd)
	cmd := exec.Command("sh", "-c", tcpdumpCmd)
	var outb, errb bytes.Buffer
	cmd.Stderr = &errb
	err = cmd.Run()
	if err != nil {
		if !errors.Is(err, &exec.ExitError{}) {
			logrus.Infof("out:%s ; %s", outb.Bytes(), errb.Bytes())
			return getPacs(errb.String()), nil
		}
		return
	}
	return 0,fmt.Errorf("unknown error")
}
func getPacs(input string) int {
	end := strings.Index(input, "packets captured")
	pos := end
	for {
		pos -= 1
		if pos <= 0 {
			return 0
		}
		if input[pos] == '\n' {
			break
		}
	}
	// logrus.Infof("captured:%s", input[pos+1:end-1])
	v, err := strconv.Atoi(input[pos+1 : end-1])
	if err != nil {
		return 0
	}
	return v
}

這里要注意幾點:

執行cmd := exec.Command("sh", "-c", tcpdumpCmd)后,tcpdump的返回信息類似:

listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes\n56 packets captured\n56 packets received by filter\n0 packets dropped by kernel\n

是在stderr中的。而不是stdout。

getPacs函數簡單的從xx packets received中提取出了抓包數。但是如果是中文的服務器系統(不會吧,不會吧),就不太好使了。

編寫api

現在函數已經有了,只要再寫一個http api,就能很方便的把它暴露出去。

import "github.com/gogf/gf/v2/encoding/gjson"
// ErrJson,寫入一個error json,形如:
//{
//    "err": code,
//    "err_msg": msg
//}
func ErrJson(w http.ResponseWriter, errCode int, errStr string) error {
	w.Header().Set("Content-Type", "application/json")
	js := make(map[string]interface{})
	js["err"] = errCode
	js["err_msg"] = errStr
	jsBts, _ := json.Marshal(js)
	_, err := w.Write(jsBts)
	return err
}
/* TcpDumpHandler
req:{
	"sudo":  true,
	"eth": "eth0",
	"host": "10.99.17.135",
	"port": 0
}
rsp:{
	"err": 0,
	"caps": 14
}
*/
func TcpDumpHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	ret, err := ioutil.ReadAll(r.Body)
	if err != nil {
		ErrJson(w, 1, "數據錯誤")
		return
	}
	js := gjson.New(ret)
	sudo := js.Get("sudo").Bool()
	eth := js.Get("eth").String()
	if eth == "" {
		ErrJson(w, 1, "數據錯誤, eth不存在")
		return
	}
	host := js.Get("host").String()
	if host == "" {
		ErrJson(w, 1, "數據錯誤, host不存在")
		return
	}
	port := js.Get("port").Int()
	timeout := js.Get("timeout").Int()
	if timeout == 0 {
		ErrJson(w, 1, "數據錯誤, timeout為0或不存在")
		return
	}
	go func() {
		chatKey := config.GlobalConfigObj.Global.ChatKey
		botKey := config.GlobalConfigObj.Global.BotKey
		
		// 這里直接利用了公司的一個消息系統,如果貴公司沒有這樣的系統,就變通一下
		msgSender := msg.NewNiuBiMsg(chatKey, botKey)
		caps, err := TcpDump(sudo, timeout, eth, host, port)
		if err != nil {
			return
		}
		if caps > 0 {
			// 這里直接利用了公司的一個消息系統,向企業IM發一條消息
			msgSender.Send(fmt.Sprintf("tcpdump agent_ip:%v host:%v eth:%v port:%v, captured:%v",
				config.GlobalLocalConfig.LocalIP, host, eth, port, caps))
			bts, err := ioutil.ReadFile("/tmp/log.cap")
			if err != nil {
				return
			}
			b64Caps := base64.StdEncoding.EncodeToString(bts)
			// 把抓包的文件通過這個消息系統也發到企業IM中
			msgSender.File(fmt.Sprintf("pacs_%v.cap", config.GlobalLocalConfig.LocalIP), b64Caps)
		}
	}()
}

然后起一個http svr

func runHttp() {
	mux := http.NewServeMux()
	server :=
		http.Server{
			Addr:         fmt.Sprintf(":%d", 3527),
			Handler:      mux,
			ReadTimeout:  3 * time.Second,
			WriteTimeout: 5 * time.Second,
		}
	// 開始添加路由
	mux.HandleFunc("/tcpdump", tcpdumpsvc.TcpDumpHandler)
	logrus.Infof("run http:%v", 3527)
	logrus.Info(server.ListenAndServe())
}

到這一步,這個系統就基本完成了。使用這個命令就能調用接口。

curl --header "Content-Type: application/json" --request GET --data '{"sudo":false,"eth":"eth0","host":"100.xxx.xxx.10","port":0,"timeout":5}' http://0.0.0.0:3527/tcpdump

這個系統有幾個硬傷。

  • 依賴了公司的消息系統完成抓包數據回發的功能。假如各位大佬的公司沒有這樣的系統msgSender.Send,可行的方法有:
  • scp到一個特定的文件夾。
  • 使用電子郵件。
  • 和領導申請自己開發一套,你看,需求就來了。
  • tcpdump可能會生成極大的抓包文件,此時使用bts, err := ioutil.ReadFile("/tmp/log.cap"),可能會直接讓系統OOM。所以設置timeout和抓包的大小(比如在tcpdump命令中使用-c)是很重要的。換句話說,這個api不是公有的,別讓不了解的人去調用。

不過這都是小問題。現在用戶找上門來,我只需要啟動腳本,從服務發現api拉到所有的實例IP,然后依次調用tcpdump api,等待IM的反饋即可。又能快樂的摸魚啦。

原文鏈接:https://www.cnblogs.com/superpigwin/archive/2022/05/23/16271664.html

欄目分類
最近更新