Guest User

Untitled

a guest
Mar 17th, 2023
648
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.71 KB | None | 0 0
  1. #!/usr/bin/python
  2. from prometheus_client import start_http_server, Metric, REGISTRY
  3. from threading import Lock
  4. from cachetools import cached, TTLCache
  5. from requests import Request, Session
  6. import requests
  7. import re
  8. import os
  9. import sys
  10. import argparse
  11. import json
  12. import logging
  13. import time
  14.  
  15. from bs4 import BeautifulSoup
  16.  
  17. baseurl = 'http://192.168.100.1' # Default IP
  18. username = "leox" #Default login
  19. password = "leolabs_7" #Default password
  20.  
  21.  
  22. # lock of the collect method
  23. lock = Lock()
  24.  
  25. # logging setup
  26. log = logging.getLogger('leox-exporter')
  27. log.setLevel(logging.INFO)
  28. ch = logging.StreamHandler(sys.stdout)
  29. ch.setLevel(logging.INFO)
  30. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  31. ch.setFormatter(formatter)
  32. log.addHandler(ch)
  33.  
  34. # caching API for 15s
  35. # Note the api limits: https://pro.coinmarketcap.com/features
  36. cache_ttl = int(os.environ.get('CACHE_TTL', 15))
  37. cache_max_size = int(os.environ.get('CACHE_MAX_SIZE', 10000))
  38. cache = TTLCache(maxsize=cache_max_size, ttl=cache_ttl)
  39.  
  40.  
  41. class LeoxClient():
  42. def __init__(self):
  43. self.urls = [
  44. ['pon_stats' , baseurl + '/admin/pon-stats.asp?' ],
  45. ['pon_status', baseurl + '/status_pon.asp?'],
  46. ['ont_status', baseurl + '/status.asp?' ]
  47. ]
  48.  
  49. @cached(cache)
  50. def getinfos(self):
  51. log.info("Mis a jours des information")
  52. infos= []
  53. for url in self.urls:
  54. print(url)
  55. req = requests.get(url[1], auth=(username, password))
  56. soup = BeautifulSoup(req.content, 'html.parser')
  57. d = 0
  58. divs = soup.find_all("div", {"class": "column"})
  59. for div in divs:
  60. d = d + 1
  61. #print("DIV",div)
  62. div_title = div.find("div",{"class": "column_title"})
  63. if div_title :
  64. titre = div_title.find("p").get_text()
  65. #print("TITRE",titre)
  66. data = div.find("div",{"class" :"data_common"})
  67. datav = div.find("div",{"class" :"data_common data_vertical"})
  68. if datav:
  69. print("DATA VERTICAL","datav")
  70. else:
  71. for row in data.findAll("tr"):
  72. dtitre = titre + '_' + row.findAll("th")[0].get_text().replace(" ","_")
  73. dtitre = re.sub(r"\s+", '_', dtitre).lower()
  74. dvalue = row.findAll("td")[0].get_text()
  75. print('ont_leox_' + dtitre + ': ' + dvalue)
  76. infos.append({'name' : 'ont_leox_' + dtitre ,'value' : dvalue})
  77.  
  78. #print("DATA",data)
  79. if d == 0:
  80. titre = 'PON Statistics'
  81. for row in soup.findAll("tr"):
  82. dtitre = titre + '_' + row.findAll("th")[0].get_text().replace(" ","_")
  83. dtitre = re.sub(r"\s+", '_', dtitre).lower()
  84. dtitre = re.sub(r":", '', dtitre)
  85. dvalue = row.findAll("td")[0].get_text()
  86. print('ont_leox_' + dtitre + ': ' + dvalue)
  87. infos.append({'name' : 'ont_leox_' + dtitre ,'value':dvalue})
  88. #pon_statistics
  89. #<div class="data_common data_common_notitle">
  90. return infos
  91.  
  92. class LeoxCollector():
  93. def __init__(self):
  94. self.client = LeoxClient()
  95.  
  96.  
  97. def collect(self):
  98. with lock:
  99. log.info('collecting...')
  100. infos = self.client.getinfos()
  101. metric = Metric('leox', 'Leox metric values', 'gauge')
  102. for info in infos:
  103. #print(info)
  104. name = info['name']
  105. value = info['value']
  106. value_int = False
  107. match = re.search(r'^[\-0-9.]+', value)
  108. if match:
  109. value_int = match.group(0)
  110. #Remove IP
  111. match = re.search(r'^[0-9]+\.[0-9]+\.[0-9].[0-9]+', value)
  112. if match:
  113. value_int = False
  114.  
  115. match = re.search(r'^O([0-9])$', value)
  116. if match:
  117. value_int = match.group(1)
  118. print('Colected:' + name + ': ' + value + '>' + str(value_int))
  119.  
  120. if value_int:
  121. metric.add_sample(name, value=float(value_int), labels={'name': 'LEOX'})
  122. yield metric
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130. if __name__ == '__main__':
  131. try:
  132. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  133. parser.add_argument('--port', nargs='?', const=9103, help='The TCP port to listen on', default=9103)
  134. parser.add_argument('--addr', nargs='?', const='127.0.0.1', help='The interface to bind to', default='127.0.0.1')
  135. args = parser.parse_args()
  136. log.info('listening on http://%s:%d/metrics' % (args.addr, args.port))
  137.  
  138. REGISTRY.register(LeoxCollector())
  139. start_http_server(int(args.port), addr=args.addr)
  140.  
  141. while True:
  142. time.sleep(60)
  143. except KeyboardInterrupt:
  144. print(" Interrupted")
  145. exit(0)
  146.  
  147.  
Advertisement
Add Comment
Please, Sign In to add comment