mirror of https://github.com/Kodomo/esxi-vm
Migrate to Python 3 (print function)
parent
6ecf4d7fbc
commit
f9f1d16251
106
esxi-vm-create
106
esxi-vm-create
|
@ -1,6 +1,5 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
|
||||
import argparse # Argument parser
|
||||
import re # For regex
|
||||
import paramiko # For remote ssh
|
||||
|
@ -115,7 +114,7 @@ if args.VMXOPTS and args.VMXOPTS != 'NIL':
|
|||
|
||||
|
||||
if args.UPDATE:
|
||||
print "Saving new Defaults to ~/.esxi-vm.yml"
|
||||
print("Saving new Defaults to ~/.esxi-vm.yml")
|
||||
ConfigData['isDryRun'] = isDryRun
|
||||
ConfigData['isVerbose'] = isVerbose
|
||||
ConfigData['isSummary'] = isSummary
|
||||
|
@ -145,7 +144,7 @@ LogOutput = '{'
|
|||
LogOutput += '"datetime":"' + str(the_current_date_time()) + '",'
|
||||
|
||||
if NAME == "":
|
||||
print "ERROR: Missing required option --name"
|
||||
print("ERROR: Missing required option --name")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
|
@ -156,11 +155,11 @@ try:
|
|||
(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, port: %s, username: %s" % (HOST, PORT, USER)
|
||||
print("Unable to determine if this is a ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER))
|
||||
sys.exit(1)
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
print "Unable to access ESXi Host: %s, port: %s, username: %s" % (HOST, PORT, USER)
|
||||
print("The Error is " + str(sys.exc_info()[0]))
|
||||
print("Unable to access ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER))
|
||||
sys.exit(1)
|
||||
|
||||
#
|
||||
|
@ -176,7 +175,7 @@ try:
|
|||
VOLUMES[splitLine[0]] = splitLine[1]
|
||||
LeastUsedDS = splitLine[1]
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
print("The Error is {}".format(sys.exc_info()[0]))
|
||||
sys.exit(1)
|
||||
|
||||
if STORE == "LeastUsed":
|
||||
|
@ -192,10 +191,10 @@ try:
|
|||
type(stdin)
|
||||
VMNICS = []
|
||||
for line in stdout.readlines():
|
||||
splitLine = re.split(',|\n', line)
|
||||
splitLine = re.split('[,\n]', line)
|
||||
VMNICS.append(splitLine[0])
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
print("The Error is {}".format(sys.exc_info()[0]))
|
||||
sys.exit(1)
|
||||
|
||||
#
|
||||
|
@ -210,7 +209,7 @@ if MAC != "":
|
|||
elif re.compile(MACregex).search("00:50:56:" + MAC):
|
||||
MAC = "00:50:56:" + MAC.replace("-", ":")
|
||||
else:
|
||||
print "ERROR: " + MAC + " Invalid MAC address."
|
||||
print("ERROR: {} Invalid MAC address.".format(MAC))
|
||||
ErrorMessages += " " + MAC + " Invalid MAC address."
|
||||
CheckHasErrors = True
|
||||
|
||||
|
@ -225,12 +224,13 @@ if ISO != "":
|
|||
try:
|
||||
# If ISO has no "/", try to find the ISO
|
||||
if not re.match('/', ISO):
|
||||
(stdin, stdout, stderr) = ssh.exec_command("find /vmfs/volumes/ -type f -name " + ISO +
|
||||
" -exec sh -c 'echo $1; kill $PPID' sh {} 2>/dev/null \;")
|
||||
(stdin, stdout, stderr) = \
|
||||
ssh.exec_command("find /vmfs/volumes/ -type f -name " + ISO +
|
||||
" -exec sh -c 'echo $1; kill $PPID' sh {} 2>/dev/null \;")
|
||||
type(stdin)
|
||||
FoundISOPath = str(stdout.readlines()[0]).strip('\n')
|
||||
if isVerbose:
|
||||
print "FoundISOPath: " + str(FoundISOPath)
|
||||
print("FoundISOPath: {}".format(FoundISOPath))
|
||||
ISO = str(FoundISOPath)
|
||||
|
||||
(stdin, stdout, stderr) = ssh.exec_command("ls " + str(ISO))
|
||||
|
@ -239,7 +239,7 @@ if ISO != "":
|
|||
ISOfound = True
|
||||
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
print("The Error is {}".format(sys.exc_info()[0]))
|
||||
sys.exit(1)
|
||||
|
||||
#
|
||||
|
@ -253,12 +253,12 @@ try:
|
|||
splitLine = line.split()
|
||||
if NAME == splitLine[1]:
|
||||
VMID = splitLine[0]
|
||||
print "ERROR: VM " + NAME + " already exists."
|
||||
print("ERROR: VM {} already exists.".format(NAME))
|
||||
ErrorMessages += " VM " + NAME + " already exists."
|
||||
CheckHasErrors = True
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
sys.exit(1)
|
||||
print("The Error is {}".format(sys.exc_info()[0]))
|
||||
sys.exit(1)
|
||||
|
||||
#
|
||||
# Do checks here
|
||||
|
@ -266,19 +266,19 @@ except:
|
|||
|
||||
# Check CPU
|
||||
if CPU < 1 or CPU > 128:
|
||||
print str(CPU) + " CPU out of range. [1-128]."
|
||||
print("{} CPU out of range. [1-128].".format(CPU))
|
||||
ErrorMessages += " " + str(CPU) + " CPU out of range. [1-128]."
|
||||
CheckHasErrors = True
|
||||
|
||||
# Check MEM
|
||||
if MEM < 1 or MEM > 4080:
|
||||
print str(MEM) + "GB Memory out of range. [1-4080]."
|
||||
print("{} GB Memory out of range. [1-4080].".format(MEM))
|
||||
ErrorMessages += " " + str(MEM) + "GB Memory out of range. [1-4080]."
|
||||
CheckHasErrors = True
|
||||
|
||||
# Check HDISK
|
||||
if HDISK < 1 or HDISK > 63488:
|
||||
print "Virtual Disk size " + str(HDISK) + "GB out of range. [1-63488]."
|
||||
print("Virtual Disk size {} GB out of range. [1-63488].".format(HDISK))
|
||||
ErrorMessages += " Virtual Disk size " + str(HDISK) + "GB out of range. [1-63488]."
|
||||
CheckHasErrors = True
|
||||
|
||||
|
@ -291,22 +291,22 @@ for Path in VOLUMES:
|
|||
DSSTORE = VOLUMES[Path]
|
||||
|
||||
if DSSTORE not in V:
|
||||
print "ERROR: Disk Storage " + STORE + " doesn't exist. "
|
||||
print " Available Disk Stores: " + str([str(item) for item in V])
|
||||
print " LeastUsed Disk Store : " + str(LeastUsedDS)
|
||||
print("ERROR: Disk Storage {} doesn't exist. ".format(STORE))
|
||||
print(" Available Disk Stores: {}".format([str(item) for item in V]))
|
||||
print(" LeastUsed Disk Store : {}".format(LeastUsedDS))
|
||||
ErrorMessages += " Disk Storage " + STORE + " doesn't exist. "
|
||||
CheckHasErrors = True
|
||||
|
||||
# Check NIC (NIC record)
|
||||
if (NET not in VMNICS) and (NET != "None"):
|
||||
print "ERROR: Virtual NIC " + NET + " doesn't exist."
|
||||
print " Available VM NICs: " + str([str(item) for item in VMNICS]) + " or 'None'"
|
||||
print("ERROR: Virtual NIC {} doesn't exist.".format(NET))
|
||||
print(" Available VM NICs: {} or 'None'".format([str(item) for item in VMNICS]))
|
||||
ErrorMessages += " Virtual NIC " + NET + " doesn't exist."
|
||||
CheckHasErrors = True
|
||||
|
||||
# Check ISO exists
|
||||
if ISO != "" and not ISOfound:
|
||||
print "ERROR: ISO " + ISO + " not found. Use full path to ISO"
|
||||
print("ERROR: ISO {} not found. Use full path to ISO".format(ISO))
|
||||
ErrorMessages += " ISO " + ISO + " not found. Use full path to ISO"
|
||||
CheckHasErrors = True
|
||||
|
||||
|
@ -316,7 +316,7 @@ try:
|
|||
(stdin, stdout, stderr) = ssh.exec_command("ls -d " + FullPath)
|
||||
type(stdin)
|
||||
if stdout.readlines() and not stderr.readlines():
|
||||
print "ERROR: Directory " + FullPath + " already exists."
|
||||
print("ERROR: Directory {} already exists.".format(FullPath))
|
||||
ErrorMessages += " Directory " + FullPath + " already exists."
|
||||
CheckHasErrors = True
|
||||
except:
|
||||
|
@ -397,9 +397,9 @@ for VMXopt in VMXOPTS:
|
|||
vmx.append(key + " = " + value)
|
||||
|
||||
if isVerbose and VMXOPTS != '':
|
||||
print "VMX file:"
|
||||
print("VMX file:")
|
||||
for i in vmx:
|
||||
print i
|
||||
print(i)
|
||||
|
||||
MyVM = FullPath + "/" + NAME
|
||||
if CheckHasErrors:
|
||||
|
@ -412,7 +412,7 @@ if not isDryRun and not CheckHasErrors:
|
|||
|
||||
# Create NAME.vmx
|
||||
if isVerbose:
|
||||
print "Create " + NAME + ".vmx file"
|
||||
print("Create {}.vmx file".format(NAME))
|
||||
(stdin, stdout, stderr) = ssh.exec_command("mkdir " + FullPath)
|
||||
type(stdin)
|
||||
for line in vmx:
|
||||
|
@ -421,25 +421,25 @@ if not isDryRun and not CheckHasErrors:
|
|||
|
||||
# Create vmdk
|
||||
if isVerbose:
|
||||
print "Create " + NAME + ".vmdk file"
|
||||
print("Create {}.vmdk file".format(NAME))
|
||||
(stdin, stdout, stderr) = \
|
||||
ssh.exec_command("vmkfstools -c " + str(HDISK) + "G -d " + DISKFORMAT + " " + MyVM + ".vmdk")
|
||||
type(stdin)
|
||||
|
||||
# Register VM
|
||||
if isVerbose:
|
||||
print "Register VM"
|
||||
print("Register VM")
|
||||
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd solo/registervm " + MyVM + ".vmx")
|
||||
type(stdin)
|
||||
VMID = int(stdout.readlines()[0])
|
||||
|
||||
# Power on VM
|
||||
if isVerbose:
|
||||
print "Power ON VM"
|
||||
print("Power ON VM")
|
||||
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.on " + str(VMID))
|
||||
type(stdin)
|
||||
if stderr.readlines():
|
||||
print "Error Powering-on VM."
|
||||
print("Error Powering-on VM.")
|
||||
Result = "Fail"
|
||||
|
||||
# Get Generated MAC
|
||||
|
@ -450,7 +450,7 @@ if not isDryRun and not CheckHasErrors:
|
|||
GeneratedMAC = str(stdout.readlines()[0]).strip('\n"')
|
||||
|
||||
except:
|
||||
print "There was an error creating the VM."
|
||||
print("There was an error creating the VM.")
|
||||
ErrorMessages += " There was an error creating the VM."
|
||||
Result = "Fail"
|
||||
|
||||
|
@ -485,40 +485,40 @@ try:
|
|||
with open(LOG, "a+w") as FD:
|
||||
FD.write(LogOutput)
|
||||
except:
|
||||
print "Error writing to log file: " + LOG
|
||||
print("Error writing to log file: {}".format(LOG))
|
||||
|
||||
if isSummary:
|
||||
if isDryRun:
|
||||
print "\nDry Run summary:"
|
||||
print("\nDry Run summary:")
|
||||
else:
|
||||
print "\nCreate VM Success:"
|
||||
print("\nCreate VM Success:")
|
||||
|
||||
if isVerbose:
|
||||
print "ESXi Host: " + HOST
|
||||
print "ESXi Port: " + PORT
|
||||
print "VM NAME: " + NAME
|
||||
print "vCPU: " + str(CPU)
|
||||
print "Memory: " + str(MEM) + "GB"
|
||||
print "VM Disk: " + str(HDISK) + "GB"
|
||||
print("ESXi Host: {}".format(HOST))
|
||||
print("ESXi Port: {}".format(PORT))
|
||||
print("VM NAME: {}".format(NAME))
|
||||
print("vCPU: {}".format(CPU))
|
||||
print("Memory: {} GB".format(MEM))
|
||||
print("VM Disk: {} GB".format(HDISK))
|
||||
if isVerbose:
|
||||
print "Format: " + DISKFORMAT
|
||||
print "DS Store: " + DSSTORE
|
||||
print "Network: " + NET
|
||||
print("Format: {}".format(DISKFORMAT))
|
||||
print("DS Store: {}".format(DSSTORE))
|
||||
print("Network: {}".format(NET))
|
||||
if ISO:
|
||||
print "ISO: " + ISO
|
||||
print("ISO: {}".format(ISO))
|
||||
if isVerbose:
|
||||
print "Guest OS: " + GUESTOS
|
||||
print "MAC: " + GeneratedMAC
|
||||
print("Guest OS: {}".format(GUESTOS))
|
||||
print("MAC: {}".format(GeneratedMAC))
|
||||
else:
|
||||
pass
|
||||
|
||||
if CheckHasErrors:
|
||||
if isDryRun:
|
||||
print "Dry Run: Failed."
|
||||
print("Dry Run: Failed.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
if isDryRun:
|
||||
print "Dry Run: Success."
|
||||
print("Dry Run: Success.")
|
||||
else:
|
||||
print GeneratedMAC
|
||||
print(GeneratedMAC)
|
||||
sys.exit(0)
|
||||
|
|
|
@ -78,7 +78,7 @@ LogOutput = '{'
|
|||
LogOutput += '"datetime":"' + str(the_current_date_time()) + '",'
|
||||
|
||||
if NAME == "":
|
||||
print "ERROR: Missing required option --name"
|
||||
print("ERROR: Missing required option --name")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
|
@ -89,11 +89,11 @@ try:
|
|||
(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, port: %s, username: %s" % (HOST, PORT, USER)
|
||||
print("Unable to determine if this is a ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER))
|
||||
sys.exit(1)
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
print "Unable to access ESXi Host: %s, port: %s, username: %s" % (HOST, PORT, USER)
|
||||
print("The Error is {}".format(sys.exc_info()[0]))
|
||||
print("Unable to access ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER))
|
||||
sys.exit(1)
|
||||
|
||||
#
|
||||
|
@ -114,12 +114,12 @@ try:
|
|||
VMDIR = splitLine[3]
|
||||
|
||||
if VMID == -1:
|
||||
print "Warning: VM " + NAME + " doesn't exists."
|
||||
print("Warning: VM {} doesn't exists.".format(NAME))
|
||||
ErrorMessages += " VM " + NAME + " doesn't exists."
|
||||
CheckHasErrors = True
|
||||
CheckHasWarnings = True
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
print("The Error is {}".format(sys.exc_info()[0]))
|
||||
sys.exit(1)
|
||||
|
||||
# Get List of Volumes,
|
||||
|
@ -132,7 +132,7 @@ try:
|
|||
splitLine = line.split()
|
||||
VOLUMES[splitLine[0]] = splitLine[1]
|
||||
except:
|
||||
print "The Error is " + str(sys.exc_info()[0])
|
||||
print("The Error is {}".format(sys.exc_info()[0]))
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
|
@ -155,42 +155,40 @@ if not CheckHasErrors:
|
|||
|
||||
CurrentState = ""
|
||||
CurrentStateCounter = 0
|
||||
while CurrentState != "off":
|
||||
while CurrentStateCounter < 10:
|
||||
if isVerbose:
|
||||
print "Get state VM"
|
||||
print("Get state of 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
|
||||
print("power.getstate: {}".format(lines))
|
||||
if re.search("Powered off", lines):
|
||||
CurrentState = "off"
|
||||
break
|
||||
|
||||
# Power off VM
|
||||
if isVerbose:
|
||||
print "Power OFF VM"
|
||||
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)
|
||||
print("power.off: {}".format(lines))
|
||||
|
||||
CurrentStateCounter += 1
|
||||
if CurrentStateCounter > 10:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
# destroy VM
|
||||
if isVerbose:
|
||||
print "Destroy VM"
|
||||
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)
|
||||
print("destroy: {}".format(lines))
|
||||
|
||||
except:
|
||||
print "There was an error destroying the VM."
|
||||
print("There was an error destroying the VM.")
|
||||
ErrorMessages += " There was an error destroying the VM."
|
||||
CheckHasErrors = True
|
||||
Result = "Fail"
|
||||
|
@ -212,20 +210,20 @@ try:
|
|||
with open(LOG, "a+w") as FD:
|
||||
FD.write(LogOutput)
|
||||
except:
|
||||
print "Error writing to log file: " + LOG
|
||||
print("Error writing to log file: {}".format(LOG))
|
||||
|
||||
if isSummary:
|
||||
if isVerbose:
|
||||
print "ESXi Host: " + HOST
|
||||
print "VM NAME: " + NAME
|
||||
print "Path: " + DSSTORE
|
||||
print("ESXi Host: {}".format(HOST))
|
||||
print("VM NAME: {}".format(NAME))
|
||||
print("Path: {}".format(DSSTORE))
|
||||
else:
|
||||
pass
|
||||
|
||||
if CheckHasErrors and not CheckHasWarnings:
|
||||
print "Failed"
|
||||
print("Failed")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print "Success"
|
||||
print("Success")
|
||||
sys.exit(0)
|
||||
|
||||
|
|
|
@ -80,9 +80,9 @@ def setup_config():
|
|||
yaml.dump(config_data, FD, default_flow_style=False)
|
||||
FD.close()
|
||||
except:
|
||||
print "Unable to create/update config file " + config_data_file_location
|
||||
print("Unable to create/update config file {}".format(config_data_file_location))
|
||||
e = sys.exc_info()[0]
|
||||
print "The Error is " + str(e)
|
||||
print("The Error is {}".format(e))
|
||||
sys.exit(1)
|
||||
return config_data
|
||||
|
||||
|
@ -94,9 +94,9 @@ def save_config(config_data):
|
|||
yaml.dump(config_data, FD, default_flow_style=False)
|
||||
FD.close()
|
||||
except:
|
||||
print "Unable to create/update config file " + config_data_file_location
|
||||
print("Unable to create/update config file {}".format(config_data_file_location))
|
||||
e = sys.exc_info()[0]
|
||||
print "The Error is " + str(e)
|
||||
print("The Error is {}".format(e))
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
@ -104,20 +104,3 @@ def save_config(config_data):
|
|||
def the_current_date_time():
|
||||
i = datetime.datetime.now()
|
||||
return str(i.isoformat())
|
||||
|
||||
|
||||
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 1, 2, 2, 2])
|
||||
|
||||
|
||||
def float2human(num):
|
||||
"""Integer to Human readable"""
|
||||
if num > 1:
|
||||
exponent = min(int(log(float(num), 1024)), len(unit_list) - 1)
|
||||
quotient = float(num) / 1024**exponent
|
||||
unit, num_decimals = unit_list[exponent]
|
||||
format_string = '{:.%sf} {}' % num_decimals
|
||||
return format_string.format(quotient, unit)
|
||||
if num == 0:
|
||||
return '0 bytes'
|
||||
if num == 1:
|
||||
return '1 byte'
|
||||
|
|
Loading…
Reference in New Issue