forked from doccaz/kvm-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qemuguest
executable file
·434 lines (350 loc) · 13.8 KB
/
qemuguest
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/python
import sys
import time
import base64
import subprocess
import json
from subprocess import check_output, CalledProcessError
from subprocess import PIPE
import getopt
def getOSVersion(vm_name):
osInfoCMD = {
"execute":"guest-get-osinfo"
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(osInfoCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error getting guest agent OS Info: %s' % e)
return "no OS information available"
return json.loads(cmd_result)['return']
def guestExec(vm_name, cmd, args):
execCMD = {
"execute":"guest-exec",
"arguments":{
"path": cmd,
"arg": args,
"capture-output":True
}
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(execCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error executing command')
return (-1, 'error executing command')
pid = json.loads(cmd_result)['return']['pid']
print('Command execution returned PID=%s' % pid)
time.sleep(2)
resultCMD = {
"execute":"guest-exec-status",
"arguments":{
"pid":pid
}
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(resultCMD)]
cmd_result = subprocess.check_output(cmd_list)
#print('command output: %s' % cmd_result)
except CalledProcessError as e:
print('Error executing command')
return (-1, '')
ret = json.loads(cmd_result)['return']['exitcode']
print('Command execution returned RC=%s' % ret)
try:
output = json.loads(cmd_result)['return']['out-data']
except KeyError:
output = ''
#print("Command output: [%s]" % output)
decoded_output = base64.b64decode(output).decode("utf-8")
#print("Decoded output: [%s]" % (decoded_output))
return (ret, decoded_output)
def guestSetPassword(vm_name, username, password):
execCMD = {
"execute":"guest-set-user-password",
"arguments":{
"username": username,
"password": base64.encodestring(password.encode('ascii')).decode('ascii'),
"crypted":False
}
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(execCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error executing command')
return False
output = json.loads(cmd_result)
#print('Command execution returned [%s]' % output)
if output['return'] == {}:
return True
else:
print('error changing password: [%s]' % output)
return False
def readFileFromVM(vm_name, filename):
file_handle = -1
fileOpenCMD = {
"execute":"guest-file-open",
"arguments":{
"path":"%s" % filename
}
}
# get the file handle first
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(fileOpenCMD)]
try:
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
# print('Error while opening file from VM: %s' % e)
return ""
file_handle = json.loads(cmd_result)['return']
#print("file handle: %s" % file_handle)
if file_handle <= 0:
print('Invalid handle while opening file from VM')
return ""
# command structures with the file handle
fileReadCMD = {
"execute":"guest-file-read",
"arguments":{
"handle": file_handle,
"count":65535
}
}
fileCloseCMD = {
"execute":"guest-file-close",
"arguments":{
"handle":file_handle
}
}
# we have a valid file handle, let's get the contents
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(fileReadCMD)]
try:
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error while getting file contents from VM')
return ""
file_contents = json.loads(cmd_result)['return']['buf-b64']
file_size = json.loads(cmd_result)['return']['count']
print("Received file %s (%d bytes)" % (filename, file_size))
decoded_file = base64.b64decode(file_contents)
#print("Decoded content: [%s]" % (decoded_file))
# now we need to close the file handle
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(fileCloseCMD)]
try:
cmd_result = subprocess.check_output(cmd_list)
#print("Close file handle %s: %s" % (file_handle, json.loads(cmd_result)['return']))
except CalledProcessError as e:
print('Error while closing file handle: %s' % e)
return decoded_file
def writeFileToVM(vm_name, local_file, remote_file):
file_handle = -1
fileOpenCMD = {
"execute":"guest-file-open",
"arguments":{
"path":"%s" % remote_file,
"mode":"w"
}
}
# read local file contents
try:
with open(local_file, 'rb') as f:
file_contents = base64.b64encode(f.read())
except Exception as e:
print('Error [%s] opening local file: %s ' % (str(e), local_file))
return -1
print("Sending file %s to %s" % (local_file, remote_file))
# get the file handle first
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(fileOpenCMD)]
try:
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error while opening file from VM: %s' % e)
return -1
file_handle = json.loads(cmd_result)['return']
#print("file handle: %s" % file_handle)
if file_handle <= 0:
print('Invalid handle while opening file from VM')
return ""
# command structures with the file handle
fileWriteCMD = {
"execute":"guest-file-write",
"arguments":{
"handle": file_handle,
"buf-b64":file_contents
}
}
fileCloseCMD = {
"execute":"guest-file-close",
"arguments":{
"handle":file_handle
}
}
# we have a valid file handle, let's write the contents
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(fileWriteCMD)]
try:
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error while writing file to VM: ' + str(e))
return ""
#print("Return: [%s]" % (cmd_result))
bytes_written = json.loads(cmd_result)['return']['count']
# now we need to close the file handle
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(fileCloseCMD)]
try:
cmd_result = subprocess.check_output(cmd_list)
#print("Close file handle %s: %s" % (file_handle, json.loads(cmd_result)['return']))
except CalledProcessError as e:
print('Error while closing file handle: %s' % e)
return bytes_written
def getNetworkInterfaces(vm_name):
execCMD = {
"execute":"guest-network-get-interfaces",
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(execCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error executing command')
return (-1, 'error executing command')
output = json.loads(cmd_result)
#print("Command output: [%s]" % output)
return output['return']
def getHostname(vm_name):
execCMD = {
"execute":"guest-get-host-name",
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(execCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error executing command')
return (-1, 'error executing command')
output = json.loads(cmd_result)
#print("Command output: [%s]" % output)
return output['return']['host-name']
def getVCPUs(vm_name):
execCMD = {
"execute":"guest-get-vcpus",
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(execCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error executing command')
return (-1, 'error executing command')
output = json.loads(cmd_result)
#print("Command output: [%s]" % output)
return output['return']
def pingAgent(vm_name):
execCMD = {
"execute":"guest-ping",
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(execCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
return False
output = json.loads(cmd_result)
return True
def getFilesystems(vm_name):
execCMD = {
"execute":"guest-get-fsinfo",
}
try:
cmd_list = ['virsh', '-c', 'qemu:///system', 'qemu-agent-command', vm_name, json.dumps(execCMD)]
cmd_result = subprocess.check_output(cmd_list)
except CalledProcessError as e:
print('Error executing command')
return (-1, 'error executing command')
output = json.loads(cmd_result)
#print("Command output: [%s]" % output)
return output['return']
def usage():
print('qemuguest [-n <VM name>] [-h|--help] [-e|--exec <command to execute>] [-i|--info] [--changepassword|-p <username:password>] [-f|--filesystems] [-u|--upload <local file>:<remote file>] [-d|--download <remote file>]')
return
def checkPreReqs(vm_name):
if vm_name == '':
print('Must provide a VM name.')
usage()
sys.exit()
if pingAgent(vm_name) is False:
print('Guest Agent not responding on VM: ' + vm_name)
sys.exit()
return
def main(argv):
try:
opts, args = getopt.getopt(argv,"hn:ie:p:ifd:u:",["help","vm=","info","exec=","changepassword=","filesystems","download=","upload="])
except getopt.GetoptError:
usage()
sys.exit(2)
if len(argv) == 0:
usage()
sys.exit()
vm_name = ''
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-n", "--vm"):
vm_name = arg
elif opt in ("-i", "--info"):
checkPreReqs(vm_name)
print('---- System information ----\n')
print('Host name: ' + str(getHostname(vm_name)))
for cpu in getVCPUs(vm_name):
status = "online" if cpu['online'] else "offline"
print('vCPU ' + str(cpu['logical-id']) + ': ' + status)
print('\n---- OS information ----\n')
osinfo = getOSVersion(vm_name)
for k in osinfo.keys():
print(k + ': ' + osinfo[k])
print('\n---- Network Interfaces ----\n')
for nic in getNetworkInterfaces(vm_name):
print(nic['name'] + ' (mac: ' + nic['hardware-address'] + ')')
for ip in nic['ip-addresses']:
print('\t' + ip['ip-address'] + '/' + str(ip['prefix']) + ' (' + ip['ip-address-type'] + ')')
elif opt in ("-f", "--filesystems"):
checkPreReqs(vm_name)
print('---- Filesystem information ----\n')
filesystems = getFilesystems(vm_name)
for fs in filesystems:
print('Device: %s (%s)' % (fs['name'], fs['disk'][0]['serial']))
print('Mount point: %s' % fs['mountpoint'])
print('File system: %s' % fs['type'])
print('Used bytes: %d MiB (Total: %d MiB)' % (fs['used-bytes']/1024/1024, fs['total-bytes']/1024/1024))
print('\n')
elif opt in ("-e", "--exec"):
checkPreReqs(vm_name)
cmds = arg.split()
command = cmds[0]
cmds.remove(cmds[0])
args = cmds
ret,output = guestExec(vm_name, command, args)
print('exec rc = %s, output=[%s]' % (ret, output))
elif opt in ("-p", "--changepass"):
checkPreReqs(vm_name)
params = arg.split(':')
output = guestSetPassword(vm_name, params[0], params[1])
print('set password = [%s]' % output)
elif opt in ("-d", "--download"):
checkPreReqs(vm_name)
params = arg.split(':')
if len(params) != 2:
print('You need to supply a remote filename and a local file name.')
print('e.g.: <remote file>:<local file>')
sys.exit()
file_contents = readFileFromVM(vm_name, params[0])
if file_contents == '':
print('returned content is null, will not write file.')
sys.exit(1)
with open(params[1], 'w') as f:
f.write(file_contents)
elif opt in ("-u", "--upload"):
checkPreReqs(vm_name)
params = arg.split(':')
if len(params) != 2:
print('You need to supply a local filename and a remote file name.')
print('e.g.: <local file>:<remote file>')
sys.exit()
print('Total bytes written: %d' % writeFileToVM(vm_name, params[0], params[1]))
if __name__ == "__main__":
main(sys.argv[1:])