-
Notifications
You must be signed in to change notification settings - Fork 73
/
libvirt_csv.py
executable file
·88 lines (72 loc) · 2.37 KB
/
libvirt_csv.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python
"""
Test of using the LibVirt Python bindings to gather
information about libvirt (qemu/KVM) guests.
test on opskvmtie13
##################
Copyright 2014 Jason Antman <[email protected]> <http://www.jasonantman.com>
Free for any use provided that patches are submitted back to me.
The latest version of this script can be found at:
<https://github.com/jantman/misc-scripts/blob/master/libvirt_csv.py>
CHANGELOG:
- initial script
"""
import libvirt
import sys
if len(sys.argv) > 1:
hostname = sys.argv[1]
else:
print("USAGE: test_libvirt.py <hostname> <...>")
sys.exit(1)
DOM_STATES = {
libvirt.VIR_DOMAIN_NOSTATE: 'no state',
libvirt.VIR_DOMAIN_RUNNING: 'running',
libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
libvirt.VIR_DOMAIN_CRASHED: 'crashed',
libvirt.VIR_DOMAIN_PMSUSPENDED: 'suspended by guest power mgmt',
}
# bitwise or of all possible flags to virConnectListAllDomains
ALL_OPTS = 16383
def bool(a):
if a == 0:
return False
return True
def get_domains(conn):
"""
Takes a libvirt connection object,
returns a list of all domains, each element
being a dict with items "name", "ID", "UUID",
"""
domains = conn.listAllDomains(ALL_OPTS)
ret = []
for d in domains:
foo = {}
foo['name'] = d.name()
foo['ID'] = d.ID()
foo['UUID'] = d.UUIDString().upper()
[state, maxmem, mem, ncpu, cputime] = d.info()
foo['state'] = DOM_STATES.get(state, state)
ret.append(foo)
return ret
hosts = sys.argv
hosts.pop(0)
print("host,name,ID,state,UUID")
for h in hosts:
uri = "qemu+ssh://%s/system" % h
#print("Using hostname: %s (URI: %s)" % (h, uri))
try:
conn = libvirt.openReadOnly(uri)
except libvirt.libvirtError as e:
print("ERROR connecting to %s: %s" % (uri, e.message))
continue
# some code examples imply that older versions
# returned None instead of raising an exception
if conn is None:
print("ERROR connecting to %s: %s" % (uri, e.message))
continue
doms = get_domains(conn)
for d in doms:
print("{host},{name},{ID},{state},{UUID}".format(host=h, name=d['name'], ID=d['ID'], UUID=d['UUID'], state=d['state']))