Skip to content

Instantly share code, notes, and snippets.

@pathcl
Last active July 10, 2020 01:54
Show Gist options
  • Select an option

  • Save pathcl/d1df21e09f3f8f732d61 to your computer and use it in GitHub Desktop.

Select an option

Save pathcl/d1df21e09f3f8f732d61 to your computer and use it in GitHub Desktop.
VMware shell through pyVmomi
#!/usr/bin/env python3
# Please install pyVmomi first.
# i.e.
# pip install pyvmomi
#
from pyVim import connect
from pyVmomi import vmodl
from pyVmomi import vim
import re
import os
import pchelper
import getpass
import cmd
import warnings
import atexit
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
warnings.filterwarnings("ignore")
class someshell(cmd.Cmd):
def connect(self, host):
""" Basic connector to ESXi. It uses pchelper in order to get vm
properties.
"""
self.vcenter = host
user = input("Please enter your username: ")
password = getpass.getpass("Password: ")
SI = connect.SmartConnect(host=host, user=user,
pwd=password,
port=443)
atexit.register(connect.Disconnect, SI)
view = pchelper.get_container_view(SI, obj_type=[vim.VirtualMachine])
vm_properties = ["name", "config.instanceUuid",
"config.hardware.numCPU",
"config.hardware.memoryMB", "runtime.powerState",
"config.guestFullName", "config.guestId",
"config.version"]
vm_data = pchelper.collect_properties(SI, view_ref=view,
obj_type=vim.VirtualMachine,
path_set=vm_properties,
include_mors=True)
return vm_data
def do_ls(self, host):
"""
Get all VM's on vCenter or ESXi.
It will ask you an username and valid password.
Usage example and output:
(Cmd) ls somehost.esxi.local
Please enter your username: root
Password:
----------------------------------------------------------------------
Name: vm01
Instance UUID: 523589d3-60fd-b49a-0dc1-c66b0b42b394
CPUs: 2
MemoryMB: 4096
Guest PowerState: running
Guest Full Name: Ubuntu Linux (64-bit)
Guest Container Type: ubuntu64Guest
Container Version: vmx-07
**********************************************************************
You have a total of 1 VM in somehost.esxi.local
"""
self.host = host
if host:
try:
vm_list = self.connect(host)
for vm in vm_list:
print("-" * 70)
print(
"Name: {0}".format(vm["name"]))
print("Instance UUID: {0}".format(
vm["config.instanceUuid"]))
print("CPUs: {0}".format(
vm["config.hardware.numCPU"]))
print("MemoryMB: {0}".format(
vm["config.hardware.memoryMB"]))
print("Guest PowerState: {0}".format(
vm["runtime.powerState"]))
print("Guest Full Name: {0}".format(
vm["config.guestFullName"]))
print("Guest Container Type: {0}".format(
vm["config.guestId"]))
print("Container Version: {0}".format(
vm["config.version"]))
print("*" * 70)
print("You have a total of {0} VM in {1}".format(len(vm_list),
host))
except vmodl.MethodFault as e:
print("Caught vmodl fault : ", e)
return 0
else:
print("Please provide a hostname or IP address")
def do_lson(self, host):
"""
Show PoweredOn VM. Usage example and output:
(Cmd) lson somehost.esxi.local
Please enter your username: root
Password:
----------------------------------------------------------------------
Name: vm01
Instance UUID: 523589d3-60fd-b49a-0dc1-c66b0b42b394
CPUs: 2
MemoryMB: 4096
Guest PowerState: running
Guest Full Name: Ubuntu Linux (64-bit)
Guest Container Type: ubuntu64Guest
Container Version: vmx-07
"""
self.host = host
if host:
try:
vm_list = self.connect(host)
for vm in vm_list:
if vm["runtime.powerState"] == 'running':
print("-" * 70)
print(
"Name: {0}".format(vm["name"]))
print("Instance UUID: {0}".format(
vm["config.instanceUuid"]))
print("CPUs: {0}".format(
vm["config.hardware.numCPU"]))
print("MemoryMB: {0}".format(
vm["config.hardware.memoryMB"]))
print("Guest PowerState: {0}".format(
vm["runtime.powerState"]))
print("Guest Full Name: {0}".format(
vm["config.guestFullName"]))
print("Guest Container Type: {0}".format(
vm["config.guestId"]))
print("Container Version: {0}".format(
vm["config.version"]))
except vmodl.MethodFault as e:
print("Caught vmodl fault : ", e)
return 0
else:
print("Please provide a hostname or IP address")
def do_stop(self, host):
""" Shutdown a cluster
"""
line = host.split()
user = input("Please enter your username: ")
password = getpass.getpass("Password: ")
SI = connect.SmartConnect(host=host, user=user,
pwd=password,
port=443)
content = SI.RetrieveContent()
objview = content.viewManager.CreateContainerView(content.rootFolder,
[vim.VirtualMachine],
True)
if host:
for vm in objview.view:
""" Regex hosts
"""
if re.match(r'^somehost.*', vm.runtime.host.name):
""" TODO "
Save poweredOn VM UUID BEFORE GOING
OFF!!!
"""
vm.PowerOff()
else:
print("Please provide a vmware host to connect")
def do_start(self, host):
""" Start a cluster
"""
line = host.split()
user = input("Please enter your username: ")
password = getpass.getpass("Password: ")
SI = connect.SmartConnect(host=host, user=user,
pwd=password,
port=443)
content = SI.RetrieveContent()
objview = content.viewManager.CreateContainerView(content.rootFolder,
[vim.VirtualMachine],
True)
if host:
for vm in objview.view:
vm.PowerOn()
"""
with open('poweredOn.txt', 'r') as f:
for line in f:
l = line.strip()
print('power on {0}'.format(l))
vm.PowerOn()
"""
else:
print("Please provide a vmware host to connect to: ")
def do_shell(self, line):
"Run a shell command"
print("running shell command:", line)
output = os.popen(line).read()
print(output)
self.last_output = output
def do_EOF(self, line):
return True
def postloop(self):
print
def emptyline(self):
print("Do not type empty lines! type 'help' to get commands")
if __name__ == '__main__':
someshell().cmdloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment