Dhcp.leases kontrollimise skript

From ICO wiki

Skript, mis analüüsib DHCP serveri leases faili, leiab sealt kehtivad lease'id ning pingib neid aadresse tegemaks kindlaks, kas masin on üleval või mitte (eeldusel, et masin üldse pingile tahab vastata).

Siim Liivand, AK41

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Siim Liivand, AK41

import re, time
from subprocess import Popen, PIPE

fh = open("dhcpd.leases")
lines = fh.read().split("\n")
fh.close()
lease = None
outdated = False
timestamp = time.time()
for line in lines:
    if not line or line.startswith("#"):
        continue
    if line == "}" and lease:
        if not outdated:
            ping = Popen(
                ["ping", "-n", "-c", "4", str(lease["ip"])],
                stdout = PIPE,
                stderr = PIPE
            )
            lease["status"] = "Down"
            if re.search(r",\s[1-4]\sreceived,", ping.stdout.read()):
                lease["status"] = "Up"
            # print lease
            print 'IP: %s,\tMAC: %s,\tState: %s' % (lease["ip"], lease["mac"], lease["status"])
        lease = None
        outdated = False
        continue
    m = re.match("lease\s+([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", line)
    if m:
        assert not lease, "Parse error: '%s'" % line
        lease = {}
        lease["ip"] = re.findall("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", str(m.groups()))[0]
        continue
    assert isinstance(lease, dict), "Parse error: '%s'" % line
    m = re.match(r"\s+([a-z\s\-]+)\s+\"?(.+?)?\"?\;", line);
    if m:
        key, value = m.groups()
        if key == "hardware ethernet":
            lease["mac"] = value.lower()
        elif key == "ends":
            if time.mktime(time.strptime(value, "%w %Y/%m/%d %H:%M:%S")) < timestamp:
                outdated = True