-
Notifications
You must be signed in to change notification settings - Fork 39
/
esxi-vm-destroy
executable file
·224 lines (191 loc) · 6.31 KB
/
esxi-vm-destroy
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
#!/usr/bin/python
import argparse # Argument parser
import datetime # For current Date/Time
import time
import os.path # To check if file exists
import sys # For args
import re # For regex
import paramiko # For remote ssh
import yaml
import warnings
from esxi_vm_functions import *
# Defaults and Variable setup
ConfigData = setup_config()
NAME = ""
LOG = ConfigData['LOG']
isDryRun = ConfigData['isDryRun']
isVerbose = ConfigData['isVerbose']
isSummary = ConfigData['isSummary']
HOST = ConfigData['HOST']
USER = ConfigData['USER']
PASSWORD = ConfigData['PASSWORD']
CPU = ConfigData['CPU']
MEM = ConfigData['MEM']
HDISK = int(ConfigData['HDISK'])
DISKFORMAT = ConfigData['DISKFORMAT']
VIRTDEV = ConfigData['VIRTDEV']
STORE = ConfigData['STORE']
NET = ConfigData['NET']
ISO = ConfigData['ISO']
GUESTOS = ConfigData['GUESTOS']
ErrorMessages = ""
CheckHasErrors = False
DSPATH=""
DSSTORE=""
#
# Process Arguments
#
parser = argparse.ArgumentParser(description='ESXi Create VM utility.')
parser.add_argument("-H", "--Host", dest='HOST', type=str, help="ESXi Host/IP (" + str(HOST) + ")")
parser.add_argument("-U", "--User", dest='USER', type=str, help="ESXi Host username (" + str(USER) + ")")
parser.add_argument("-P", "--Password", dest='PASSWORD', type=str, help="ESXi Host password (*****)")
parser.add_argument("-n", "--name", dest='NAME', type=str, help="VM name")
parser.add_argument('-V', '--verbose', dest='isVerbosearg', action='store_true', help="Enable Verbose mode (" + str(isVerbose) + ")")
parser.add_argument('--summary', dest='isSummaryarg', action='store_true', help="Display Summary (" + str(isSummary) + ")")
args = parser.parse_args()
if args.isVerbosearg:
isVerbose = True
if args.isSummaryarg:
isSummary = True
if args.HOST:
HOST=args.HOST
if args.USER:
USER=args.USER
if args.PASSWORD:
PASSWORD=args.PASSWORD
if args.NAME:
NAME=args.NAME
#
# main()
#
LogOutput = '{'
LogOutput += '"datetime":"' + str(theCurrDateTime()) + '",'
if NAME == "":
print "ERROR: Missing required option --name"
sys.exit(1)
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(HOST, username=USER, password=PASSWORD)
(stdin, stdout, stderr) = ssh.exec_command("esxcli system version get |grep Version")
type(stdin)
if re.match("Version", str(stdout.readlines())) is not None:
print "Unable to determine if this is a ESXi Host: %s, username: %s" % (HOST, USER)
sys.exit(1)
except:
print "The Error is " + str(sys.exc_info()[0])
print "Unable to access ESXi Host: %s, username: %s" % (HOST, USER)
sys.exit(1)
#
# Check if VM exists
#
VMID = -1
try:
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/getallvms")
type(stdin)
for line in stdout.readlines():
splitLine = line.split()
if NAME == splitLine[1]:
VMID = splitLine[0]
JNK = line.split('[')[1]
STORE = JNK.split(']')[0]
VMDIR = splitLine[3]
if VMID == -1:
print "Warning: VM " + NAME + " doesn't exists."
ErrorMessages += " VM " + NAME + " doesn't exists."
CheckHasErrors = True
CheckHasWarnings = True
except:
print "The Error is " + str(sys.exc_info()[0])
sys.exit(1)
# Get List of Volumes,
try:
(stdin, stdout, stderr) = ssh.exec_command("esxcli storage filesystem list |grep '/vmfs/volumes/.*true VMFS' |sort -nk7")
type(stdin)
VOLUMES = {}
for line in stdout.readlines():
splitLine = line.split()
VOLUMES[splitLine[0]] = splitLine[1]
except:
print "The Error is " + str(sys.exc_info()[0])
sys.exit(1)
# Convert STORE to path and visa-versa
V = []
for Path in VOLUMES:
V.append(VOLUMES[Path])
if STORE == Path or STORE == VOLUMES[Path]:
DSPATH = Path
DSSTORE = VOLUMES[Path]
if CheckHasErrors:
Result = "Errors"
else:
Result = "Success"
if not CheckHasErrors:
try:
CurrentState = ""
CurrentStateCounter = 0
while CurrentState != "off":
if isVerbose:
print "Get state VM"
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.getstate " + str(VMID))
type(stdin)
lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose:
print "power.getstate: " + lines
if re.search("Powered off", lines):
CurrentState = "off"
# Power off VM
if isVerbose:
print "Power OFF VM"
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.off " + str(VMID) + " ||echo")
type(stdin)
lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose:
print "power.off: " + str(lines)
CurrentStateCounter += 1
if CurrentStateCounter >10:
break
time.sleep(1)
# destroy VM
if isVerbose:
print "Destroy VM"
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/destroy " + str(VMID))
type(stdin)
lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose:
print "destroy: " + str(lines)
except:
print "There was an error destroying the VM."
ErrorMessages += " There was an error destroying the VM."
CheckHasErrors = True
Result = "Fail"
# Print Summary
#
# The output log string
LogOutput += '"Host":"' + HOST + '",'
LogOutput += '"Name":"' + NAME + '",'
LogOutput += '"Store Used":"' + DSPATH + '",'
LogOutput += '"Verbose":"' + str(isVerbose) + '",'
if ErrorMessages != "":
LogOutput += '"Error Message":"' + ErrorMessages + '",'
LogOutput += '"Result":"' + Result + '",'
LogOutput += '"Completion Time":"' + str(theCurrDateTime()) + '"'
LogOutput += '}\n'
try:
with open(LOG, "a+w") as FD:
FD.write(LogOutput)
except:
print "Error writing to log file: " + LOG
if isSummary:
if isVerbose:
print "ESXi Host: " + HOST
print "VM NAME: " + NAME
print "Path: " + DSSTORE
else:
pass
if CheckHasErrors and not CheckHasWarnings:
print "Failed"
sys.exit(1)
else:
print "Success"
sys.exit(0)