fetchport.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. if port < sw.first_port or port > sw.last_port:
  26. continue
  27. g = status_regex.match(info)
  28. if not g:
  29. continue
  30. status = g.group('status')
  31. if status == 'up':
  32. up.append(port)
  33. else:
  34. assert(status == 'down')
  35. down.append(port)
  36. unknown = set(range(sw.first_port, sw.last_port + 1)) - set(up) - set(down)
  37. upped = sw.ports.filter(port__in=up).exclude(up=True).update(up=True)
  38. downed = sw.ports.filter(port__in=down).exclude(up=False).update(up=False)
  39. unknowned = sw.ports.filter(port__in=unknown).exclude(up__isnull=True).update(up=None)
  40. #print("Switch %s: UP: %d (%+d), DOWN: %d (%+d), UNKNOWN: %d (%+d)" \
  41. # % (sw.name, len(up), upped, len(down), downed, len(unknown), unknowned))