forked from andrivet/esxi-vm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esxi-vm-destroy
executable file
·198 lines (168 loc) · 6.26 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
#!/usr/bin/python
import argparse # Argument parser
import time
from esxi_vm_functions import *
# Defaults and Variable setup
ConfigData = setup_config()
NAME = ""
LOG = ConfigData['LOG']
writeLog = ConfigData['writeLog']
isDryRun = ConfigData['isDryRun']
isVerbose = ConfigData['isVerbose']
isSummary = ConfigData['isSummary']
HOST = ConfigData['HOST']
PORT = ConfigData['PORT']
USER = ConfigData['USER']
PASSWORD = ConfigData['PASSWORD']
KEY = ConfigData['KEY']
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 Destroy VM utility.')
parser.add_argument("-H", "--Host", dest='HOST', type=str, help="ESXi Host/IP ({})".format(HOST))
parser.add_argument("-T", "--Port", dest='PORT', type=int, help="ESXi Port number ({})".format(PORT))
parser.add_argument("-U", "--User", dest='USER', type=str, help="ESXi Host username ({})".format(USER))
parser.add_argument("-P", "--Password", dest='PASSWORD', type=str, help="ESXi Host password (*****)")
parser.add_argument("-K", "--Key", dest='KEY', type=str, help="ESXi Host path to private key ({})".format(KEY))
parser.add_argument("-n", "--name", dest='NAME', type=str, help="VM name ()".format(NAME))
parser.add_argument('-V', '--verbose', dest='isVerbosearg', action='store_true', help="Enable Verbose mode ({})".format(isVerbose))
parser.add_argument('-f', '--logfile', dest='LOG', type=str, help='Path to the log file ({})'.format(LOG))
parser.add_argument('-l', '--log', dest='writeLog', action='store_true', help='Write to log file ({})'.format(writeLog))
parser.add_argument('--summary', dest='isSummaryarg', action='store_true', help="Display Summary ({})".format(isSummary))
args = parser.parse_args()
if args.isVerbosearg:
isVerbose = True
if args.LOG:
LOG = args.LOG
if args.LOG or args.writeLog:
writeLog = True
if args.isSummaryarg:
isSummary = True
if args.HOST:
HOST = args.HOST
if args.PORT:
PORT = args.PORT
if args.USER:
USER = args.USER
if args.PASSWORD:
PASSWORD = args.PASSWORD
if args.KEY:
KEY = args.KEY
if args.NAME:
NAME = args.NAME
if NAME == "":
print("ERROR: Missing required option --name")
sys.exit(1)
LogOutput = '{'
LogOutput += '"datetime":"{}",'.format(the_current_date_time())
ssh = connect_to_esxi(HOST, PORT, USER, PASSWORD, KEY, isVerbose)
VMID = -1
CheckHasWarnings = False
try:
(stdin, stdout, stderr) = exec_ssh_command("Get list of VMs", "vim-cmd vmsvc/getallvms", ssh, isVerbose)
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 {} doesn't exists.".format(NAME))
ErrorMessages += " VM " + NAME + " doesn't exists."
CheckHasErrors = True
CheckHasWarnings = True
except Exception as e:
print("The Error is {}".format(e))
sys.exit(1)
try:
(stdin, stdout, stderr) = \
exec_ssh_command("Get List of Volumes",
"esxcli storage filesystem list |grep '/vmfs/volumes/.*true VMFS' |sort -nk7",
ssh, isVerbose)
type(stdin)
VOLUMES = {}
for line in stdout.readlines():
splitLine = line.split()
VOLUMES[splitLine[0]] = splitLine[1]
except Exception as e:
print("The Error is {}".format(e))
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:
for i in range(0, 10):
(stdin, stdout, stderr) = exec_ssh_command("Get state of VM",
"vim-cmd vmsvc/power.getstate {}".format(VMID),
ssh, isVerbose)
lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose:
print("power.getstate: {}".format(lines))
if re.search("Powered off", lines):
break
(stdin, stdout, stderr) = exec_ssh_command("Power OFF VM",
"vim-cmd vmsvc/power.off {} ||echo".format(VMID),
ssh, isVerbose)
lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose:
print("power.off: {}".format(lines))
time.sleep(1)
(stdin, stdout, stderr) = exec_ssh_command("Destroy VM",
"vim-cmd vmsvc/destroy {}".format(VMID),
ssh, isVerbose)
lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose:
print("destroy: {}".format(lines))
except Exception as e:
print("There was an error destroying the VM: {}".format(e))
ErrorMessages += " There was an error destroying the VM: {}".format(e)
CheckHasErrors = True
Result = "Fail"
LogOutput += '"Host":"{}","Name":"{}","Store Used":"{}","Verbose":"{}"'.format(HOST, NAME, DSPATH, isVerbose)
if ErrorMessages != "":
LogOutput += '"Error Message":"{}",'.format(ErrorMessages)
LogOutput += '"Result":"{}","Completion Time":"{}"'.format(Result, the_current_date_time())
LogOutput += '}\n'
if writeLog:
try:
with open(LOG, "a") as FD:
FD.write(LogOutput)
except Exception as e:
print("Error writing to log file: {}".format(e))
if isSummary:
if isVerbose:
print("ESXi Host: {}".format(HOST))
print("VM NAME: {}".format(NAME))
print("Path: {}".format(DSSTORE))
else:
pass
if CheckHasErrors and not CheckHasWarnings:
print("Failed")
sys.exit(1)
else:
print("Success")
sys.exit(0)