Migrate to Python 3 (print function)

master
Sebastien Andrivet 2018-01-10 20:06:33 +01:00
parent 6ecf4d7fbc
commit f9f1d16251
3 changed files with 79 additions and 98 deletions

View File

@ -1,6 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
import argparse # Argument parser import argparse # Argument parser
import re # For regex import re # For regex
import paramiko # For remote ssh import paramiko # For remote ssh
@ -115,7 +114,7 @@ if args.VMXOPTS and args.VMXOPTS != 'NIL':
if args.UPDATE: if args.UPDATE:
print "Saving new Defaults to ~/.esxi-vm.yml" print("Saving new Defaults to ~/.esxi-vm.yml")
ConfigData['isDryRun'] = isDryRun ConfigData['isDryRun'] = isDryRun
ConfigData['isVerbose'] = isVerbose ConfigData['isVerbose'] = isVerbose
ConfigData['isSummary'] = isSummary ConfigData['isSummary'] = isSummary
@ -145,7 +144,7 @@ LogOutput = '{'
LogOutput += '"datetime":"' + str(the_current_date_time()) + '",' LogOutput += '"datetime":"' + str(the_current_date_time()) + '",'
if NAME == "": if NAME == "":
print "ERROR: Missing required option --name" print("ERROR: Missing required option --name")
sys.exit(1) sys.exit(1)
try: try:
@ -156,11 +155,11 @@ try:
(stdin, stdout, stderr) = ssh.exec_command("esxcli system version get |grep Version") (stdin, stdout, stderr) = ssh.exec_command("esxcli system version get |grep Version")
type(stdin) type(stdin)
if re.match("Version", str(stdout.readlines())) is not None: 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) sys.exit(1)
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is " + str(sys.exc_info()[0]))
print "Unable to access ESXi Host: %s, port: %s, username: %s" % (HOST, PORT, USER) print("Unable to access ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER))
sys.exit(1) sys.exit(1)
# #
@ -176,7 +175,7 @@ try:
VOLUMES[splitLine[0]] = splitLine[1] VOLUMES[splitLine[0]] = splitLine[1]
LeastUsedDS = splitLine[1] LeastUsedDS = splitLine[1]
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is {}".format(sys.exc_info()[0]))
sys.exit(1) sys.exit(1)
if STORE == "LeastUsed": if STORE == "LeastUsed":
@ -192,10 +191,10 @@ try:
type(stdin) type(stdin)
VMNICS = [] VMNICS = []
for line in stdout.readlines(): for line in stdout.readlines():
splitLine = re.split(',|\n', line) splitLine = re.split('[,\n]', line)
VMNICS.append(splitLine[0]) VMNICS.append(splitLine[0])
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is {}".format(sys.exc_info()[0]))
sys.exit(1) sys.exit(1)
# #
@ -210,7 +209,7 @@ if MAC != "":
elif re.compile(MACregex).search("00:50:56:" + MAC): elif re.compile(MACregex).search("00:50:56:" + MAC):
MAC = "00:50:56:" + MAC.replace("-", ":") MAC = "00:50:56:" + MAC.replace("-", ":")
else: else:
print "ERROR: " + MAC + " Invalid MAC address." print("ERROR: {} Invalid MAC address.".format(MAC))
ErrorMessages += " " + MAC + " Invalid MAC address." ErrorMessages += " " + MAC + " Invalid MAC address."
CheckHasErrors = True CheckHasErrors = True
@ -225,12 +224,13 @@ if ISO != "":
try: try:
# If ISO has no "/", try to find the ISO # If ISO has no "/", try to find the ISO
if not re.match('/', ISO): if not re.match('/', ISO):
(stdin, stdout, stderr) = ssh.exec_command("find /vmfs/volumes/ -type f -name " + ISO + (stdin, stdout, stderr) = \
" -exec sh -c 'echo $1; kill $PPID' sh {} 2>/dev/null \;") ssh.exec_command("find /vmfs/volumes/ -type f -name " + ISO +
" -exec sh -c 'echo $1; kill $PPID' sh {} 2>/dev/null \;")
type(stdin) type(stdin)
FoundISOPath = str(stdout.readlines()[0]).strip('\n') FoundISOPath = str(stdout.readlines()[0]).strip('\n')
if isVerbose: if isVerbose:
print "FoundISOPath: " + str(FoundISOPath) print("FoundISOPath: {}".format(FoundISOPath))
ISO = str(FoundISOPath) ISO = str(FoundISOPath)
(stdin, stdout, stderr) = ssh.exec_command("ls " + str(ISO)) (stdin, stdout, stderr) = ssh.exec_command("ls " + str(ISO))
@ -239,7 +239,7 @@ if ISO != "":
ISOfound = True ISOfound = True
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is {}".format(sys.exc_info()[0]))
sys.exit(1) sys.exit(1)
# #
@ -253,12 +253,12 @@ try:
splitLine = line.split() splitLine = line.split()
if NAME == splitLine[1]: if NAME == splitLine[1]:
VMID = splitLine[0] VMID = splitLine[0]
print "ERROR: VM " + NAME + " already exists." print("ERROR: VM {} already exists.".format(NAME))
ErrorMessages += " VM " + NAME + " already exists." ErrorMessages += " VM " + NAME + " already exists."
CheckHasErrors = True CheckHasErrors = True
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is {}".format(sys.exc_info()[0]))
sys.exit(1) sys.exit(1)
# #
# Do checks here # Do checks here
@ -266,19 +266,19 @@ except:
# Check CPU # Check CPU
if CPU < 1 or CPU > 128: 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]." ErrorMessages += " " + str(CPU) + " CPU out of range. [1-128]."
CheckHasErrors = True CheckHasErrors = True
# Check MEM # Check MEM
if MEM < 1 or MEM > 4080: 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]." ErrorMessages += " " + str(MEM) + "GB Memory out of range. [1-4080]."
CheckHasErrors = True CheckHasErrors = True
# Check HDISK # Check HDISK
if HDISK < 1 or HDISK > 63488: 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]." ErrorMessages += " Virtual Disk size " + str(HDISK) + "GB out of range. [1-63488]."
CheckHasErrors = True CheckHasErrors = True
@ -291,22 +291,22 @@ for Path in VOLUMES:
DSSTORE = VOLUMES[Path] DSSTORE = VOLUMES[Path]
if DSSTORE not in V: if DSSTORE not in V:
print "ERROR: Disk Storage " + STORE + " doesn't exist. " print("ERROR: Disk Storage {} doesn't exist. ".format(STORE))
print " Available Disk Stores: " + str([str(item) for item in V]) print(" Available Disk Stores: {}".format([str(item) for item in V]))
print " LeastUsed Disk Store : " + str(LeastUsedDS) print(" LeastUsed Disk Store : {}".format(LeastUsedDS))
ErrorMessages += " Disk Storage " + STORE + " doesn't exist. " ErrorMessages += " Disk Storage " + STORE + " doesn't exist. "
CheckHasErrors = True CheckHasErrors = True
# Check NIC (NIC record) # Check NIC (NIC record)
if (NET not in VMNICS) and (NET != "None"): if (NET not in VMNICS) and (NET != "None"):
print "ERROR: Virtual NIC " + NET + " doesn't exist." print("ERROR: Virtual NIC {} doesn't exist.".format(NET))
print " Available VM NICs: " + str([str(item) for item in VMNICS]) + " or 'None'" print(" Available VM NICs: {} or 'None'".format([str(item) for item in VMNICS]))
ErrorMessages += " Virtual NIC " + NET + " doesn't exist." ErrorMessages += " Virtual NIC " + NET + " doesn't exist."
CheckHasErrors = True CheckHasErrors = True
# Check ISO exists # Check ISO exists
if ISO != "" and not ISOfound: 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" ErrorMessages += " ISO " + ISO + " not found. Use full path to ISO"
CheckHasErrors = True CheckHasErrors = True
@ -316,7 +316,7 @@ try:
(stdin, stdout, stderr) = ssh.exec_command("ls -d " + FullPath) (stdin, stdout, stderr) = ssh.exec_command("ls -d " + FullPath)
type(stdin) type(stdin)
if stdout.readlines() and not stderr.readlines(): 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." ErrorMessages += " Directory " + FullPath + " already exists."
CheckHasErrors = True CheckHasErrors = True
except: except:
@ -397,9 +397,9 @@ for VMXopt in VMXOPTS:
vmx.append(key + " = " + value) vmx.append(key + " = " + value)
if isVerbose and VMXOPTS != '': if isVerbose and VMXOPTS != '':
print "VMX file:" print("VMX file:")
for i in vmx: for i in vmx:
print i print(i)
MyVM = FullPath + "/" + NAME MyVM = FullPath + "/" + NAME
if CheckHasErrors: if CheckHasErrors:
@ -412,7 +412,7 @@ if not isDryRun and not CheckHasErrors:
# Create NAME.vmx # Create NAME.vmx
if isVerbose: if isVerbose:
print "Create " + NAME + ".vmx file" print("Create {}.vmx file".format(NAME))
(stdin, stdout, stderr) = ssh.exec_command("mkdir " + FullPath) (stdin, stdout, stderr) = ssh.exec_command("mkdir " + FullPath)
type(stdin) type(stdin)
for line in vmx: for line in vmx:
@ -421,25 +421,25 @@ if not isDryRun and not CheckHasErrors:
# Create vmdk # Create vmdk
if isVerbose: if isVerbose:
print "Create " + NAME + ".vmdk file" print("Create {}.vmdk file".format(NAME))
(stdin, stdout, stderr) = \ (stdin, stdout, stderr) = \
ssh.exec_command("vmkfstools -c " + str(HDISK) + "G -d " + DISKFORMAT + " " + MyVM + ".vmdk") ssh.exec_command("vmkfstools -c " + str(HDISK) + "G -d " + DISKFORMAT + " " + MyVM + ".vmdk")
type(stdin) type(stdin)
# Register VM # Register VM
if isVerbose: if isVerbose:
print "Register VM" print("Register VM")
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd solo/registervm " + MyVM + ".vmx") (stdin, stdout, stderr) = ssh.exec_command("vim-cmd solo/registervm " + MyVM + ".vmx")
type(stdin) type(stdin)
VMID = int(stdout.readlines()[0]) VMID = int(stdout.readlines()[0])
# Power on VM # Power on VM
if isVerbose: if isVerbose:
print "Power ON VM" print("Power ON VM")
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.on " + str(VMID)) (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.on " + str(VMID))
type(stdin) type(stdin)
if stderr.readlines(): if stderr.readlines():
print "Error Powering-on VM." print("Error Powering-on VM.")
Result = "Fail" Result = "Fail"
# Get Generated MAC # Get Generated MAC
@ -450,7 +450,7 @@ if not isDryRun and not CheckHasErrors:
GeneratedMAC = str(stdout.readlines()[0]).strip('\n"') GeneratedMAC = str(stdout.readlines()[0]).strip('\n"')
except: 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." ErrorMessages += " There was an error creating the VM."
Result = "Fail" Result = "Fail"
@ -485,40 +485,40 @@ try:
with open(LOG, "a+w") as FD: with open(LOG, "a+w") as FD:
FD.write(LogOutput) FD.write(LogOutput)
except: except:
print "Error writing to log file: " + LOG print("Error writing to log file: {}".format(LOG))
if isSummary: if isSummary:
if isDryRun: if isDryRun:
print "\nDry Run summary:" print("\nDry Run summary:")
else: else:
print "\nCreate VM Success:" print("\nCreate VM Success:")
if isVerbose: if isVerbose:
print "ESXi Host: " + HOST print("ESXi Host: {}".format(HOST))
print "ESXi Port: " + PORT print("ESXi Port: {}".format(PORT))
print "VM NAME: " + NAME print("VM NAME: {}".format(NAME))
print "vCPU: " + str(CPU) print("vCPU: {}".format(CPU))
print "Memory: " + str(MEM) + "GB" print("Memory: {} GB".format(MEM))
print "VM Disk: " + str(HDISK) + "GB" print("VM Disk: {} GB".format(HDISK))
if isVerbose: if isVerbose:
print "Format: " + DISKFORMAT print("Format: {}".format(DISKFORMAT))
print "DS Store: " + DSSTORE print("DS Store: {}".format(DSSTORE))
print "Network: " + NET print("Network: {}".format(NET))
if ISO: if ISO:
print "ISO: " + ISO print("ISO: {}".format(ISO))
if isVerbose: if isVerbose:
print "Guest OS: " + GUESTOS print("Guest OS: {}".format(GUESTOS))
print "MAC: " + GeneratedMAC print("MAC: {}".format(GeneratedMAC))
else: else:
pass pass
if CheckHasErrors: if CheckHasErrors:
if isDryRun: if isDryRun:
print "Dry Run: Failed." print("Dry Run: Failed.")
sys.exit(1) sys.exit(1)
else: else:
if isDryRun: if isDryRun:
print "Dry Run: Success." print("Dry Run: Success.")
else: else:
print GeneratedMAC print(GeneratedMAC)
sys.exit(0) sys.exit(0)

