def main(): """ Simple command-line program for executing a process in the VM without the network requirement to actually access it. """ args = get_args() try: if args.disable_ssl_verification: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() # if instanceUuid is false it will search for VM BIOS UUID instead vm = content.searchIndex.FindByUuid(datacenter=None, uuid=args.vm_uuid, vmSearch=True, instanceUuid=False) if not vm: raise SystemExit("Unable to locate the virtual machine.") tools_status = vm.guest.toolsStatus if (tools_status == 'toolsNotInstalled' or tools_status == 'toolsNotRunning'): raise SystemExit( "VMwareTools is either not running or not installed. " "Rerun the script after verifying that VMwareTools " "is running") creds = vim.vm.guest.NamePasswordAuthentication(username=args.vm_user, password=args.vm_pwd) try: pm = content.guestOperationsManager.processManager ps = vim.vm.guest.ProcessManager.ProgramSpec( programPath=args.path_to_program, arguments=args.program_arguments) res = pm.StartProgramInGuest(vm, creds, ps) if res > 0: print "Program executed, PID is %d" % res except IOError, e: print e except vmodl.MethodFault as error: print "Caught vmodl fault : " + error.msg return -1 return 0
def connect(self): ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # ssl_context.verify_mode = ssl.CERT_NONE try: self.si = connect.SmartConnect(host=self._host, port=self._port, user=self._user, pwd=self._pwd, sslContext=ssl_context, **self._kwargs) except ssl.SSLError: try: self.si = connect.SmartConnectNoSSL(host=self._host, port=self._port, user=self._user, pwd=self._pwd, **self._kwargs) except Exception: LOG.Exception( _LE("Exception connect to the specified vcenter using " "specified username and password")) finally: if self.si is None: LOG.error( _LE("Could not connect to the specified vcenter using " "specified username and password"))
def main(): """ Simple command-line program for listing the virtual machines on a system. """ args = cli.get_args() try: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) if not service_instance: print("Could not connect to the specified host using specified " "username and password") return -1 atexit.register(connect.Disconnect, service_instance) # ## Do the actual parsing of data ## # parse_service_instance(service_instance) except vmodl.MethodFault, e: print "Caught vmodl fault : " + e.msg return -1
def main(): args = get_args() if args.date: try: dt = datetime.strptime(args.date, '%d/%m/%Y %H:%M') except ValueError: print('Unrecognized date format') raise return -1 if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host, args.user)) # try: # si = connect.SmartConnectNoSSL(host=args.host, # user=args.user, # pwd=password, # port=int(args.port)) # except vim.fault.InvalidLogin: # print("Could not connect to the specified host using specified " # "username and password") # return -1 si = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=password, port=int(args.port)) atexit.register(connect.Disconnect, si) # vm = None # view = si.content.viewManager.CreateContainerView(si.content.rootFolder, [vim.VirtualMachine], True) vms = [vm for vm in view.view if vm.name == args.vmname] if not vms: print('VM not found') connect.Disconnect(si) return -1 vm = vms[0] # vm = si.content.searchIndex.FindByDnsName(None, args.vmname, # True) # spec = vim.scheduler.ScheduledTaskSpec() # spec.name = 'PowerOff vm %s' % args.vmname # spec.description = 'poweroff vm machine' # spec.scheduler = vim.scheduler.OnceTaskScheduler() # spec.scheduler.runAt = dt # spec.action = vim.action.MethodAction() # spec.action.name = vim.VirtualMachine.PowerOff # spec.enabled = True # si.content.scheduledTaskManager.CreateScheduledTask(vm, spec) TASK = vm.PowerOff() tasks.wait_for_tasks(si, [TASK])
def connect_vsphere(username, password, hostname, port, use_ssl): """ Connects to a ESXi host or vCenter server. """ server = None try: if use_ssl: # Connect to server using SSL certificate verification server = connect.SmartConnect(host=hostname, user=username, pwd=password, port=port) else: server = connect.SmartConnectNoSSL(host=hostname, user=username, pwd=password, port=port) except vim.fault.InvalidLogin: print("ERROR: Invalid login credentials for user '%s'" % username) exit(1) except vim.fault as message: print("Error connecting to vSphere: %s" % str(message)) exit(1) # Ensures clean disconnect upon program termination atexit.register(connect.Disconnect, server) return server
def main(): """ Simple command-line program for listing the virtual machines on a system. """ # args = cli.get_args() try: service_instance = connect.SmartConnectNoSSL(host='', user='', pwd='', port=443) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() container = content.rootFolder # starting point to look into viewType = [vim.VirtualMachine] # object types to look for recursive = True # whether we should look into it recursively containerView = content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view for child in children: print_vm_info(child) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def main(): """ Simple command-line program for creating a first class disk. """ args = get_args() try: if args.disable_ssl_verification: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() # Connect to SPBM Endpoint pbmSi = pbmhelper.create_pbm_session(service_instance._stub) pbmContent = pbmSi.RetrieveContent() # Retrieving Storage Policy if args.policy: policy = pbmhelper.retrieve_storage_policy(pbmContent, args.policy) else: policy = None # Retrieve Datastore Object datastore = disk.get_obj(content, [vim.Datastore], args.datastore) # Setting FCD Specifications spec = vim.vslm.CreateSpec() spec.name = args.name spec.capacityInMB = args.capacityInGB * 1024 if args.keepAfterDeleteVm: spec.keepAfterDeleteVm = True spec.backingSpec = vim.vslm.CreateSpec.DiskFileBackingSpec() spec.backingSpec.provisioningType = "thin" spec.backingSpec.datastore = datastore if policy: spec.profile = [ vim.vm.DefinedProfileSpec(profileId=policy.profileId.uniqueId) ] # Create FCD storage = content.vStorageObjectManager task = storage.CreateDisk_Task(spec) tasks.wait_for_tasks(service_instance, [task]) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def main(): """Simple program to test connectivity to vSphere host""" args = get_args() try: if args.disable_ssl_verification: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) print("\nHello World!\n") print( "If you got here, you have authenticated to vSphere successfully!") session_id = service_instance.content.sessionManager.currentSession.key print("Current session id: {}".format(session_id)) except vmodl.MethodFault as error: print("Caught vmodl fault: " + error.msg) return -1 return 0
def main(): """ Simple command-line program for listing the virtual machines on a system. """ args = get_args() try: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) print "\nHello World!\n" print "If you got here, you authenticted into vCenter." print "The server is {}!".format(args.host) # NOTE (hartsock): only a successfully authenticated session has a # session key aka session id. session_id = service_instance.content.sessionManager.currentSession.key print "current session id: {}".format(session_id) print "Well done!" print "\n" print "Download, learn and contribute back:" print "https://github.com/vmware/pyvmomi-community-samples" print "\n\n" except vmodl.MethodFault as error: print "Caught vmodl fault : " + error.msg return -1 return 0
def connect(self): """Connect to the configured VMWare service & set self.conn""" try: SSLVerificationError = _get_ssl_error() try: debug("Connecting with SmartConnect - regular SSL") self.conn = connect.SmartConnect(host=self.ip_addr, user=self.username, pwd=self.password) except SSLVerificationError: try: ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ctx.verify_mode = ssl.CERT_NONE debug("Connecting with SmartConnec - TLSv1 and verify off") self.conn = connect.SmartConnect(host=self.ip_addr, user=self.username, pwd=self.password, sslContext=ctx) except (ssl.SSLEOFError, OSError): debug("Connecting with SmartConnectNoSSL") self.conn = connect.SmartConnectNoSSL(host=self.ip_addr, user=self.username, pwd=self.password) except vim.fault.InvalidLogin: error(f"ERROR: Invalid login for VMware server {self.ip_addr}", exit=True) debug("Connection successful")
def main(): config = initConf(confpath_argv()) vcc = connect.SmartConnectNoSSL(host=config['Connection']['host'], user=config['Connection']['user'], pwd=config['Connection']['pswd'], port=config['Connection']['port']) containerView = vcc.content.viewManager.CreateContainerView( vcc.content.rootFolder, [vim.VirtualMachine], recursive=True) resolv = [] for vm in containerView.view: try: for net in vm.guest.net: if ipaddress.IPv4Address(net.ipAddress[0]): resolv.append([ net.ipAddress[0], vm.guest.ipStack[0].dnsConfig.hostName ]) except: continue # Print bindings to stdout if config['Debug']['enabled']: for entry in resolv: print(entry[0].ljust(20) + entry[1]) # Populating hosts file if config['Hosts']['enabled']: hostsfile = open(file=config['Hosts']['path'], mode='w') hostsfile.write('127.0.0.1 localhost\n') for entry in resolv: hostsfile.write(entry[0].ljust(20) + entry[1] + "\n") hostsfile.close()
def main(): """ Simple command-line program for listing all snapshots of a fcd """ args = get_args() try: if args.disable_ssl_verification: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() # Retrieve Datastore Object datastore = disk.get_obj(content, [vim.Datastore], args.datastore) # Retrieve FCD Object all_vdisk = disk.retrieve_all_fcd(content, datastore) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def connect(self): self.service_instance = connect.SmartConnectNoSSL( host=self.host, user=self.username, pwd=self.password, port=self.port )
def authenticate_vc(self, host, username, password, port=443): vc = connect.SmartConnectNoSSL(host=host, user=username, pwd=password, port=port) atexit.register(connect.Disconnect, vc) return vc
def main(): """ Simple command-line program for retrieving a port group """ args = get_args() try: if args.disable_ssl_verification: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() # searching for port group pg = get_obj(content, [vim.Network], args.portgroupname) print(pg) except vmodl.MethodFault as error: print("Caught vmodl fault : {0}".format(error.msg)) return -1 return 0
def main(): try: # 如果需要使用SSL证书,则用,这里没有使用 # service_instance = connect.SmartConnect(host="HOST", # user="******", # pwd="密码", # port=端口,默认443) service_instance = connect.SmartConnectNoSSL(host="HOST", user="******", pwd="密码", port=端口,默认443) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() container = content.rootFolder # starting point to look into viewType = [vim.VirtualMachine] # object types to look for recursive = True # whether we should look into it recursively containerView = content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view for child in children: print_vm_info(child) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def connect(self): log.task("log in to vcenter".format(self.host)) log.info("connecting...") try: if self.insecure is False: service_instance = connect.SmartConnect(host=self.host, user=self.username, pwd=self.password, port=int(self.port)) atexit.register(connect.Disconnect, service_instance) self.service_instance = service_instance log.info("connection succeeded".format(self.host)) return service_instance elif self.insecure is True: service_instance = connect.SmartConnectNoSSL( host=self.host, user=self.username, pwd=self.password, port=int(self.port)) atexit.register(connect.Disconnect, service_instance) self.service_instance = service_instance log.info("connection succeeded".format(self.host)) return service_instance except Exception as e: quit("connection failed: {0}".format(e))
def __init__(self, h, po, nt, u, p): try: if nt: session = requests.session() session.verify = False urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning) self.connection = connect.SmartConnectNoSSL(host=h, user=u, pwd=p, port=int(po)) self.client = create_vsphere_client(server=h, username=u, password=p, session=session) else: session = requests.session() self.connection = connect.SmartConnect(host=h, user=u, pwd=p, port=int(po)) self.client = create_vsphere_client(server=h, username=u, password=p, session=session) self.content = self.connection.RetrieveContent() self.tag_association = self.client.tagging.TagAssociation self.tag_svc = self.client.tagging.Tag self.cat_svc = self.client.tagging.Category print('Connection Success') except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1
def si(self): if not hasattr(self, '_si'): self._si = connect.SmartConnectNoSSL(host='vcenter', user='******', pwd='my_pass') atexit.register(connect.Disconnect, self._si) return self._si
def getVM(args): try: vm = None socket.setdefaulttimeout(args.timeout) esxi = connect.SmartConnectNoSSL( host=args.host, user=args.username, pwd=args.password, port=args.port) atexit.register(connect.Disconnect, esxi) entity_stack = esxi.content.rootFolder.childEntity while entity_stack: entity = entity_stack.pop() if entity.name == args.vm: vm = entity del entity_stack[0:len(entity_stack)] return vm elif hasattr(entity, 'childEntity'): entity_stack.extend(entity.childEntity) elif isinstance(entity, vim.Datacenter): entity_stack.append(entity.vmFolder) if not isinstance(vm, vim.VirtualMachine): msg = "Virtual Machine %s not found." % args.vm sys.exit(msg) except vim.fault.InvalidLogin as e: msg = "Cannot complete login due to an incorrect user name or password." sys.exit(msg) except socket.timeout as e: msg = "Unable to connect to %s:%s (%s)" % (args.host, args.port, e) sys.exit(msg) except socket.gaierror as e: msg = "Unable to resolve %s (%s)" % (args.host, e) sys.exit(msg) except Exception as e: sys.exit(e)
def vm_info_for_ansible(virtual_machine, user, password): try: for vcenter in vcenters: #connection to vcenter service_instance = connect.SmartConnectNoSSL(host=vcenter, user=user, pwd=password) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() container = content.rootFolder # starting point to look into viewType = [vim.VirtualMachine] # object types to look for recursive = True # whether we should look into it recursively containerView = content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view pat = re.compile(virtual_machine, re.IGNORECASE) for child in children: if pat.search(child.summary.config.name) is not None: datacenter = find_datacenter(child) return datacenter, vcenter except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1
def main(): """ Simple command-line program for listing the virtual machines on a system. """ args = cli.get_args() try: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() children = content.rootFolder.childEntity for child in children: if hasattr(child, 'vmFolder'): datacenter = child else: # some other non-datacenter type object continue vm_folder = datacenter.vmFolder vm_list = vm_folder.childEntity for virtual_machine in vm_list: print_vm_info(virtual_machine, 10) except vmodl.MethodFault as error: print "Caught vmodl fault : " + error.msg return -1 return 0
def main(): args = get_args() try: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) except: print("Could not connect to the specified host using specified " "username and password") return -1 atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() search_index = content.searchIndex host = search_index.FindByDnsName(dnsName=args.vihost, vmSearch=False) perf = perfdata() counters = perf.perfcounters() for counter in counters: p = Thread(target=perf.run, args=( content, host, counter, )) p.start()
def __init__(self): self.service_instance = connect.SmartConnectNoSSL( host=DJANGO_SETTINGS.VMWARE_SERVER, user=DJANGO_SETTINGS.VMWARE_USERNAME, pwd=DJANGO_SETTINGS.VMWARE_PASSWD, port=443) atexit.register(connect.Disconnect, self.service_instance)
def get_service_instance(kwargs): host = kwargs.get('host') username = kwargs.get('username') password = kwargs.get('password') service_instance = connect.SmartConnectNoSSL(host=host, user=username, pwd=password, port=int(443)) if not service_instance: raise Exception('Could not connect to the specified host using specified username and password') return service_instance
def __init__(self, VMWARE_SERVER, VMWARE_USERNAME, VMWARE_PASSWD): self.server = VMWARE_SERVER self.service_instance = connect.SmartConnectNoSSL(host=VMWARE_SERVER, user=VMWARE_USERNAME, pwd=VMWARE_PASSWD, port=443) atexit.register(connect.Disconnect, self.service_instance)
def main(): """ Simple command-line program for listing the virtual machines on a system. """ args = get_args() try: if args.disable_ssl_verification: service_instance = connect.SmartConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) else: service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(connect.Disconnect, service_instance) content = service_instance.RetrieveContent() container = content.rootFolder # starting point to look into viewType = [vim.VirtualMachine] # object types to look for recursive = True # whether we should look into it recursively containerView = content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view if args.find is not None: pat = re.compile(args.find, re.IGNORECASE) for child in children: if args.find is None: print(child.summary.guest.ipAddress) print(child.summary.config.instanceUuid) print(child.summary.runtime.powerState) if len(child.guest.net[0].ipAddress) > 1: print(child.guest.net[0].ipAddress[1]) else: print(child.guest.net[0].ipAddress[0]) else: if pat.search(child.summary.config.name) is not None: # print_vm_info(child) print(child.summary.guest.ipAddress) print(child.summary.config.instanceUuid) print(child.summary.runtime.powerState) if len(child.guest.net[0].ipAddress) > 1: print(child.guest.net[0].ipAddress[1]) else: print(child.guest.net[0].ipAddress[0]) # prn_obj(child.config.hardware) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def connect_vcenter(ip): from pyVim import connect vcenter = ip vcenteruser = "******" vcenterpwd = "Testing%123" SI = connect.SmartConnectNoSSL(host=vcenter, user=vcenteruser, pwd=vcenterpwd, port=443) if not SI: test_util.test_fail("Unable to connect to the vCenter %s" % vcenter) return SI
def __init__(self, host, user, pwd, port): self.host = host self.user = user self.pwd = pwd self.port = port self.si = connect.SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port)
def get_windows_under_gid(host, login, passwd): vcenter_si = None try: vcenter_si = connect.SmartConnectNoSSL(host=host, user=login, pwd=passwd) except: logger.error("Can't login to {}".format(host)) return None content = vcenter_si.RetrieveContent() datacenter = content.rootFolder.childEntity[0] # datastores = datacenter.datastore vmfolder = datacenter.vmFolder raw_vmlist = vmfolder.childEntity perf_manager = content.perfManager # cluster = datacenter.hostFolder.childEntity[0] vmlist = get_all_vm_under_folder(raw_vmlist) vm_windows_attribute_key = get_attribute_key_by_name(content, LICENSED_WINDOWS_FIELD_NAME) gid_windows_count = defaultdict(list) # os_set = set() # for vm in vmlist: # os_set.add(vm.config.guestId) for vm in vmlist: # resourcePool is None means this it template if vm.resourcePool is None: continue top_parent_name = find_top_resource_pool(vm.resourcePool) vm_data = VM() vm_data.name = vm.name vm_data.resource_pool_name = vm.resourcePool.name vm_data.top_resource_pool_name = top_parent_name vm_data.config_cpu = vm.summary.config.numCpu vm_data.config_ram = vm.summary.config.memorySizeMB vm_data.os = vm.config.guestId vm_data.powered_on = vm.summary.runtime.powerState == "poweredOn" if vm_data.powered_on: # and vm_data.os.startswith("win"): cpu_usage, mem_usage = get_vm_resource_usage(perf_manager, vm) vm_data.cpu_usage = cpu_usage.avg vm_data.ram_usage = mem_usage.avg if vm_windows_attribute_key is not None: for tag in vm.value: if tag.key == vm_windows_attribute_key and tag.value == LICENSED_WINDOWS_FIELD_VALUE: vm_data.windows_licensed = True gid_windows_count[top_parent_name].append(vm_data) # if vm.config.guestId.startswith('win'): # top_parent_name = find_top_resource_pool(vm.resourcePool) # if top_parent_name is not None and top_parent_name.startswith('GID'): # if top_parent_name is not None and 'GID' in top_parent_name: # gid_windows_count[top_parent_name] += 1 # total_gid_windows_count = 0 # for k, v in sorted(gid_windows_count.items()): # logger.debug("{} have {} windows.".format(k, v)) # total_gid_windows_count += v # logger.info('Total: {}'.format(total_gid_windows_count)) connect.Disconnect(vcenter_si) return {"host": host, "gid_windows_count": gid_windows_count}