def __init__(self, guests_only=None): self.config = ConfigParser.SafeConfigParser() if os.environ.get('VMWARE_INI', ''): config_files = [os.environ['VMWARE_INI']] else: config_files = [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini'] for config_file in config_files: if os.path.exists(config_file): self.config.read(config_file) break # Retrieve only guest VMs, or include host systems? if guests_only is not None: self.guests_only = guests_only elif self.config.has_option('defaults', 'guests_only'): self.guests_only = self.config.getboolean('defaults', 'guests_only') else: self.guests_only = True # Read authentication information from VMware environment variables # (if set), otherwise from INI file. auth_host = os.environ.get('VMWARE_HOST') if not auth_host and self.config.has_option('auth', 'host'): auth_host = self.config.get('auth', 'host') auth_user = os.environ.get('VMWARE_USER') if not auth_user and self.config.has_option('auth', 'user'): auth_user = self.config.get('auth', 'user') auth_password = os.environ.get('VMWARE_PASSWORD') if not auth_password and self.config.has_option('auth', 'password'): auth_password = self.config.get('auth', 'password') # Create the VMware client connection. self.client = Client(auth_host, auth_user, auth_password)
def main(): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE # real vcenter kwargs = {'host': '192.168.1.39', 'user': '******', 'pwd': 'vmware', 'port': 443, 'sslContext': context} # fake vcenter kwargs = {'host': 'localhost', 'user': '******', 'pwd': 'test', 'port': 443, 'sslContext': context } print('# PYVMOMI ...') try: si = SmartConnect(**kwargs) content = si.RetrieveContent() virtual_machines = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) for virtual_machine in virtual_machines.view: name = virtual_machine.name print('name: %s' % name) if virtual_machine.guest: for net in virtual_machine.guest.net: print('mac: %s' % net.macAddress) except Exception as e: print e print('# PSPHERE ...') client = Client(kwargs['host'], kwargs['user'], kwargs['pwd']) hosts = HostSystem.all(client) for host in hosts: print 'host:',host.name for vm in host.vm: print 'name: ',vm.name
def __init__(self, url, username, password): self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__)) if(url.startswith('http://') or url.startswith('https://')): server = urllib2.Request(url).get_host() else: server = url self.client = Client(server=server, username=username, password=password)
def main(): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE # real vcenter kwargs = { 'host': '192.168.1.39', 'user': '******', 'pwd': 'vmware', 'port': 443, 'sslContext': context } # fake vcenter kwargs = { 'host': 'localhost', 'user': '******', 'pwd': 'test', 'port': 443, 'sslContext': context } print('# PYVMOMI ...') try: si = SmartConnect(**kwargs) content = si.RetrieveContent() except Exception as e: print e print('# PSPHERE ...') client = Client(kwargs['host'], kwargs['user'], kwargs['pwd'])
def connect_server(self): try: client = Client(self.server_ip, self.username, self.password) print "connection established" return client except Exception, e: print "exception:", e sys.exit(1)
def check_template_exists(hostname, username, password, name): client = Client(server=hostname, username=username, password=password) try: VirtualMachine.get(client, name=name) print "VSPHERE: A Machine with that name already exists" except ObjectNotFoundError: return False client.logout() return True
def main(options): """Obtains supported features from the license manager""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) lm_info = client.sc.licenseManager.QuerySupportedFeatures() for feature in lm_info: print('%s: %s' % (feature.featureName, feature.state)) client.logout()
def main(options): """A simple connection test to login and print the server time.""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) print(client.si.CurrentTime()) client.logout()
def __init__(self, guests_only=None): self.config = configparser.SafeConfigParser() if os.environ.get('VMWARE_INI', ''): config_files = [os.environ['VMWARE_INI']] else: config_files = [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini'] for config_file in config_files: if os.path.exists(config_file): self.config.read(config_file) break # Retrieve only guest VMs, or include host systems? if guests_only is not None: self.guests_only = guests_only elif self.config.has_option('defaults', 'guests_only'): self.guests_only = self.config.getboolean('defaults', 'guests_only') else: self.guests_only = True # Read authentication information from VMware environment variables # (if set), otherwise from INI file. auth_host = os.environ.get('VMWARE_HOST') if not auth_host and self.config.has_option('auth', 'host'): auth_host = self.config.get('auth', 'host') auth_user = os.environ.get('VMWARE_USER') if not auth_user and self.config.has_option('auth', 'user'): auth_user = self.config.get('auth', 'user') auth_password = os.environ.get('VMWARE_PASSWORD') if not auth_password and self.config.has_option('auth', 'password'): auth_password = self.config.get('auth', 'password') sslcheck = os.environ.get('VMWARE_SSLCHECK') if not sslcheck and self.config.has_option('auth', 'sslcheck'): sslcheck = self.config.get('auth', 'sslcheck') if not sslcheck: sslcheck = True else: if sslcheck.lower() in ['no', 'false']: sslcheck = False else: sslcheck = True # Limit the clusters being scanned self.filter_clusters = os.environ.get('VMWARE_CLUSTERS') if not self.filter_clusters and self.config.has_option('defaults', 'clusters'): self.filter_clusters = self.config.get('defaults', 'clusters') if self.filter_clusters: self.filter_clusters = [x.strip() for x in self.filter_clusters.split(',') if x.strip()] # Override certificate checks if not sslcheck: if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context # Create the VMware client connection. self.client = Client(auth_host, auth_user, auth_password)
def main(name, options): """The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str """ server = config._config_value("general", "server", options.server) if server is None: raise ValueError("server must be supplied on command line" " or in configuration file.") username = config._config_value("general", "username", options.username) if username is None: raise ValueError("username must be supplied on command line" " or in configuration file.") password = config._config_value("general", "password", options.password) if password is None: raise ValueError("password must be supplied on command line" " or in configuration file.") vm_template = None if options.template is not None: try: vm_template = template.load_template(options.template) except TemplateNotFoundError: print("ERROR: Template \"%s\" could not be found." % options.template) sys.exit(1) expected_opts = ["compute_resource", "datastore", "disksize", "nics", "memory", "num_cpus", "guest_id", "host"] vm_opts = {} for opt in expected_opts: vm_opts[opt] = getattr(options, opt) if vm_opts[opt] is None: if vm_template is None: raise ValueError("%s not specified on the command line and" " you have not specified any template to" " inherit the value from." % opt) try: vm_opts[opt] = vm_template[opt] except AttributeError: raise ValueError("%s not specified on the command line and" " no value is provided in the specified" " template." % opt) client = Client(server=server, username=username, password=password) create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"], vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"], vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"]) client.logout()
def make_template(client, name, hostname, username, password): print "VSPHERE: Marking as Template" client = Client(server=hostname, username=username, password=password) vm = VirtualMachine.get(client, name=name) try: vm.MarkAsTemplate() print " VSPHERE: Successfully templatized machine" except: print " VSPHERE: Failed to templatize machine" sys.exit(127)
def __init__(self, vsphere_server, vsphere_username, vsphere_password): self.server = vsphere_server self.username = vsphere_username self.password = vsphere_password try: log._info("Attempting to connect to vCenter server: %s" % (self.server)) self.client = Client(self.server, self.username, self.password) log._info("CONNECTED to vCenter server: %s" % (self.server)) except VimFault as e: log._warn("Failed to connect to vCenter: %s" % (e.fault_name)) return False
def run(**kwargs): provider = cfme_data['management_systems'][kwargs.get('provider')] creds = credentials[provider['credentials']] hostname = provider['hostname'] username = creds['username'] password = creds['password'] client = Client(server=hostname, username=username, password=password) kwargs = update_params_api(client, **kwargs) name = kwargs.get('template_name', None) if name is None: name = cfme_data['basic_info']['appliance_template'] print "VSPHERE: Template Name: %s" % name check_kwargs(**kwargs) url = kwargs.get('image_url') if not check_template_exists(hostname, username, password, name): if kwargs.get('upload'): # Wrapper for ovftool - sometimes it just won't work for i in range(0, NUM_OF_TRIES_OVFTOOL): print "VSPHERE: Trying ovftool %s..." % i ova_ret, ova_out = upload_ova(hostname, username, password, name, kwargs.get('datastore'), kwargs.get('cluster'), kwargs.get('datacenter'), url, kwargs.get('host'), kwargs.get('proxy')) if ova_ret is 0: break if ova_ret is -1: print "VSPHERE: Ovftool failed to upload file." print ova_out sys.exit(127) if kwargs.get('disk'): add_disk(client, name) if kwargs.get('template'): make_template(client, name, hostname, username, password) client.logout() print "VSPHERE: Completed successfully"
def main(options): client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) host = HostSystem.all(client) for h in host: # Preload the name attribute of all items in the vm attribute. Read the # manual as this significantly speeds up queries for ManagedObject's h.preload("vm", properties=["name", "guest"]) # Iterate over the items in host.vm and print their names for vm in sorted(h.vm): print("%s: %s" % (vm.name, vm.guest.guestState)) # Close the connection client.logout()
def main(options): client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) # Get a HostSystem object representing the host host = HostSystem.get(client, name=options.hostsystem) # Preload the name attribute of all items in the vm attribute. Read the # manual as this significantly speeds up queries for ManagedObject's host.preload("vm", properties=["name"]) # Iterate over the items in host.vm and print their names for vm in sorted(host.vm): print(vm.name) # Close the connection client.logout()
import psphere from psphere.client import Client from psphere.managedobjects import HostSystem client = Client("192.168.0.116", "root", "xxxxx") hosts = HostSystem.all(client) host = hosts[0] db = host.datastoreBrowser mor = db.SearchDatastore_Task(datastorePath="[datastore1] vCenter/", searchSpec={ "matchPattern": "vCenter.vmx", "details": { "fileType": True, "fileSize": True, "modification": True, "fileOwner": True }, "searchCaseInsensitive": False, "sortFoldersFirst": False, "query": None }) while True: info = mor.info if info.state in ["success"]: break mor.update(properties=["info"]) result = info.result files = result.file
#!/bin/env python import sys from psphere.client import Client argvs = sys.argv target_host = argvs[1] # 第1引数に指定したターゲットホスト名取得 target_vm = argvs[2] # 第2引数に指定したターゲットVM名取得 client = Client("ホスト名/IPアドレス", "ログインユーザ名", "パスワード") host = HostSystem.get(client, name=target_host) #ターゲットホストシステム情報取得 for vm in host.vm: if vm.name == target_vm: vm.PowerOnVM_Task() # ターゲットVMのPowerOn実行
if sys.argv[1] == "--host": hostname = sys.argv[2] # Read config config = ConfigParser.SafeConfigParser() for configfilename in [ os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini' ]: if os.path.exists(configfilename): config.read(configfilename) break try: client = Client( config.get('auth', 'host'), config.get('auth', 'user'), config.get('auth', 'password'), ) except Exception, e: client = None #print >> STDERR "Unable to login (only cache avilable): %s", str(e) # acitually do the work if hostname is None: inventory = get_inventory(client, config) else: inventory = get_single_host(client, config, hostname) # return to ansible print inventory
e.g. reconfig_vm test """ import sys import time from psphere.client import Client from psphere.soap import VimFault from psphere.managedobjects import VirtualMachine from psphere.errors import ObjectNotFoundError vm_name = sys.argv[1] client = Client() new_config = client.create("VirtualMachineConfigSpec") new_config.numCPUs = 2 try: vm = VirtualMachine.get(client, name=vm_name) except ObjectNotFoundError: print("ERROR: No VM found with name %s" % vm_name) print("Reconfiguring %s" % vm_name) if vm.config.hardware.numCPU == 2: print("Not reconfiguring %s as it already has 2 CPUs" % vm_name) sys.exit() try: task = vm.ReconfigVM_Task(spec=new_config)
from ssl import SSLContext, PROTOCOL_SSLv23, CERT_NONE from psphere.client import Client context = SSLContext(PROTOCOL_SSLv23) context.verify_mode = CERT_NONE test_client = Client("192.168.0.14", "root", "password", sslcontext=context) print(test_client.si.CurrentTime()) test_client.logout()
def __init__(self, key, secret=None, secure=True, host=None): self.key = key self.secret = secret self.host = host self.connection = Client(server=host, username=key, password=secret)
def main(): client = Client() vd = Discovery(client) vd.discovery(sys.argv[1])
#!/usr/bin/python import sys from psphere.client import Client from psphere.managedobjects import HostSystem, VirtualMachine client = Client(sys.argv[1], sys.argv[2], sys.argv[3]) host_systems = HostSystem.all(client) print("HostSystem.all(client) finds these hosts") for host_system in host_systems: print(host_system.name) vm = VirtualMachine.get(client, name="genesis", overallStatus="green") print('VirtualMachine.get(client, name="genesis", overallStatus="green")' ' got the following host:') print("Name: %s" % vm.name) print("overallStatus: %s" % vm.overallStatus)
#!/bin/env python from psphere.client import Client from psphere.managedobjects import HostSystem esxi_host = sys.argv[1] #HyperVisor hostname username = sys.argv[2] #HyperVisor login username password = sys.argv[3] #HyperVisor login password client = Client(esxi_host, username, password) hosts = HostSystem.all(client) cpu_usage = hosts[0].summary.quickStats.overallCpuUsage print cpu_usage
def main(): client = Client() dsf = DatastoreFiles(client) dsf.list_files() client.logout()
if sys.argv[1] == "--host": hostname = sys.argv[2] # Read config config = ConfigParser.SafeConfigParser() me = os.path.abspath(sys.argv[0]).rstrip('.py') for configfilename in [me + '.ini', 'vmware.ini']: if os.path.exists(configfilename): config.read(configfilename) break mename = os.path.basename(me).upper() host = os.getenv('VMWARE_' + mename + '_HOST',os.getenv('VMWARE_HOST', config.get('auth','host'))) user = os.getenv('VMWARE_' + mename + '_USER', os.getenv('VMWARE_USER', config.get('auth','user'))) password = os.getenv('VMWARE_' + mename + '_PASSWORD',os.getenv('VMWARE_PASSWORD', config.get('auth','password'))) try: client = Client( host,user,password ) except Exception, e: client = None #print >> STDERR "Unable to login (only cache available): %s", str(e) # Actually do the work if hostname is None: inventory = get_inventory(client, config) else: inventory = get_single_host(client, config, hostname) # Return to ansible print inventory
def exportVM(serverIp, user, passwd, vmName, workingDir): try: print "Connecting to the server...." client = Client(serverIp, user, passwd) except WebFault: print "Can't connect to the server" sys.exit(1) print "Connected" validVms = {} if vmName <> 'all': try: vm = VirtualMachine.get(client, name=vmName) if vm.runtime.powerState <> 'poweredOff': print 'Skipping VM:' + vm.name + ' VM is not powered off' sys.exit(5) if len(vm.network) <> 1: print 'Skipping VM:' + vm.name + ' The number of network devices is not equal to 1' sys.exit(5) vmdkPath = getVMDKUri(serverIp, vm) if vmdkPath != None: validVms[vm.name] = vmdkPath except ObjectNotFoundError: print 'Invalid VM name' client.logout() sys.exit(2) else: # inspect all vms vms = VirtualMachine.all(client) for vm in vms: if vm.runtime.powerState <> 'poweredOff': print 'Skipping VM:' + vm.name + ' VM is not powered off' continue if len(vm.network) <> 1: print 'Skipping VM:' + vm.name + ' The number of network devices is not equal to 1' continue vmdkPath = getVMDKUri(serverIp, vm) if vmdkPath != None: validVms[vm.name] = vmdkPath else: continue client.logout() if len(validVms.keys()) == 0: print 'Nothing to export' sys.exit(2) # get vmdks for all valid vms for vmName in validVms.keys(): directory = workingDir + '/' + vmName + '/' if not os.path.exists(directory): os.makedirs(directory) VmdkUri = validVms[vmName] downloadFile(VmdkUri, user, passwd, directory + vmName + '.vmdk') extends = parseVMDK(directory + vmName + '.vmdk') if extends == None: print 'No accessable extends' sys.exit(3) else: available = getAvalableDiskSpaceBytes(workingDir) for s in extends.values(): available = available - s if available < 0: print 'There is not enough free disk space to download all extends for VM:' + vmName exit(4) for e in extends.keys(): m = re.match('^(.+?)/folder/(.+?)/(.+?)\?(.+)$', VmdkUri) uri = m.group(1) + '/folder/' + m.group(2) + '/' + urllib2.quote(e) + '?' + m.group(4) downloadFile(uri, user, passwd, directory + e) sys.exit(0)