View File

@ -78,7 +78,7 @@ LogOutput = '{'
LogOutput += '"datetime":"' + str(the_current_date_time()) + '",' LogOutput += '"datetime":"' + str(the_current_date_time()) + '",'
if NAME == "": if NAME == "":
print "ERROR: Missing required option --name" print("ERROR: Missing required option --name")
sys.exit(1) sys.exit(1)
try: try:
@ -89,11 +89,11 @@ try:
(stdin, stdout, stderr) = ssh.exec_command("esxcli system version get |grep Version") (stdin, stdout, stderr) = ssh.exec_command("esxcli system version get |grep Version")
type(stdin) type(stdin)
if re.match("Version", str(stdout.readlines())) is not None: 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) sys.exit(1)
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is {}".format(sys.exc_info()[0]))
print "Unable to access ESXi Host: %s, port: %s, username: %s" % (HOST, PORT, USER) print("Unable to access ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER))
sys.exit(1) sys.exit(1)
# #
@ -114,12 +114,12 @@ try:
VMDIR = splitLine[3] VMDIR = splitLine[3]
if VMID == -1: if VMID == -1:
print "Warning: VM " + NAME + " doesn't exists." print("Warning: VM {} doesn't exists.".format(NAME))
ErrorMessages += " VM " + NAME + " doesn't exists." ErrorMessages += " VM " + NAME + " doesn't exists."
CheckHasErrors = True CheckHasErrors = True
CheckHasWarnings = True CheckHasWarnings = True
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is {}".format(sys.exc_info()[0]))
sys.exit(1) sys.exit(1)
# Get List of Volumes, # Get List of Volumes,
@ -132,7 +132,7 @@ try:
splitLine = line.split() splitLine = line.split()
VOLUMES[splitLine[0]] = splitLine[1] VOLUMES[splitLine[0]] = splitLine[1]
except: except:
print "The Error is " + str(sys.exc_info()[0]) print("The Error is {}".format(sys.exc_info()[0]))
sys.exit(1) sys.exit(1)
@ -155,42 +155,40 @@ if not CheckHasErrors:
CurrentState = "" CurrentState = ""
CurrentStateCounter = 0 CurrentStateCounter = 0
while CurrentState != "off": while CurrentStateCounter < 10:
if isVerbose: if isVerbose:
print "Get state VM" print("Get state of VM")
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.getstate " + str(VMID)) (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.getstate " + str(VMID))
type(stdin) type(stdin)
lines = str(stdout.readlines()) + str(stderr.readlines()) lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose: if isVerbose:
print "power.getstate: " + lines print("power.getstate: {}".format(lines))
if re.search("Powered off", lines): if re.search("Powered off", lines):
CurrentState = "off" break
# Power off VM # Power off VM
if isVerbose: if isVerbose:
print "Power OFF VM" print("Power OFF VM")
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.off " + str(VMID) + " ||echo") (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.off " + str(VMID) + " ||echo")
type(stdin) type(stdin)
lines = str(stdout.readlines()) + str(stderr.readlines()) lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose: if isVerbose:
print "power.off: " + str(lines) print("power.off: {}".format(lines))
CurrentStateCounter += 1 CurrentStateCounter += 1
if CurrentStateCounter > 10:
break
time.sleep(1) time.sleep(1)
# destroy VM # destroy VM
if isVerbose: if isVerbose:
print "Destroy VM" print("Destroy VM")
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/destroy " + str(VMID)) (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/destroy " + str(VMID))
type(stdin) type(stdin)
lines = str(stdout.readlines()) + str(stderr.readlines()) lines = str(stdout.readlines()) + str(stderr.readlines())
if isVerbose: if isVerbose:
print "destroy: " + str(lines) print("destroy: {}".format(lines))
except: 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." ErrorMessages += " There was an error destroying the VM."
CheckHasErrors = True CheckHasErrors = True
Result = "Fail" Result = "Fail"
@ -212,20 +210,20 @@ try:
with open(LOG, "a+w") as FD: with open(LOG, "a+w") as FD:
FD.write(LogOutput) FD.write(LogOutput)
except: except:
print "Error writing to log file: " + LOG print("Error writing to log file: {}".format(LOG))
if isSummary: if isSummary:
if isVerbose: if isVerbose:
print "ESXi Host: " + HOST print("ESXi Host: {}".format(HOST))
print "VM NAME: " + NAME print("VM NAME: {}".format(NAME))
print "Path: " + DSSTORE print("Path: {}".format(DSSTORE))
else: else:
pass pass
if CheckHasErrors and not CheckHasWarnings: if CheckHasErrors and not CheckHasWarnings:
print "Failed" print("Failed")
sys.exit(1) sys.exit(1)
else: else:
print "Success" print("Success")
sys.exit(0) sys.exit(0)

View File

@ -80,9 +80,9 @@ def setup_config():
yaml.dump(config_data, FD, default_flow_style=False) yaml.dump(config_data, FD, default_flow_style=False)
FD.close() FD.close()
except: 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] e = sys.exc_info()[0]
print "The Error is " + str(e) print("The Error is {}".format(e))
sys.exit(1) sys.exit(1)
return config_data return config_data
@ -94,9 +94,9 @@ def save_config(config_data):
yaml.dump(config_data, FD, default_flow_style=False) yaml.dump(config_data, FD, default_flow_style=False)
FD.close() FD.close()
except: 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] e = sys.exc_info()[0]
print "The Error is " + str(e) print("The Error is {}".format(e))
return 1 return 1
return 0 return 0
@ -104,20 +104,3 @@ def save_config(config_data):
def the_current_date_time(): def the_current_date_time():
i = datetime.datetime.now() i = datetime.datetime.now()
return str(i.isoformat()) 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'