-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathvSphereWebServicesAPI_Manage.py
444 lines (352 loc) · 19 KB
/
vSphereWebServicesAPI_Manage.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
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
433
434
435
436
437
438
439
440
441
442
443
444
#python3
import os
import sys
import re
import requests
from pyVmomi import vmodl, vim
from pyVim.connect import SmartConnect, Disconnect
import warnings
warnings.filterwarnings("ignore")
def print_vm_info(virtual_machine):
summary = virtual_machine.summary
print("Name : ", summary.config.name)
print("Template : ", summary.config.template)
print("Path : ", summary.config.vmPathName)
print("Guest : ", summary.config.guestFullName)
print("Instance UUID : ", summary.config.instanceUuid)
print("Bios UUID : ", summary.config.uuid)
annotation = summary.config.annotation
if annotation:
print("Annotation : ", annotation)
print("State : ", summary.runtime.powerState)
if summary.guest is not None:
ip_address = summary.guest.ipAddress
tools_version = summary.guest.toolsStatus
if tools_version is not None:
print("VMware-tools: ", tools_version)
else:
print("Vmware-tools: None")
if ip_address:
print("IP : ", ip_address)
else:
print("IP : None")
if summary.runtime.question is not None:
print("Question : ", summary.runtime.question.text)
print("")
def search_for_obj(content, vim_type, name, folder=None, recurse=True):
"""
Search the managed object for the name and type specified
Sample Usage:
get_obj(content, [vim.Datastore], "Datastore Name")
"""
if folder is None:
folder = content.rootFolder
obj = None
container = content.viewManager.CreateContainerView(folder, vim_type, recurse)
for managed_object_ref in container.view:
if managed_object_ref.name == name:
obj = managed_object_ref
break
container.Destroy()
return obj
def get_obj(content, vim_type, name, folder=None, recurse=True):
"""
Retrieves the managed object for the name and type specified
Throws an exception if of not found.
Sample Usage:
get_obj(content, [vim.Datastore], "Datastore Name")
"""
obj = search_for_obj(content, vim_type, name, folder, recurse)
if not obj:
raise RuntimeError("Managed Object " + name + " not found.")
return obj
def List_VM(api_host, username, password):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
try:
content = service_instance.RetrieveContent()
container = content.rootFolder # starting point to look into
view_type = [vim.VirtualMachine] # object types to look for
recursive = True # whether we should look into it recursively
container_view = content.viewManager.CreateContainerView(
container, view_type, recursive)
children = container_view.view
for child in children:
print_vm_info(child)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def Get_VM(api_host, username, password, vm_name):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
try:
content = service_instance.RetrieveContent()
container = content.rootFolder # starting point to look into
view_type = [vim.VirtualMachine] # object types to look for
recursive = True # whether we should look into it recursively
container_view = content.viewManager.CreateContainerView(
container, view_type, recursive)
children = container_view.view
pat = re.compile(vm_name, re.IGNORECASE)
for child in children:
if pat.search(child.summary.config.name) is not None:
print_vm_info(child)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def List_Host(api_host, username, password):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
try:
content = service_instance.RetrieveContent()
container = content.rootFolder # starting point to look into
view_type = [vim.HostSystem] # object types to look for
recursive = True # whether we should look into it recursively
container_view = content.viewManager.CreateContainerView(
container, view_type, recursive)
children = container_view.view
for child in children:
#print(child.summary)
print(" - host:" + str(child.summary.host))
print(" name:" + child.summary.config.name)
print(" connection_state:" + child.summary.runtime.connectionState)
print(" power_state:" + child.summary.runtime.powerState)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def ListVMProcess(api_host, username, password, vm_name, guest_username, guest_user_password):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
creds = vim.vm.guest.NamePasswordAuthentication(username=guest_username, password=guest_user_password)
try:
content = service_instance.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], vm_name)
if not vm:
raise SystemExit("Unable to locate the virtual machine.")
profile_manager = content.guestOperationsManager.processManager
res = profile_manager.ListProcessesInGuest(vm, creds)
for i in res:
print(" - name:" + i.name)
print(" cmdLine:" + i.cmdLine)
print(" pid:" + str(i.pid))
print(" owner:" + i.owner)
print(" startTime:" + str(i.startTime))
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def CreateVMProcess(api_host, username, password, vm_name, guest_username, guest_user_password, path, arguments):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
creds = vim.vm.guest.NamePasswordAuthentication(username = guest_username, password = guest_user_password)
program_spec = vim.vm.guest.ProcessManager.ProgramSpec(programPath = path, arguments = arguments)
try:
content = service_instance.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], vm_name)
if not vm:
raise SystemExit("Unable to locate the virtual machine.")
profile_manager = content.guestOperationsManager.processManager
res = profile_manager.StartProgramInGuest(vm, creds, program_spec)
print("[+] Process Pid:" + str(res))
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def KillVMProcess(api_host, username, password, vm_name, guest_username, guest_user_password, pid):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
creds = vim.vm.guest.NamePasswordAuthentication(username = guest_username, password = guest_user_password)
try:
content = service_instance.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], vm_name)
if not vm:
raise SystemExit("Unable to locate the virtual machine.")
profile_manager = content.guestOperationsManager.processManager
res = profile_manager.TerminateProcessInGuest(vm, creds, int(pid))
if res == None:
print("[+] Kill process success")
else:
print(res)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def ListVMFolder(api_host, username, password, vm_name, guest_username, guest_user_password, path):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
creds = vim.vm.guest.NamePasswordAuthentication(username = guest_username, password = guest_user_password)
try:
content = service_instance.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], vm_name)
if not vm:
raise SystemExit("Unable to locate the virtual machine.")
profile_manager = content.guestOperationsManager.fileManager
res = profile_manager.ListFilesInGuest(vm, creds, path)
for i in res.files:
print(" - path:" + i.path)
print(" size:" + str(i.size))
print(" type:" + i.type)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def DeleteVMFile(api_host, username, password, vm_name, guest_username, guest_user_password, path):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
creds = vim.vm.guest.NamePasswordAuthentication(username = guest_username, password = guest_user_password)
try:
content = service_instance.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], vm_name)
if not vm:
raise SystemExit("Unable to locate the virtual machine.")
profile_manager = content.guestOperationsManager.fileManager
res = profile_manager.DeleteFileInGuest(vm, creds, path)
if res == None:
print("[+] Delete file success")
else:
print(res)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def DownloadFileFromVM(api_host, username, password, vm_name, guest_username, guest_user_password, guest_path, type):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
creds = vim.vm.guest.NamePasswordAuthentication(username = guest_username, password = guest_user_password)
try:
content = service_instance.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], vm_name)
if not vm:
raise SystemExit("Unable to locate the virtual machine.")
profile_manager = content.guestOperationsManager.fileManager
res = profile_manager.InitiateFileTransferFromGuest(vm, creds, guest_path)
print("[+] transfer uri: " + res.url)
print(" size: " + str(res.size))
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
}
r = requests.get(res.url, headers = headers, verify = False)
if r.status_code ==200:
if type == "text":
print("[+] result: ")
print(r.text)
else:
print("[+] save the result as temp.bin")
with open("temp.bin", "wb") as file_obj:
file_obj.write(r.content)
else:
print("[!]" + str(r.status_code))
print(r.text)
exit(0)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
def UploadFileToVM(api_host, username, password, vm_name, guest_username, guest_user_password, local_path, guest_path):
service_instance = SmartConnect(host=api_host, user=username, pwd=password, port=443, disableSslCertValidation=True)
if not service_instance:
raise SystemExit("[!] Unable to connect to host with supplied credentials.")
creds = vim.vm.guest.NamePasswordAuthentication(username = guest_username, password = guest_user_password)
with open(local_path, 'rb') as file_obj:
data_to_send = file_obj.read()
try:
content = service_instance.RetrieveContent()
vm = get_obj(content, [vim.VirtualMachine], vm_name)
if not vm:
raise SystemExit("Unable to locate the virtual machine.")
file_attribute = vim.vm.guest.FileManager.FileAttributes()
profile_manager = content.guestOperationsManager.fileManager
res = profile_manager.InitiateFileTransferToGuest(vm, creds, guest_path, file_attribute, len(data_to_send), True)
print("[+] transfer uri: " + res)
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
}
r = requests.put(res, headers = headers, data = data_to_send, verify = False)
if r.status_code ==200:
print("[+] " + r.text)
else:
print("[!]" + str(r.status_code))
print(r.text)
exit(0)
except vmodl.MethodFault as error:
print("[!] Caught vmodl fault : " + error.msg)
if __name__ == "__main__":
if len(sys.argv)!=5:
print("vSphereWebServicesAPI_Manage.py")
print("Use vSphere Web Services API to manage the VM")
print("Reference: https://github.com/vmware/pyvmomi/")
print("Install: pip install --upgrade pyvmomi")
print("Usage:")
print("%s <vCenter IP> <vCenter user> <vCenter password> <mode>"%(sys.argv[0]))
print("mode:")
print("- ListVM")
print("- GetVMConfig")
print("- ListHost")
print("- ListVMProcess")
print("- CreateVMProcess")
print("- KillVMProcess")
print("- ListVMFolder")
print("- DeleteVMFile")
print("- DownloadFileFromVM")
print("- UploadFileToVM")
print("Eg.")
print("%s 192.168.1.1 [email protected] 123456 ListVM"%(sys.argv[0]))
sys.exit(0)
else:
if sys.argv[4] == "ListVM":
print("[*] Try to list the VM")
List_VM(sys.argv[1], sys.argv[2], sys.argv[3])
elif sys.argv[4] == "ListHost":
print("[*] Try to list the Host")
List_Host(sys.argv[1], sys.argv[2], sys.argv[3])
elif sys.argv[4] == "GetVMConfig":
print("[*] Try to get the config of the VM")
vm = input("input the name of the VM(eg:Win7): ")
Get_VM(sys.argv[1], sys.argv[2], sys.argv[3], vm)
elif sys.argv[4] == "ListVMProcess":
print("[*] Try to list the processes of the VM")
vm = input("input the name of the VM(eg:Win7): ")
guest_username = input("input the user name of the VM: ")
guest_user_password = input("input the password of the VM: ")
ListVMProcess(sys.argv[1], sys.argv[2], sys.argv[3], vm, guest_username, guest_user_password)
elif sys.argv[4] == "CreateVMProcess":
print("[*] Try to create the process of the VM")
vm = input("input the name of the VM(eg:Win7): ")
guest_username = input("input the user name of the VM: ")
guest_user_password = input("input the password of the VM: ")
program_path = input("input the path of the program(eg:c:\\windows\\system32\\cmd.exe): ")
program_arguments = input("input the arguments of the program(eg:/c echo 1 >c:\\1.txt): ")
CreateVMProcess(sys.argv[1], sys.argv[2], sys.argv[3], vm, guest_username, guest_user_password, program_path, program_arguments)
elif sys.argv[4] == "KillVMProcess":
print("[*] Try to kill the process of the VM")
vm = input("input the name of the VM(eg:Win7): ")
guest_username = input("input the user name of the VM: ")
guest_user_password = input("input the password of the VM: ")
pid = input("input the pid: ")
KillVMProcess(sys.argv[1], sys.argv[2], sys.argv[3], vm, guest_username, guest_user_password, pid)
elif sys.argv[4] == "ListVMFolder":
print("[*] Try to list the file of the VM")
vm = input("input the name of the VM(eg:Win7): ")
guest_username = input("input the user name of the VM: ")
guest_user_password = input("input the password of the VM: ")
folder_path = input("input the folder(eg: c:\\1): ")
ListVMFolder(sys.argv[1], sys.argv[2], sys.argv[3], vm, guest_username, guest_user_password, folder_path)
elif sys.argv[4] == "DeleteVMFile":
print("[*] Try to delete the file of the VM")
vm = input("input the name of the VM(eg:Win7): ")
guest_username = input("input the user name of the VM: ")
guest_user_password = input("input the password of the VM: ")
file_path = input("input the file(eg: c:\\1.txt): ")
DeleteVMFile(sys.argv[1], sys.argv[2], sys.argv[3], vm, guest_username, guest_user_password, file_path)
elif sys.argv[4] == "DownloadFileFromVM":
print("[*] Try to download the file of the VM")
vm = input("input the name of the VM(eg:Win7): ")
guest_username = input("input the user name of the VM: ")
guest_user_password = input("input the password of the VM: ")
file_path = input("input the file of the VM(eg: c:\\1.txt or /tmp/1.txt): ")
file_type = input("input the file type(text or raw): ")
DownloadFileFromVM(sys.argv[1], sys.argv[2], sys.argv[3], vm, guest_username, guest_user_password, file_path, file_type)
elif sys.argv[4] == "UploadFileToVM":
print("[*] Try to upload the file to the VM")
vm = input("input the name of the VM(eg:Win7): ")
guest_username = input("input the user name of the VM: ")
guest_user_password = input("input the password of the VM: ")
local_file_path = input("input the local file(eg: c:\\1.txt or /tmp/1.txt): ")
target_file_path = input("input the target file(eg: c:\\1.txt or /tmp/1.txt): ")
UploadFileToVM(sys.argv[1], sys.argv[2], sys.argv[3], vm, guest_username, guest_user_password, local_file_path, target_file_path)
else:
print("[!] Wrong parameter")