Debian Codegraph @

examples/esxlist.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 List active domains of an ESX host and print some info.
4 """
5 # also demonstrates how to use the libvirt.openAuth() method
6
7 import libvirt
8 import libxml2
9 import getpass
10 from argparse import ArgumentParser
11 from typing import Any
12
13
14 # This is the callback method passed to libvirt.openAuth() (see below).
15 #
16 # The credentials argument is a list of credentials that libvirt (actually
17 # the ESX driver) would like to request. An element of this list is itself a
18 # list containing 5 items (4 inputs, 1 output):
19 # - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME
20 # - a prompt to be displayed to the user
21 # - a challenge, the ESX driver sets this to the hostname to allow automatic
22 # distinction between requests for ESX and vCenter credentials
23 # - a default result for the request
24 # - a place to store the actual result for the request
25 #
26 # The user_data argument is the user data item of the auth argument (see below)
27 # passed to libvirt.openAuth().
28 def request_credentials(credentials: list[list], user_data: Any) -> int:
29 for credential in credentials:
30 if credential[0] == libvirt.VIR_CRED_AUTHNAME:
31 # prompt the user to input a authname. display the provided message
32 credential[4] = input(credential[1] + ": ")
33
34 # if the user just hits enter raw_input() returns an empty string.
35 # in this case return the default result through the last item of
36 # the list
37 if len(credential[4]) == 0:
38 credential[4] = credential[3]
39 elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT:
40 # use the getpass module to prompt the user to input a password.
41 # display the provided message and return the result through the
42 # last item of the list
43 credential[4] = getpass.getpass(credential[1] + ": ")
44 else:
45 return -1
46
47 return 0
48
49
50 def print_section(title: str) -> None:
51 print("\n%s" % title)
52 print("=" * 60)
53
54
55 def print_entry(key: str, value: Any) -> None:
56 print("%-10s %-10s" % (key, value))
57
58
59 def print_xml(key: str, ctx, path: str) -> str:
60 res = ctx.xpathEval(path)
61
62 if res is None or len(res) == 0:
63 value = "Unknown"
64 else:
65 value = res[0].content
66
67 print_entry(key, value)
68
69 return value
70
71
72 parser = ArgumentParser(description=__doc__)
73 parser.add_argument("hostname")
74 args = parser.parse_args()
75
76 # Connect to libvirt
77 uri = "esx://%s/?no_verify=1" % args.hostname
78
79 # The auth argument is a list that contains 3 items:
80 # - a list of supported credential types
81 # - a callable that takes 2 arguments
82 # - user data that will be passed to the callable as second argument
83 #
84 # In this example the supported credential types are VIR_CRED_AUTHNAME and
85 # VIR_CRED_NOECHOPROMPT, the callable is the unbound method request_credentials
86 # (see above) and the user data is None.
87 #
88 # libvirt (actually the ESX driver) will call the callable to request
89 # credentials in order to log into the ESX host. The callable would also be
90 # called if the connection URI would reference a vCenter to request credentials
91 # in order to log into the vCenter
92 auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
93 request_credentials, None]
94 try:
95 conn = libvirt.openAuth(uri, auth, 0)
96 except libvirt.libvirtError:
97 print("Failed to open connection to %s" % args.hostname)
98 exit(1)
99
100 state_names = {
101 libvirt.VIR_DOMAIN_RUNNING: "running",
102 libvirt.VIR_DOMAIN_BLOCKED: "idle",
103 libvirt.VIR_DOMAIN_PAUSED: "paused",
104 libvirt.VIR_DOMAIN_SHUTDOWN: "in shutdown",
105 libvirt.VIR_DOMAIN_SHUTOFF: "shut off",
106 libvirt.VIR_DOMAIN_CRASHED: "crashed",
107 libvirt.VIR_DOMAIN_NOSTATE: "no state",
108 }
109
110 for id in conn.listDomainsID():
111 domain = conn.lookupByID(id)
112 info = domain.info()
113
114 print_section("Domain " + domain.name())
115 print_entry("ID:", id)
116 print_entry("UUID:", domain.UUIDString())
117 print_entry("State:", state_names[info[0]])
118 print_entry("MaxMem:", info[1])
119 print_entry("UsedMem:", info[2])
120 print_entry("VCPUs:", info[3])
121
122 # Read some info from the XML desc
123 print_section("Devices of " + domain.name())
124
125 xmldesc = domain.XMLDesc(0)
126 doc = libxml2.parseDoc(xmldesc)
127 ctx = doc.xpathNewContext()
128 devs = ctx.xpathEval("/domain/devices/*")
129 first = True
130
131 for d in devs:
132 ctx.setContextNode(d)
133
134 if not first:
135 print("------------------------------------------------------------")
136 else:
137 first = False
138
139 print_entry("Device", d.name)
140
141 type = print_xml("Type:", ctx, "@type")
142
143 if type == "file":
144 print_xml("Source:", ctx, "source/@file")
145 print_xml("Target:", ctx, "target/@dev")
146 elif type == "block":
147 print_xml("Source:", ctx, "source/@dev")
148 print_xml("Target:", ctx, "target/@dev")
149 elif type == "bridge":
150 print_xml("Source:", ctx, "source/@bridge")
151 print_xml("MAC Addr:", ctx, "mac/@address")