summaryrefslogtreecommitdiff
path: root/examples/dhcpleases.py
blob: d023e4d25b01cf2d5a2b2d9bd4adfb7e476071a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
"""
Print leases info for a given virtual network
"""

import libvirt
import sys
import time
from argparse import ArgumentParser


parser = ArgumentParser(description=__doc__)
parser.add_argument("uri", nargs="?", default=None)
parser.add_argument("network")
args = parser.parse_args()

try:
    conn = libvirt.open(args.uri)
except libvirt.libvirtError:
    print("Unable to open connection to libvirt")
    sys.exit(1)

try:
    net = conn.networkLookupByName(args.network)
except libvirt.libvirtError:
    print("Network %s not found" % args.network)
    sys.exit(0)

leases = net.DHCPLeases()
if not leases:
    print("Failed to get leases for %s" % net.name())
    sys.exit(0)

def toIPAddrType(addrType: int) -> str:
    if addrType == libvirt.VIR_IP_ADDR_TYPE_IPV4:
        return "ipv4"
    elif addrType == libvirt.VIR_IP_ADDR_TYPE_IPV6:
        return "ipv6"
    return "Unknown"

print(" {0:20} {1:18} {2:9} {3:25} {4:15} {5}".format("Expiry Time",
                                                      "MAC address",
                                                      "Protocol",
                                                      "IP address",
                                                      "Hostname",
                                                      "Client ID or DUID"))
print("-"*115)

for lease in leases:
    print(" {0:20} {1:18} {2:9} {3:25} {4:15} {5}".format(
        time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lease['expirytime'])),
        lease['mac'],
        toIPAddrType(lease['type']),
        "{}/{}".format(lease['ipaddr'], lease['prefix']),
        lease['hostname'],
        lease['clientid']
    ))