Prometheus metrics数据抓取解析

Prometheus node的监控数据如链接展示,我们希望能更加方便的看到监控数据,shodan对Prometheus metrics 的数据做了格式化处理。172.96.3.215:9100/metricsicon-default.png?t=N7T8http://172.96.3.215:9100/metrics

 本文我自己实现了一个命令行工具,可以输出类shodan数据格式监控数据。以下是代码示例

// ExtractMsg 提取信息
/*
  1.node_dmi_info
  2.node_exporter_build_info
  3.node_network_info
  4.node_os_info
  5.node_uname_info
  按照顺序从前到后寻找
*/
func ExtractMsg(resp string) {
	//(1)提取node_dmi_info信息的子串
	tmpindex := 0
	dmiResult, dmiEndindex := common(resp, "node_dmi_info{")
	tmpindex += dmiEndindex
	//(2)提取node_exporter_build_info信息的子串
	buildResult, buildEndindex := common(resp[tmpindex:], "node_exporter_build_info{")
	tmpindex += buildEndindex
	networkStartIndex := tmpindex
	//(3)提取node_os_info信息的子串
	osResult, osEndindex := common(resp[tmpindex:], "node_os_info{")
	tmpindex += osEndindex
	// 提取node_network_info信息的子串,特殊模块
	network(resp[networkStartIndex:], "node_network_info{")
	//(4)提取node_uname_info信息的子串
	unameResult, _ := common(resp[tmpindex:], "node_uname_info{")
	// 逐个序列化
	json.Unmarshal([]byte(dmiResult), &prometheus.NodeDmiInfo)
	json.Unmarshal([]byte(buildResult), &prometheus.NodeExporterBuildInfo)
	json.Unmarshal([]byte(osResult), &prometheus.NodeOsInfo)
	json.Unmarshal([]byte(unameResult), &prometheus.NodeUnameInfo)
}

// common 公共模块
func common(resp, findstr string) (result string, endIndex int) {
	startIndex := strings.Index(resp, findstr)
	// 找不到的情况
	if startIndex == -1 {
		return "", 0
	}
	endIndex = strings.Index(resp[startIndex:], "} 1")
	endIndex = endIndex + startIndex + 1
	// 提取子串的内容
	result = strings.ReplaceAll(resp[startIndex+len(findstr)-1:endIndex], "=", ":")
	re := regexp.MustCompile(`(\w+):([^,]+)`)
	result = re.ReplaceAllString(result, `"$1":$2`)
	return
}

// network 单独的网络模块
func network(resp, findstr string) {
	count := strings.Count(resp, findstr)
	prometheus.NodeNetworkInfo = make([]Response.NodeNetworkInfo, count)
	//找到第一个开始位置
	startIndex := strings.Index(resp, findstr)
	for i := 0; i < count; i++ {
		//找到结束位置
		endIndex := strings.Index(resp[startIndex:], "} 1")
		//算出结束位置
		endIndex = endIndex + startIndex + 1
		// 提取子串的内容
		result := strings.ReplaceAll(resp[startIndex+len(findstr)-1:endIndex], "=", ":")
		// 把多余的部分截掉,使其可以被反序列化为对象
		result = strings.TrimLeft(result, "nfo")
		// 正则并且加引号,使其称为JSON格式
		re := regexp.MustCompile(`(\w+):([^,]+)`)
		result = re.ReplaceAllString(result, `"$1":$2`)
		// 反序列化
		err := json.Unmarshal([]byte(result), &prometheus.NodeNetworkInfo[i])
		if err != nil {
			panic(err)
		}
		startIndex = endIndex
	}
}

效果如下:

 

 完整代码详见GitHub

FrankZhang63/Promethues: Promethues metrics 类shodan数据格式 (github.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值