mirror of https://github.com/Kodomo/esxi-vm
199 lines
6.3 KiB
Python
Executable File
199 lines
6.3 KiB
Python
Executable File
#!/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)
|
|
|