Skip to content

Commit

Permalink
Optional writing to log file
Browse files Browse the repository at this point in the history
  • Loading branch information
andrivet committed Jan 11, 2018
1 parent ebd2ac4 commit 1b1b9e6
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 45 deletions.
56 changes: 31 additions & 25 deletions esxi-vm-create
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#!/usr/bin/python

import argparse # Argument parser
import re # For regex
import paramiko # For remote ssh

from esxi_vm_functions import *

Expand All @@ -11,6 +9,7 @@ from esxi_vm_functions import *
ConfigData = setup_config()
NAME = ""
LOG = ConfigData['LOG']
writeLog = ConfigData['writeLog']
isDryRun = ConfigData['isDryRun']
isVerbose = ConfigData['isVerbose']
isSummary = ConfigData['isSummary']
Expand Down Expand Up @@ -47,25 +46,27 @@ parser = argparse.ArgumentParser(description='ESXi Create VM utility.')

parser.add_argument('-d', '--dry', dest='isDryRunarg', action='store_true',
help="Enable Dry Run mode (" + str(isDryRun) + ")")
parser.add_argument("-H", "--Host", dest='HOST', type=str, help="ESXi Host/IP (" + str(HOST) + ")")
parser.add_argument("-T", "--Port", dest='PORT', type=int, help="ESXi Port number (" + str(PORT) + ")")
parser.add_argument("-U", "--User", dest='USER', type=str, help="ESXi Host username (" + str(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 connection key (path to private key)")
parser.add_argument("-n", "--name", dest='NAME', type=str, help="VM name")
parser.add_argument("-c", "--cpu", dest='CPU', type=int, help="Number of vCPUS (" + str(CPU) + ")")
parser.add_argument("-m", "--mem", type=int, help="Memory in GB (" + str(MEM) + ")")
parser.add_argument("-v", "--vdisk", dest='HDISK', type=str, help="Size of virt hdisk (" + str(HDISK) + ")")
parser.add_argument("-i", "--iso", dest='ISO', type=str, help="CDROM ISO Path | None (" + str(ISO) + ")")
parser.add_argument("-N", "--net", dest='NET', type=str, help="Network Interface | None (" + str(NET) + ")")
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("-c", "--cpu", dest='CPU', type=int, help="Number of vCPUS ({})".format(CPU))
parser.add_argument("-m", "--mem", type=int, help="Memory in GB ({})".format(MEM))
parser.add_argument("-v", "--vdisk", dest='HDISK', type=str, help="Size of virt hdisk ({})".format(HDISK))
parser.add_argument("-i", "--iso", dest='ISO', type=str, help="CDROM ISO Path | None ({})".format(ISO))
parser.add_argument("-N", "--net", dest='NET', type=str, help="Network Interface | None ({})".format(NET))
parser.add_argument("-M", "--mac", dest='MAC', type=str, help="MAC address")
parser.add_argument("-S", "--store", dest='STORE', type=str, help="vmfs Store | LeastUsed (" + str(STORE) + ")")
parser.add_argument("-g", "--guestos", dest='GUESTOS', type=str, help="Guest OS. (" + str(GUESTOS) + ")")
parser.add_argument("-o", "--options", dest='VMXOPTS', type=str, default='NIL', help="Comma list of VMX Options.")
parser.add_argument("-S", "--store", dest='STORE', type=str, help="vmfs Store | LeastUsed ({})".format(STORE))
parser.add_argument("-g", "--guestos", dest='GUESTOS', type=str, help="Guest OS ({})".format(GUESTOS))
parser.add_argument("-o", "--options", dest='VMXOPTS', type=str, default='NIL', help="Comma list of VMX options")
parser.add_argument('-V', '--verbose', dest='isVerbosearg', action='store_true',
help="Enable Verbose mode (" + str(isVerbose) + ")")
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 (" + str(isSummary) + ")")
help="Display Summary ({})".format(isSummary))
parser.add_argument("-u", "--updateDefaults", dest='UPDATE', action='store_true',
help="Update Default VM settings stored in ~/.esxi-vm.yml")

Expand All @@ -76,6 +77,10 @@ if args.isDryRunarg:
isDryRun = True
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:
Expand Down Expand Up @@ -201,8 +206,7 @@ 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 \;",
ssh, isVerbose
)
ssh, isVerbose)
FoundISOPath = str(stdout.readlines()[0]).strip('\n')
if isVerbose:
print("FoundISOPath: {}".format(FoundISOPath))
Expand Down Expand Up @@ -413,11 +417,13 @@ if ErrorMessages != "":
LogOutput += '"Error Message":"{}",'.format(ErrorMessages)
LogOutput += '"Result":"{}","Completion Time":"{}"'.format(Result, the_current_date_time())
LogOutput += '}\n'
try:
with open(LOG, "a") as FD:
FD.write(LogOutput)
except Exception as e:
print("Error writing to log file: {}".format(LOG))

if writeLog:
try:
with open(LOG, "a") as FD:
FD.write(LogOutput)
except Exception as e:
print("Error writing to log file: {}".format(LOG))

if isSummary:
if isDryRun:
Expand Down
45 changes: 25 additions & 20 deletions esxi-vm-destroy
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@

import argparse # Argument parser
import time
import re # For regex
import paramiko # For remote ssh

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']
Expand All @@ -38,24 +37,29 @@ DSSTORE = ""
#
# Process Arguments
#
parser = argparse.ArgumentParser(description='ESXi Create VM utility.')

parser.add_argument("-H", "--Host", dest='HOST', type=str, help="ESXi Host/IP (" + str(HOST) + ")")
parser.add_argument("-T", "--Port", dest='PORT', type=int, help="ESXi Port number (" + str(PORT) + ")")
parser.add_argument("-U", "--User", dest='USER', type=str, help="ESXi Host username (" + str(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 connection key (path to private key)")
parser.add_argument("-n", "--name", dest='NAME', type=str, help="VM name")
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 (" + str(isVerbose) + ")")
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 (" + str(isSummary) + ")")

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:
Expand Down Expand Up @@ -106,8 +110,8 @@ except Exception as e:
try:
(stdin, stdout, stderr) = \
exec_ssh_command("Get List of Volumes",
"esxcli storage filesystem list |grep '/vmfs/volumes/.*true VMFS' |sort -nk7",
ssh, isVerbose)
"esxcli storage filesystem list |grep '/vmfs/volumes/.*true VMFS' |sort -nk7",
ssh, isVerbose)
type(stdin)
VOLUMES = {}
for line in stdout.readlines():
Expand Down Expand Up @@ -172,11 +176,12 @@ if ErrorMessages != "":
LogOutput += '"Result":"{}","Completion Time":"{}"'.format(Result, the_current_date_time())
LogOutput += '}\n'

try:
with open(LOG, "a") as FD:
FD.write(LogOutput)
except Exception as e:
print("Error writing to log file: {}".format(e))
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:
Expand Down
2 changes: 2 additions & 0 deletions esxi_vm_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import re # For regex
import paramiko # For remote ssh


def setup_config():

#
Expand All @@ -15,6 +16,7 @@ def setup_config():

# Your logfile
LOG=os.path.expanduser("~") + "/esxi-vm.log",
writeLog=False, # By default, do NOT write logs

# Enable/Disable dryrun by default
isDryRun=False,
Expand Down

0 comments on commit 1b1b9e6

Please sign in to comment.