Dhcp.leases kontrollimise skript

From ICO wiki
Revision as of 22:14, 30 January 2011 by Sliivand (talk | contribs) (Created page with 'Skript, mis analüüsib DHCP serveri ''leases'' faili, leiab sealt kehtivad ''lease'''id ning ''ping''ib neid aadresse tegemaks kindlaks, kas masin on üleval või mitte (eelduse…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

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).

#!/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
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
        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"] = m.groups()
        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":
            endtime = time.mktime(time.strptime(value, "%w %Y/%m/%d %H:%M:%S"))
            # lease["end"] = value.lower()
            if endtime < time.time():
                outdated = True