routeros-exporter/main.py

63 lines
1.9 KiB
Python
Raw Normal View History

2021-05-19 21:05:54 +00:00
import requests as req
from requests.models import Response
2021-05-29 20:46:31 +00:00
from requests.packages.urllib3.exceptions import InsecureRequestWarning
2021-05-19 21:05:54 +00:00
from prometheus_client import start_http_server, Gauge
2021-05-29 21:14:26 +00:00
import time, os
2021-05-19 21:05:54 +00:00
def process_request(router_ip,router_username,router_password):
url = 'https://' + router_ip + '/rest/interface'
2021-05-29 20:46:31 +00:00
req.packages.urllib3.disable_warnings(InsecureRequestWarning)
try:
response = req.get(url, auth=(router_username,router_password), verify=False, timeout=5)
except urllib3.exceptions.ReadTimeoutError:
print("Connect timeout")
2021-05-19 21:05:54 +00:00
if response.status_code != 200:
quit()
return response.json()
2021-05-29 20:46:31 +00:00
def declare_prometheus_metrics(data,router_ip):
2021-05-19 21:05:54 +00:00
prom = dict()
2021-05-29 20:46:31 +00:00
metrics = ['fp_rx_byte','fp_tx_byte','tx_byte','rx_byte']
2021-05-19 21:05:54 +00:00
# declare all metrics
2021-05-29 20:46:31 +00:00
for key in metrics:
name = 'routeros_interface_' + key
prom[name] = Gauge(name,"RouterOS interface " + key, ['routerip','interface'])
2021-05-19 21:05:54 +00:00
return prom
2021-05-29 20:46:31 +00:00
def prom_request(data,prom,routerip):
metrics = {'fp_rx_byte' : 'fp-rx-byte','fp_tx_byte' : 'fp-tx-byte','tx_byte' : 'tx-byte','rx_byte' : 'rx-byte'}
2021-05-19 21:05:54 +00:00
for key in data:
2021-05-29 20:46:31 +00:00
for m in metrics:
name = 'routeros_interface_' + m
interface = key['name']
value = key[metrics[m]]
prom[name].labels(routerip=routerip,interface=interface).set(value)
2021-05-19 21:05:54 +00:00
if __name__ == '__main__':
2021-05-29 20:46:31 +00:00
2021-05-19 21:05:54 +00:00
router_ip = os.environ['ROUTER_IP']
router_username = os.environ['ROUTER_USERNAME']
router_password = os.environ['ROUTER_PASSWORD']
# Start up the server to expose the metrics.
start_http_server(8000)
# init metrics
data = process_request(router_ip,router_username,router_password)
2021-05-29 20:46:31 +00:00
prom = declare_prometheus_metrics(data,router_ip)
2021-05-19 21:05:54 +00:00
# Generate requests.
while True:
data = process_request(router_ip,router_username,router_password)
2021-05-29 20:46:31 +00:00
prom_request(data,prom,router_ip)
2021-05-19 21:05:54 +00:00
time.sleep(3)