fetchport.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from django.core.management.base import BaseCommand
  2. from services.models import Switch
  3. from djadhere.utils import from_livestatus
  4. import re
  5. class Command(BaseCommand):
  6. help = 'Récupération du dernier ping depuis check_mk'
  7. def handle(self, *args, **options):
  8. dell_iface_regex = re.compile('^Interface TenGigabitEthernet 0/(?P<id>[0-9]+)$')
  9. ubnt_iface_regex = re.compile('^Interface Slot: 0 Port: (?P<id>[0-9]+) (Gigabit|10G) - Level$')
  10. status_regex = re.compile('^OK .* \((?P<status>up|down)\)')
  11. for sw in Switch.objects.all():
  12. up, down = [], []
  13. hosts = from_livestatus('hosts', query=['Filter: host_name = %s' % sw.name], columns=['services_with_info'])
  14. if len(hosts) != 1:
  15. return
  16. host = hosts[0]
  17. for service in host.services_with_info:
  18. description, _, _, info = service
  19. g = dell_iface_regex.match(description)
  20. if not g:
  21. g = ubnt_iface_regex.match(description)
  22. if not g:
  23. continue
  24. port = int(g.group('id'))
  25. g = status_regex.match(info)
  26. if not g:
  27. continue
  28. status = g.group('status')
  29. if status == 'up':
  30. up.append(port)
  31. else:
  32. assert(status == 'down')
  33. down.append(port)
  34. unknown = [] # TODO
  35. upped = sw.ports.filter(port__in=up).exclude(up=True).update(up=True)
  36. downed = sw.ports.filter(port__in=down).exclude(up=False).update(up=False)
  37. unknowned = sw.ports.filter(port__in=unknown).exclude(up__isnull=True).update(up=None)
  38. print("Switch %s: UP: %d (%+d), DOWN: %d (%+d), UNKNOWN: %d (%+d)" % (sw.name, len(up), upped, len(down), downed, len(unknown), unknowned))