以下是一个示例Python脚本,可通过SNMP v2协议获取空调设备指标,并按照Prometheus Metrics标准格式输出:
from pysnmp.hlapi import *
import re
def get_snmp_metrics(ip, community):
metrics = {}
for (errorIndication,
errorStatus,
errorIndex,
varBinds) in bulkCmd(SnmpEngine(),
CommunityData(community),
UdpTransportTarget((ip, 161)),
ContextData(),
0, 50,
ObjectType(ObjectIdentity('1.3.6.1.4.1.9.9.272'))):
if errorIndication or errorStatus:
print(errorIndication or errorStatus)
return {}
for varBind in varBinds:
oid, value = varBind
match = re.match(r'.*\.(\d+)\s*$', str(oid))
if not match:
continue
index = int(match.group(1))
if index == 13: # 获取空调温度
metrics['temperature'] = int(value)
elif index == 14: # 获取空调湿度
metrics['humidity'] = int(value)
elif index == 15: # 获取空调功率消耗
metrics['power'] = int(value)
return metrics
if __name__ == '__main__':
ip_address = '192.168.1.100'
snmp_community = 'public'
metrics_dict = get_snmp_metrics(ip_address, snmp_community)
print(f'temperature {metrics_dict.get("temperature", 0)}')
print(f'humidity {metrics_dict.get("humidity", 0)}')
print(f'power {metrics_dict.get("power", 0)}')
该脚本使用了pysnmp库来执行SNMP v2协议的批量查询。在这个示例中,我们从空调设备获取了三个指标:温度、湿度和功率消耗,并将它们作为Prometheus Metrics格式输出。
要运行此脚本,请将ip_address和snmp_community变量设置为正确的值,并确保您已经安装了pysnmp库。
请注意,此示例仅供参考。具体的OID值可能会因设备型号和厂商而异,需要根据实际情况进行调整。




