diff --git a/esxi-vm-create b/esxi-vm-create index 16383aa..186c14b 100755 --- a/esxi-vm-create +++ b/esxi-vm-create @@ -7,14 +7,6 @@ import paramiko # For remote ssh from esxi_vm_functions import * -def exec_ssh_command(message, command, verbose): - if verbose: - if message: - print(message) - print("SSH: " + command) - return ssh.exec_command(command) - - # Defaults and Variable setup ConfigData = setup_config() NAME = "" @@ -146,35 +138,20 @@ if args.UPDATE: if NAME == "": sys.exit(0) -# -# main() -# -LogOutput = '{' -LogOutput += '"datetime":"{}",'.format(the_current_date_time()) - 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, port=PORT, username=USER, password=PASSWORD, key_filename=KEY) +LogOutput = '{' +LogOutput += '"datetime":"{}",'.format(the_current_date_time()) - (stdin, stdout, stderr) = exec_ssh_command("Get ESXi version", "esxcli system version get |grep Version", isVerbose) - if re.match("Version", str(stdout.readlines())) is not None: - print("Unable to determine if this is a ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER)) - sys.exit(1) -except Exception as e: - print("The Error is {}".format(e)) - print("Unable to access ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER)) - sys.exit(1) +ssh = connect_to_esxi(HOST, PORT, USER, PASSWORD, KEY, isVerbose) try: (stdin, stdout, stderr) = \ exec_ssh_command("Get existing volumes", "esxcli storage filesystem list |grep '/vmfs/volumes/.*true VMFS' |sort -nk7", - isVerbose) + ssh, isVerbose) VOLUMES = {} for line in stdout.readlines(): splitLine = line.split() @@ -192,7 +169,7 @@ try: (stdin, stdout, stderr) = \ exec_ssh_command("Get existing networks", "esxcli network vswitch standard list|grep Portgroups|sed 's/^ Portgroups: //g'", - isVerbose) + ssh, isVerbose) VMNICS = [] for line in stdout.readlines(): splitLine = re.split('[,\n]', line) @@ -224,14 +201,14 @@ if ISO != "": (stdin, stdout, stderr) = exec_ssh_command("Search ISO image", "find /vmfs/volumes/ -type f -name {}".format(ISO) + " -exec sh -c 'echo $1; kill $PPID' sh {} 2>/dev/null \;", - isVerbose + ssh, isVerbose ) FoundISOPath = str(stdout.readlines()[0]).strip('\n') if isVerbose: print("FoundISOPath: {}".format(FoundISOPath)) ISO = str(FoundISOPath) - (stdin, stdout, stderr) = exec_ssh_command("Check ISO", "ls {}".format(ISO), isVerbose) + (stdin, stdout, stderr) = exec_ssh_command("Check ISO", "ls {}".format(ISO), ssh, isVerbose) if stdout.readlines() and not stderr.readlines(): ISOfound = True @@ -241,7 +218,7 @@ if ISO != "": VMID = -1 try: - (stdin, stdout, stderr) = exec_ssh_command("Get list of VMs", "vim-cmd vmsvc/getallvms", isVerbose) + (stdin, stdout, stderr) = exec_ssh_command("Get list of VMs", "vim-cmd vmsvc/getallvms", ssh, isVerbose) for line in stdout.readlines(): splitLine = line.split() if NAME == splitLine[1]: @@ -301,7 +278,7 @@ if ISO != "" and not ISOfound: # Check if DSPATH/NAME already exists try: FullPath = DSPATH + "/" + NAME - (stdin, stdout, stderr) = exec_ssh_command("List VMs directories", "ls -d {}".format(FullPath), isVerbose) + (stdin, stdout, stderr) = exec_ssh_command("List VMs directories", "ls -d {}".format(FullPath), ssh, isVerbose) if stdout.readlines() and not stderr.readlines(): print("ERROR: Directory {} already exists.".format(FullPath)) ErrorMessages += " Directory {} already exists.".format(FullPath) @@ -393,20 +370,21 @@ else: if not isDryRun and not CheckHasErrors: try: (stdin, stdout, stderr) = exec_ssh_command("Create {}.vmx file".format(NAME), - "mkdir {}".format(FullPath), isVerbose) + "mkdir {}".format(FullPath), ssh, isVerbose) for k, v in vmx.items(): (stdin, stdout, stderr) = exec_ssh_command(None, "echo '{} = \"{}\"' >> {}.vmx".format(k, v, MyVM), - isVerbose) + ssh, isVerbose) (stdin, stdout, stderr) = exec_ssh_command("Create {}.vmdk file".format(NAME), "vmkfstools -c {}G -d {} {}.vmdk".format(HDISK, DISKFORMAT, MyVM), - isVerbose) + ssh, isVerbose) (stdin, stdout, stderr) = exec_ssh_command("Register VM", - "vim-cmd solo/registervm {}.vmx".format(MyVM), isVerbose) + "vim-cmd solo/registervm {}.vmx".format(MyVM), ssh, isVerbose) VMID = int(stdout.readlines()[0]) - (stdin, stdout, stderr) = exec_ssh_command("Power ON VM", "vim-cmd vmsvc/power.on {}".format(VMID), isVerbose) + (stdin, stdout, stderr) = exec_ssh_command("Power ON VM", "vim-cmd vmsvc/power.on {}".format(VMID), + ssh, isVerbose) if stderr.readlines(): print("Error Powering-on VM.") Result = "Fail" @@ -414,7 +392,7 @@ if not isDryRun and not CheckHasErrors: if NET != "None": (stdin, stdout, stderr) = exec_ssh_command("Get MAC address", "grep -i 'ethernet0.*ddress = ' {}.vmx".format(MyVM) + - " |tail -1|awk '{print $NF}'", isVerbose) + " |tail -1|awk '{print $NF}'", ssh, isVerbose) GeneratedMAC = str(stdout.readlines()[0]).strip('\n"') except Exception as e: diff --git a/esxi-vm-destroy b/esxi-vm-destroy index dffa22d..9850c78 100755 --- a/esxi-vm-destroy +++ b/esxi-vm-destroy @@ -71,36 +71,20 @@ if args.KEY: if args.NAME: NAME = args.NAME -# -# main() -# -LogOutput = '{' -LogOutput += '"datetime":"' + str(the_current_date_time()) + '",' - 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, port=PORT, username=USER, password=PASSWORD, key_filename=KEY) +LogOutput = '{' +LogOutput += '"datetime":"{}",'.format(the_current_date_time()) - (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: {}, port: {}, username: {}".format(HOST, PORT, USER)) - sys.exit(1) -except Exception as e: - print("The Error is {}".format(e)) - print("Unable to access ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER)) - sys.exit(1) +ssh = connect_to_esxi(HOST, PORT, USER, PASSWORD, KEY, isVerbose) VMID = -1 CheckHasWarnings = False try: - (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/getallvms") + (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() @@ -119,10 +103,11 @@ except Exception as e: print("The Error is {}".format(e)) 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") + 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(): @@ -150,31 +135,27 @@ else: if not CheckHasErrors: try: for i in range(0, 10): - if isVerbose: - print("Get state of VM") - (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.getstate {}".format(VMID)) - type(stdin) + (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 - if isVerbose: - print("Power OFF VM") - (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.off {} ||echo".format(VMID)) - type(stdin) + (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) - # destroy VM - if isVerbose: - print("Destroy VM") - (stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/destroy {}".format(VMID)) - type(stdin) + (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)) diff --git a/esxi_vm_functions.py b/esxi_vm_functions.py index 1a752b9..4ac00fb 100755 --- a/esxi_vm_functions.py +++ b/esxi_vm_functions.py @@ -3,7 +3,8 @@ import sys import yaml import datetime # For current Date/Time - +import re # For regex +import paramiko # For remote ssh def setup_config(): @@ -94,3 +95,38 @@ def save_config(config_data): def the_current_date_time(): i = datetime.datetime.now() return str(i.isoformat()) + + +def exec_ssh_command(message, command, ssh, verbose): + if verbose: + if message: + print(message) + print("SSH: " + command) + return ssh.exec_command(command) + + +def get_esxi_version(ssh, verbose): + try: + (stdin, stdout, stderr) = exec_ssh_command("Get ESXi version", "esxcli system version get |grep Version", + ssh, verbose) + if re.match("Version", str(stdout.readlines())) is not None: + print("Unable to determine if this is a ESXi Host: {}, port: {}, username: {}".format(HOST, PORT, USER)) + sys.exit(1) + + except Exception as e: + print("Unable to get ESXi version") + print("The Error is {}".format(e)) + sys.exit(1) + + +def connect_to_esxi(host, port, user, password, key, verbose): + try: + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(host, port=port, username=user, password=password, key_filename=key) + get_esxi_version(ssh, verbose) + return ssh + except Exception as e: + print("Unable to access ESXi Host: {}, port: {}, username: {}, key: {}".format(host, port, user, key)) + print("The Error is {}".format(e)) + sys.exit(1)