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 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(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 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 upload_ova(hostname, username, password, name, datastore, cluster, datacenter, url, host): client = Client(server=hostname, username=username, password=password) try: VirtualMachine.get(client, name=name) print "VSPHERE: A Machine with that name already exists" sys.exit(127) except ObjectNotFoundError: pass client.logout() cmd_args = ['ovftool'] cmd_args.append("--datastore=%s" % datastore) cmd_args.append("--name=%s" % name) cmd_args.append("--vCloudTemplate=True") cmd_args.append(url) cmd_args.append("vi://%s@%s/%s/host/%s" % (username, hostname, datacenter, cluster)) print "VSPHERE: Running OVFTool..." proc = subprocess.Popen(cmd_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out_string = "" while "'yes' or 'no'" not in out_string and "Password:"******"'yes' or 'no'" in out_string: proc.stdin.write("yes\n") proc.stdin.flush() print "VSPHERE: Added host to SSL hosts" out_string = "" while "Password:"******"\n") output = proc.stdout.read() error = proc.stderr.read() if "successfully" in output: print " VSPHERE: Upload completed" return 0, output else: print "VSPHERE: Upload did not complete" return -1, "\n".join([output, error])
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()
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()
print("Not reconfiguring %s as it already has 2 CPUs" % vm_name) sys.exit() try: task = vm.ReconfigVM_Task(spec=new_config) except VimFault, e: print("Failed to reconfigure %s: " % e) sys.exit() while task.info.state in ["queued", "running"]: print("Waiting 5 more seconds for VM creation") time.sleep(5) task.update() if task.info.state == "success": elapsed_time = task.info.completeTime - task.info.startTime print("Successfully reconfigured VM %s. Server took %s seconds." % (vm_name, elapsed_time.seconds)) elif task.info.state == "error": print("ERROR: The task for reconfiguring the VM has finished with" " an error. If an error was reported it will follow.") try: print("ERROR: %s" % task.info.error.localizedMessage) except AttributeError: print("ERROR: There is no error message available.") else: print("UNKNOWN: The task reports an unknown state %s" % task.info.state) # All done client.logout()
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 main(): client = Client() dsf = DatastoreFiles(client) dsf.list_files() client.logout()
from __future__ import absolute_import, division, print_function from ssl import CERT_NONE, PROTOCOL_SSLv23, SSLContext from psphere.client import Client if __name__ == '__main__': context = SSLContext(PROTOCOL_SSLv23) context.verify_mode = CERT_NONE test_client = Client('localhost:8989', 'user', 'pass', sslcontext=context) print(test_client.si.CurrentTime()) test_client.logout()
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)
def run(self): client = Client() hsev = client.find_entity_view('HostSystem', filter={'name': self.server}) for network in hsev.network: print network.name client.logout()
class ListDatastoreContents: def __init__(self, args): self.dcname = args.datacenter self.dsname = args.datastore self.server = config._config_value('general', 'server', args.server) self.username = config._config_value('general', 'username', args.username) self.password = config._config_value('general', 'password', args.username) self.client = None self.datacenter = None self.datastore = None def validate(self): pass def identify_datacenter(self): dcs = Datacenter.all(self.client) if self.dcname is None: self.datacenter = dcs[0] logging.info('defaulting to data center %s' % (self.datacenter.name)) else: for dc in dcs: if dc.name == self.dcname: self.datacenter = dc break if self.datacenter is None: raise ValueError('no data center named %s' % (self.dcname)) def identify_datastore(self): dss = self.datacenter.datastore if self.dsname is None: self.datastore = dss[0] logging.info('defaulting to data store %s' % (self.datastore.info.name)) else: for ds in dss: if ds.info.name == self.dsname: self.datastore = ds break if self.datastore is None: raise ValueError('no data store named %s' % (self.dsname)) def list_files(self): browser = self.datastore.browser rootpath = '[%s] /' % (self.datastore.info.name) task = browser.SearchDatastoreSubFolders_Task(datastorePath=rootpath) while task.info.state == 'running': print '.', time.sleep(3) task.update() print 'done' for resultlist in task.info.result: # first entry is a type descriptor, skip over it for result in resultlist[1:]: for r in result: try: for f in r.file: print os.path.join(r.folderPath, f.path) except AttributeError: pass def run(self): logging.info('connecting to %s', self.server) self.client = Client() self.identify_datacenter() self.identify_datastore() self.list_files() self.client.logout()
class VSphere(object): """ Class represents a vSphere client. Example usage: my_client = sut.VSphere('16.xx.xx.xx', 'user1', 'passwd1') my_vm = my_client.get_vm('user1_vm1') my_client.power_on_vm(my_vm) my_client.end_session() """ 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 end_session(self): """ Terminates session with vSphere client """ self.client.logout() def get_vm(self, vm_name): try: vm = VirtualMachine.get(self.client, name=vm_name) except ObjectNotFoundError: log._warn("Error finding VM '%s', does not exist within client" % (vm_name)) return False return vm def power_on_vm(self, vm_name): """ Powers on a VM defined in the Client Params: - vm_name: (str) The name of the virtual machine. (Ex. 'cosmos-jvm') """ vm = self.get_vm(vm_name) if vm.runtime.powerState == "poweredOn": log._warn("ERROR: %s is already powered on." % vm.name) else: try: log._info("Powering on %s" % vm.name) task = vm.PowerOnVM_Task() except VimFault as e: log._warn("ERROR: Failed to power on %s %s" % (vm.name, e)) def power_off_vm(self, vm_name): """ Powers off a VM defined in the Client Params: - vm: (str) The name of the virtual machine. (Ex. 'cosmos-jvm') """ vm = self.get_vm(vm_name) if vm.runtime.powerState == "poweredOff": log._warn("ERROR: %s is already powered off." % vm.name) else: try: log._info("Powering off %s" % vm.name) task = vm.PowerOffVM_Task() except VimFault as e: log._warn("ERROR: Failed to power off %s %s" % (vm.name, e)) def suspend_vm(self, vm): """ Powers off a VM defined in the Client Params: - vm: (str) The name of the virtual machine. (Ex. 'cosmos-jvm') """ if vm.runtime.powerState in ["poweredOff", "suspended"]: log._warn( "ERROR: %s is powered off or suspended. Cannot suspend." % vm.name) else: try: log._info("Suspending %s" % vm.name) task = vm.SuspendVM_Task() except VimFault as e: log._warn("ERROR: Failed to suspend %s %s" % (vm.name, e)) def reset_vm(self, vm): """ Resets the virtual machine Params: - vm: (str) The name of the virtual machine. (Ex. 'cosmos-jvm') """ try: log._info("Restarting %s" % vm.name) task = vm.RestartVM_Task() except VimFault as e: log._warn("ERROR: Failed to restart %s %s" % (vm.name, e)) def destroy_vm(self, vm_name): """ Destroys VM*, deleting its contents and removing it from parent folder Params: - vm: (str) The name of the virtual machine to be deleted. *Assumes proper permissions (VirtualMachine.Inventory.Delete) """ vm = VirtualMachine.get(self.client, name=vm_name) try: log._info("Destroying %s" % vm.name) task = vm.Destroy_Task() except VimFault as e: log._warn("ERROR: Failed to destroy %s %s" % (vm.name, e)) def clone_vm(self, source_vm_name, dest_vm_name, power_on=False, is_template=False): """ Creates a clone of virtual machine 'vm'. If the vm is a template, this method corresponds to deploying from a template Params: - (str)source_vm: Name of Virtual machine (or template) to clone - (str)dest_vm_name: Name of the new clone Optional: - power_on: Option to power on the cloned vm after creation - is_template: Option to mark cloned vm as a template * Assumes proper permissions. The privilege required on the source virtual machine depends on the source and destination types: - source is virtual machine, destination is virtual machine - VirtualMachine.Provisioning.Clone - source is virtual machine, destination is template - VirtualMachine.Provisioning.CreateTemplateFromVM - source is template, destination is virtual machine - VirtualMachine.Provisioning.DeployTemplate - source is template, destination is template - VirtualMachine.Provisioning.CloneTemplate """ # host_system = HostSystem.get(client, name=vm_host) # check to see if dest_vm already exists try: vm = VirtualMachine.get(self.client, name=dest_vm_name) if vm.name == dest_vm_name: log._warn("ERROR: Destination VM '%s' already exists." % dest_vm_name) return False except ObjectNotFoundError: pass # we want the object to not be found :) # also, check to see if the source vm exists try: source_vm = VirtualMachine.get(self.client, name=source_vm_name) except ObjectNotFoundError: log._warn("ERROR: No VM with name \"%s\" to clone" % source_vm_name) return False vm_clone_spec = self.client.create("VirtualMachineCloneSpec") vm_reloc_spec = self.client.create("VirtualMachineRelocateSpec") vm_reloc_spec.datastore = source_vm.datastore # [0] vm_reloc_spec.pool = source_vm.resourcePool vm_reloc_spec.host = None # vm_reloc_spec.disk = None #[] vm_reloc_spec.transform = None vm_clone_spec.powerOn = power_on vm_clone_spec.template = is_template vm_clone_spec.location = vm_reloc_spec vm_clone_spec.snapshot = None # Datacenter folder datacenter_folder = source_vm.parent.parent.vmFolder try: log._info("Attempting to clone %s" % source_vm.name) task = source_vm.CloneVM_Task(folder=datacenter_folder, name=dest_vm_name, spec=vm_clone_spec) except VimFault as e: log._warn("ERROR: Failed to clone '%s'" % e) return False while task.info.state in ["queued", "running"]: log._info("Waiting 5 more seconds for VM creation") time.sleep(5) task.update() if task.info.state == "success": elapsed_time = task.info.completeTime - task.info.startTime log._info( "Successfully cloned VM %s from %s. Server took %s seconds." % (dest_vm_name, source_vm_name, elapsed_time.seconds)) elif task.info.state == "error": log._warn("ERROR: The task for cloning the VM has finished with" " an error. If an error was reported it will follow.") try: log._warn("ERROR: %s" % task.info.error.localizedMessage) except AttributeError: log._warn("ERROR: There is no error message available.") else: log._warn("UNKNOWN: The task reports an unknown state %s" % task.info.state) def deploy_from_ovf(self, ovf_path, vm_name): """ Deploys a VM from an .ovf file """ pass # def get_descriptor(ovf_path): # """ # Opens .ovf file and returns descriptor # """ # fh = open(ovf_path, "r") # ovf_descriptor = fh.read() # fh.close() # return ovf_descriptor # ''' # https://groups.google.com/forum/#!topic/pysphere/NkTOy_GSaKw # def parse_descriptor(ovf_descriptor): # ovf_manager = s._do_service_content.OvfManager # request = VI.ParseDescriptorRequestMsg() # _this =request.new__this(ovf_manager) # _this.set_attribute_type(ovf_manager.get_attribute_type()) # request.set_element__this(_this) # request.set_element_ovfDescriptor(ovf_descriptor) # pdp = request.new_pdp() # pdp.set_element_locale("") # pdp.set_element_deploymentOption("") # request.set_element_pdp(pdp) # return s._proxy.ParseDescriptor(request)._returnval # ''' # def deploy(args): # """ # """ # ovfdesc = get_descriptor(ovf_path) # ovfmgr = self.client.sc.ovfManager # descriptor_info = parse_descriptor(o) # descriptor_info = ovfmgr.ParseDescriptor(ovfdesc) # ovfimportresult = ovfmgr.CreateImportSpec(ovfDescriptor=ovfdesc, resourcePool=resourcepool, datastore=dstore, cisp=ocisp) # httpNfcLease = resourcepool.ImportVApp(spec=ovfimportresult.importSpec, folder=dl.vmFolder) def create_snapshot(self, vm_name, snapshot_name): """ Creates a snapshot of 'vm' with name of 'snapshot_name' Both arguments are type 'str' """ try: vm = VirtualMachine.get(self.client, vm_name) except ObjectNotFoundError: log._warn("ERROR: No VM with name \"%s\" to clone" % source_vm_name) return False try: log._info("Creating snapshot for VM: %s" % vm.name) # task = vm.CreateSnapshot_Task(name=snapshot_name, memory=False, quiesce=False) task = vm.CreateSnapshot_Task(name=snapshot_name, memory=True, quiesce=True) except VimFault as e: log._warn("Failed to create snapshot %s: " % e) while task.info.state in ["queued", "running"]: log.info("Waiting 5 more seconds for VM snapshot to complete") time.sleep(5) task.update() if task.info.state == "success": elapsed_time = task.info.completeTime - task.info.startTime log._info( "Successfully create snapshot for VM %s. Processing took %s seconds." % (vm_name, elapsed_time.seconds)) elif task.info.state == "error": log._warn( "ERROR: The task for creating the VM snapshot has finished with an error. If an error was reported it will follow." ) try: log._warn("ERROR: %s" % task.info.error.localizedMessage) except AttributeError: log._warn("ERROR: There is no error message available.") else: log._warn("UNKNOWN: The task reports an unknown state %s" % task.info.state)