mirror of https://github.com/Kodomo/esxi-vm
Move common code to esxi_vm_functions,
parent
d7c4e3cfda
commit
de57ce517e
|
@ -7,14 +7,6 @@ import paramiko # For remote ssh
|
||||||
from esxi_vm_functions import *
|
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
|
# Defaults and Variable setup
|
||||||
ConfigData = setup_config()
|
ConfigData = setup_config()
|
||||||
NAME = ""
|
NAME = ""
|
||||||
|
@ -146,35 +138,20 @@ if args.UPDATE:
|
||||||
if NAME == "":
|
if NAME == "":
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
#
|
|
||||||
# main()
|
|
||||||
#
|
|
||||||
LogOutput = '{'
|
|
||||||
LogOutput += '"datetime":"{}",'.format(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:
|
LogOutput = '{'
|
||||||
ssh = paramiko.SSHClient()
|
LogOutput += '"datetime":"{}",'.format(the_current_date_time())
|
||||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
||||||
ssh.connect(HOST, port=PORT, username=USER, password=PASSWORD, key_filename=KEY)
|
|
||||||
|
|
||||||
(stdin, stdout, stderr) = exec_ssh_command("Get ESXi version", "esxcli system version get |grep Version", isVerbose)
|
ssh = connect_to_esxi(HOST, PORT, USER, PASSWORD, KEY, 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)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
(stdin, stdout, stderr) = \
|
(stdin, stdout, stderr) = \
|
||||||
exec_ssh_command("Get existing volumes",
|
exec_ssh_command("Get existing volumes",
|
||||||
"esxcli storage filesystem list |grep '/vmfs/volumes/.*true VMFS' |sort -nk7",
|
"esxcli storage filesystem list |grep '/vmfs/volumes/.*true VMFS' |sort -nk7",
|
||||||
isVerbose)
|
ssh, isVerbose)
|
||||||
VOLUMES = {}
|
VOLUMES = {}
|
||||||
for line in stdout.readlines():
|
for line in stdout.readlines():
|
||||||
splitLine = line.split()
|
splitLine = line.split()
|
||||||
|
@ -192,7 +169,7 @@ try:
|
||||||
(stdin, stdout, stderr) = \
|
(stdin, stdout, stderr) = \
|
||||||
exec_ssh_command("Get existing networks",
|
exec_ssh_command("Get existing networks",
|
||||||
"esxcli network vswitch standard list|grep Portgroups|sed 's/^ Portgroups: //g'",
|
"esxcli network vswitch standard list|grep Portgroups|sed 's/^ Portgroups: //g'",
|
||||||
isVerbose)
|
ssh, isVerbose)
|
||||||
VMNICS = []
|
VMNICS = []
|
||||||
for line in stdout.readlines():
|
for line in stdout.readlines():
|
||||||
splitLine = re.split('[,\n]', line)
|
splitLine = re.split('[,\n]', line)
|
||||||
|
@ -224,14 +201,14 @@ if ISO != "":
|
||||||
(stdin, stdout, stderr) = exec_ssh_command("Search ISO image",
|
(stdin, stdout, stderr) = exec_ssh_command("Search ISO image",
|
||||||
"find /vmfs/volumes/ -type f -name {}".format(ISO) +
|
"find /vmfs/volumes/ -type f -name {}".format(ISO) +
|
||||||
" -exec sh -c 'echo $1; kill $PPID' sh {} 2>/dev/null \;",
|
" -exec sh -c 'echo $1; kill $PPID' sh {} 2>/dev/null \;",
|
||||||
isVerbose
|
ssh, isVerbose
|
||||||
)
|
)
|
||||||
FoundISOPath = str(stdout.readlines()[0]).strip('\n')
|
FoundISOPath = str(stdout.readlines()[0]).strip('\n')
|
||||||
if isVerbose:
|
if isVerbose:
|
||||||
print("FoundISOPath: {}".format(FoundISOPath))
|
print("FoundISOPath: {}".format(FoundISOPath))
|
||||||
ISO = str(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():
|
if stdout.readlines() and not stderr.readlines():
|
||||||
ISOfound = True
|
ISOfound = True
|
||||||
|
|
||||||
|
@ -241,7 +218,7 @@ if ISO != "":
|
||||||
|
|
||||||
VMID = -1
|
VMID = -1
|
||||||
try:
|
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():
|
for line in stdout.readlines():
|
||||||
splitLine = line.split()
|
splitLine = line.split()
|
||||||
if NAME == splitLine[1]:
|
if NAME == splitLine[1]:
|
||||||
|
@ -301,7 +278,7 @@ if ISO != "" and not ISOfound:
|
||||||
# Check if DSPATH/NAME already exists
|
# Check if DSPATH/NAME already exists
|
||||||
try:
|
try:
|
||||||
FullPath = DSPATH + "/" + NAME
|
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():
|
if stdout.readlines() and not stderr.readlines():
|
||||||
print("ERROR: Directory {} already exists.".format(FullPath))
|
print("ERROR: Directory {} already exists.".format(FullPath))
|
||||||
ErrorMessages += " Directory {} already exists.".format(FullPath)
|
ErrorMessages += " Directory {} already exists.".format(FullPath)
|
||||||
|
@ -393,20 +370,21 @@ else:
|
||||||
if not isDryRun and not CheckHasErrors:
|
if not isDryRun and not CheckHasErrors:
|
||||||
try:
|
try:
|
||||||
(stdin, stdout, stderr) = exec_ssh_command("Create {}.vmx file".format(NAME),
|
(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():
|
for k, v in vmx.items():
|
||||||
(stdin, stdout, stderr) = exec_ssh_command(None, "echo '{} = \"{}\"' >> {}.vmx".format(k, v, MyVM),
|
(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),
|
(stdin, stdout, stderr) = exec_ssh_command("Create {}.vmdk file".format(NAME),
|
||||||
"vmkfstools -c {}G -d {} {}.vmdk".format(HDISK, DISKFORMAT, MyVM),
|
"vmkfstools -c {}G -d {} {}.vmdk".format(HDISK, DISKFORMAT, MyVM),
|
||||||
isVerbose)
|
ssh, isVerbose)
|
||||||
|
|
||||||
(stdin, stdout, stderr) = exec_ssh_command("Register VM",
|
(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])
|
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():
|
if stderr.readlines():
|
||||||
print("Error Powering-on VM.")
|
print("Error Powering-on VM.")
|
||||||
Result = "Fail"
|
Result = "Fail"
|
||||||
|
@ -414,7 +392,7 @@ if not isDryRun and not CheckHasErrors:
|
||||||
if NET != "None":
|
if NET != "None":
|
||||||
(stdin, stdout, stderr) = exec_ssh_command("Get MAC address",
|
(stdin, stdout, stderr) = exec_ssh_command("Get MAC address",
|
||||||
"grep -i 'ethernet0.*ddress = ' {}.vmx".format(MyVM) +
|
"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"')
|
GeneratedMAC = str(stdout.readlines()[0]).strip('\n"')
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
@ -71,36 +71,20 @@ if args.KEY:
|
||||||
if args.NAME:
|
if args.NAME:
|
||||||
NAME = args.NAME
|
NAME = args.NAME
|
||||||
|
|
||||||
#
|
|
||||||
# main()
|
|
||||||
#
|
|
||||||
LogOutput = '{'
|
|
||||||
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:
|
LogOutput = '{'
|
||||||
ssh = paramiko.SSHClient()
|
LogOutput += '"datetime":"{}",'.format(the_current_date_time())
|
||||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
||||||
ssh.connect(HOST, port=PORT, username=USER, password=PASSWORD, key_filename=KEY)
|
|
||||||
|
|
||||||
(stdin, stdout, stderr) = ssh.exec_command("esxcli system version get |grep Version")
|
ssh = connect_to_esxi(HOST, PORT, USER, PASSWORD, KEY, isVerbose)
|
||||||
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)
|
|
||||||
|
|
||||||
VMID = -1
|
VMID = -1
|
||||||
CheckHasWarnings = False
|
CheckHasWarnings = False
|
||||||
|
|
||||||
try:
|
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)
|
type(stdin)
|
||||||
for line in stdout.readlines():
|
for line in stdout.readlines():
|
||||||
splitLine = line.split()
|
splitLine = line.split()
|
||||||
|
@ -119,10 +103,11 @@ except Exception as e:
|
||||||
print("The Error is {}".format(e))
|
print("The Error is {}".format(e))
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Get List of Volumes,
|
|
||||||
try:
|
try:
|
||||||
(stdin, stdout, stderr) = \
|
(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)
|
type(stdin)
|
||||||
VOLUMES = {}
|
VOLUMES = {}
|
||||||
for line in stdout.readlines():
|
for line in stdout.readlines():
|
||||||
|
@ -150,31 +135,27 @@ else:
|
||||||
if not CheckHasErrors:
|
if not CheckHasErrors:
|
||||||
try:
|
try:
|
||||||
for i in range(0, 10):
|
for i in range(0, 10):
|
||||||
if isVerbose:
|
(stdin, stdout, stderr) = exec_ssh_command("Get state of VM",
|
||||||
print("Get state of VM")
|
"vim-cmd vmsvc/power.getstate {}".format(VMID),
|
||||||
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.getstate {}".format(VMID))
|
ssh, isVerbose)
|
||||||
type(stdin)
|
|
||||||
lines = str(stdout.readlines()) + str(stderr.readlines())
|
lines = str(stdout.readlines()) + str(stderr.readlines())
|
||||||
if isVerbose:
|
if isVerbose:
|
||||||
print("power.getstate: {}".format(lines))
|
print("power.getstate: {}".format(lines))
|
||||||
if re.search("Powered off", lines):
|
if re.search("Powered off", lines):
|
||||||
break
|
break
|
||||||
|
|
||||||
if isVerbose:
|
(stdin, stdout, stderr) = exec_ssh_command("Power OFF VM",
|
||||||
print("Power OFF VM")
|
"vim-cmd vmsvc/power.off {} ||echo".format(VMID),
|
||||||
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/power.off {} ||echo".format(VMID))
|
ssh, isVerbose)
|
||||||
type(stdin)
|
|
||||||
lines = str(stdout.readlines()) + str(stderr.readlines())
|
lines = str(stdout.readlines()) + str(stderr.readlines())
|
||||||
if isVerbose:
|
if isVerbose:
|
||||||
print("power.off: {}".format(lines))
|
print("power.off: {}".format(lines))
|
||||||
|
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
# destroy VM
|
(stdin, stdout, stderr) = exec_ssh_command("Destroy VM",
|
||||||
if isVerbose:
|
"vim-cmd vmsvc/destroy {}".format(VMID),
|
||||||
print("Destroy VM")
|
ssh, isVerbose)
|
||||||
(stdin, stdout, stderr) = ssh.exec_command("vim-cmd vmsvc/destroy {}".format(VMID))
|
|
||||||
type(stdin)
|
|
||||||
lines = str(stdout.readlines()) + str(stderr.readlines())
|
lines = str(stdout.readlines()) + str(stderr.readlines())
|
||||||
if isVerbose:
|
if isVerbose:
|
||||||
print("destroy: {}".format(lines))
|
print("destroy: {}".format(lines))
|
||||||
|
|
|
@ -3,7 +3,8 @@ import os.path
|
||||||
import sys
|
import sys
|
||||||
import yaml
|
import yaml
|
||||||
import datetime # For current Date/Time
|
import datetime # For current Date/Time
|
||||||
|
import re # For regex
|
||||||
|
import paramiko # For remote ssh
|
||||||
|
|
||||||
def setup_config():
|
def setup_config():
|
||||||
|
|
||||||
|
@ -94,3 +95,38 @@ 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())
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
Loading…
Reference in New Issue