Debian Codegraph @

examples/dhcpleases.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 Print leases info for a given virtual network
4 """
5
6 import libvirt
7 import time
8 from argparse import ArgumentParser
9
10
11 parser = ArgumentParser(description=__doc__)
12 parser.add_argument("uri", nargs="?", default=None)
13 parser.add_argument("network")
14 args = parser.parse_args()
15
16 try:
17 conn = libvirt.open(args.uri)
18 except libvirt.libvirtError:
19 print("Unable to open connection to libvirt")
20 exit(1)
21
22 try:
23 net = conn.networkLookupByName(args.network)
24 except libvirt.libvirtError:
25 print("Network %s not found" % args.network)
26 exit(0)
27
28 leases = net.DHCPLeases()
29 if not leases:
30 print("Failed to get leases for %s" % net.name())
31 exit(0)
32
33
34 def toIPAddrType(addrType: int) -> str:
35 if addrType == libvirt.VIR_IP_ADDR_TYPE_IPV4:
36 return "ipv4"
37 elif addrType == libvirt.VIR_IP_ADDR_TYPE_IPV6:
38 return "ipv6"
39 return "Unknown"
40
41
42 print(" {0:20} {1:18} {2:9} {3:25} {4:15} {5}".format("Expiry Time",
43 "MAC address",
44 "Protocol",
45 "IP address",
46 "Hostname",
47 "Client ID or DUID"))
48 print("-" * 115)
49
50 for lease in leases:
51 print(" {0:20} {1:18} {2:9} {3:25} {4:15} {5}".format(
52 time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lease['expirytime'])),
53 lease['mac'],
54 toIPAddrType(lease['type']),
55 "{}/{}".format(lease['ipaddr'], lease['prefix']),
56 lease['hostname'],
57 lease['clientid']
58 ))