Python pyVim.connect.SmartConnectNoSSL() Examples

The following are 30 code examples of pyVim.connect.SmartConnectNoSSL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyVim.connect , or try the search function .
Example #1
Source File: add_portgroup_to_vswitch.py    From pyvmomi-community-samples with Apache License 2.0 7 votes vote down vote up
def main():
    args = get_args()
    if args.skip_verification:
        serviceInstance = SmartConnectNoSSL(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=443)
    else:
        serviceInstance = SmartConnect(host=args.host,
                                       user=args.user,
                                       pwd=args.password,
                                       port=443)
    atexit.register(Disconnect, serviceInstance)
    content = serviceInstance.RetrieveContent()

    hosts = GetVMHosts(content, args.regex_esxi)
    AddHostsPortgroup(hosts, args.vswitch, args.portgroup, args.vlanid)


# Main section 
Example #2
Source File: utils_pyvmomi.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def connect(self):
        """
        Initialize the service instance to the VSphere server
        """
        # Check if an valid connection has already been establised.
        # If yes, just refresh the connection to keep it alive.
        # If not, close the old connection and establise a new one.
        if self.is_conn_dead():
            self.close()
        else:
            self.keep_alive()
            return

        kwargs = self.kwargs

        if self.insecure:
            self.service_instance = SmartConnectNoSSL(**kwargs)
        else:
            self.service_instance = SmartConnect(**kwargs)

        if self.service_instance:
            logging.debug(
                'New vsphere connection established: %s (%s)',
                self.service_instance, id(self.service_instance)) 
Example #3
Source File: filter_vms.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def main():
    args = setup_args()
    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=args.password,
                           port=args.port)
    # Start with all the VMs from container, which is easier to write than
    # PropertyCollector to retrieve them.
    vms = get_obj(si, si.content.rootFolder, [vim.VirtualMachine])

    pc = si.content.propertyCollector
    filter_spec = create_filter_spec(pc, vms, args.property)
    options = vmodl.query.PropertyCollector.RetrieveOptions()
    result = pc.RetrievePropertiesEx([filter_spec], options)
    vms = filter_results(result, args.value)
    print("VMs with %s = %s" % (args.property, args.value))
    for vm in vms:
        print(vm.name)

    Disconnect(si) 
Example #4
Source File: run.py    From vcenter-netbox-sync with Apache License 2.0 5 votes vote down vote up
def authenticate(self):
        """Create a session to vCenter and authenticate against it"""
        log.info(
            "Attempting authentication to vCenter instance '%s'.",
            self.vc_host
            )
        try:
            vc_instance = SmartConnectNoSSL(
                host=self.vc_host,
                port=self.vc_port,
                user=self.vc_user,
                pwd=self.vc_pass,
                )
            atexit.register(Disconnect, vc_instance)
            self.vc_session = vc_instance.RetrieveContent()
            log.info(
                "Successfully authenticated to vCenter instance '%s'.",
                self.vc_host
                )
        except (gaierror, vim.fault.InvalidLogin, OSError) as err:
            if isinstance(err, OSError):
                err = "System unreachable."
            err_msg = (
                "Unable to connect to vCenter instance '{}' on port {}. "
                "Reason: {}".format(self.vc_host, self.vc_port, err)
                )
            log.critical(err_msg)
            raise ConnectionError(err_msg) 
Example #5
Source File: ezmomi.py    From ezmomi with MIT License 5 votes vote down vote up
def connect(self):
        """Connect to vCenter server"""
        try:
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            if self.config['no_ssl_verify']:
                requests.packages.urllib3.disable_warnings()
                context.verify_mode = ssl.CERT_NONE
                self.si = SmartConnectNoSSL(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    certFile=None,
                    keyFile=None,
                )
            else:
                self.si = SmartConnect(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    sslContext=context,
                    certFile=None,
                    keyFile=None,
                )
        except Exception as e:
            print('Unable to connect to vsphere server.')
            print(e)
            sys.exit(1)

        # add a clean up routine
        atexit.register(Disconnect, self.si)

        self.content = self.si.RetrieveContent() 
Example #6
Source File: nsxt_vcenter_moids.py    From ansible-module-chaperone with Apache License 2.0 5 votes vote down vote up
def main():
  argument_spec = vmware_argument_spec()
 
  argument_spec.update(
        dict(hostname= dict(required=True, type='str'),
            username=dict(required=True, type='str'),
            password=dict(required=True, type='str'),
            datacenter=dict(required=True, type='str'),
            cluster=dict(required=True, type='str'),
            datastore=dict(required=True,type='str'),
            portgroup1= dict(required=True,type='str'),
            portgroup2= dict(required=True, type='str'),
            portgroup3=dict(required=True, type='str')))

  module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
  try:
	logger.info("Trying to connect to VCENTER SERVER . . .")
	si = SmartConnectNoSSL(host=module.params['hostname'],
						   user=module.params['username'],
						   pwd=module.params['password'],
						   port=443)
        logger.info("Connected to VCENTER SERVER !")
  except IOError, e:
	#pass
	#atexit.register(Disconnect, si)
	logger.info("Connection failed {0}")
        module.fail_json(changed=False, msg="Failed to connect vCenter") 
Example #7
Source File: get_vm_names.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for listing the virtual machines on a host.
    """

    args = setup_args()
    si = None
    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=int(args.port))
        atexit.register(Disconnect, si)
    except vim.fault.InvalidLogin:
        raise SystemExit("Unable to connect to host "
                         "with supplied credentials.")

    content = si.RetrieveContent()
    for child in content.rootFolder.childEntity:
        if hasattr(child, 'vmFolder'):
            datacenter = child
            vmfolder = datacenter.vmFolder
            vmlist = vmfolder.childEntity
            for vm in vmlist:
                printvminfo(vm)

# Start program 
Example #8
Source File: configure_dvs_port_group.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = SmartConnectNoSSL(host=args.host,
                                                 user=args.user,
                                                 pwd=args.password,
                                                 port=args.port)
        else:
            service_instance = SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=args.port)

        atexit.register(Disconnect, service_instance)

        # call configuration of dvs port group
        configure_dvs_pg(service_instance, args.dvs_name, args.dvs_pg_name)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : {0}".format(error.msg))
        return -1

    return 0


# Start program 
Example #9
Source File: add_raw_disk_to_vm.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()

    # create the service instance
    si = None
    if args.disable_ssl_verification:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=args.port)
    else:
        si = SmartConnect(host=args.host,
                          user=args.user,
                          pwd=args.password,
                          port=args.port)

    # disconnect the service instance at program exit
    atexit.register(Disconnect, si)

    vm = None
    if args.uuid:
        search_index = si.content.searchIndex
        vm = search_index.FindByUuid(None, args.uuid, True)
    elif args.vm_name:
        content = si.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)

    if vm:
        add_raw_disk(vm, si, args.device_name,
                     args.disk_mode, args.compatibility_mode)
    else:
        print "VM not found"


# start this thing 
Example #10
Source File: get_portgroup.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
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


# Start program 
Example #11
Source File: relocate_events.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = setup_args()
    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=args.password,
                           port=args.port)
    if args.datacenter:
        dc = get_dc(si, args.datacenter)
    else:
        dc = si.content.rootFolder.childEntity[0]

    vm = si.content.searchIndex.FindChild(dc.vmFolder, args.name)
    if vm is None:
        raise Exception('Failed to find VM %s in datacenter %s' %
                        (dc.name, args.name))
    byEntity = vim.event.EventFilterSpec.ByEntity(entity=vm, recursion="self")
    ids = ['VmRelocatedEvent', 'DrsVmMigratedEvent', 'VmMigratedEvent']
    filterSpec = vim.event.EventFilterSpec(entity=byEntity, eventTypeId=ids)

    # Optionally filter by users
    userList = []
    if args.filterUsers:
        userList = re.split('.*,.*', args.filterUsers)
    if len(userList) > 0 or args.filterSystemUser:
        byUser = vim.event.EventFilterSpec.ByUsername(userList=userList)
        byUser.systemUser = args.filterSystemUser
        filterSpec.userName = byUser
    eventManager = si.content.eventManager
    events = eventManager.QueryEvent(filterSpec)

    for event in events:
        print("%s" % event._wsdlName)
        print("VM: %s" % event.vm.name)
        print("User: %s" % event.userName)
        print("Host: %s -> %s" % (event.sourceHost.name, event.host.name))
        print("Datacenter: %s -> %s" % (event.sourceDatacenter.name,
                                        event.datacenter.name))
        print("Datastore: %s -> %s" % (event.sourceDatastore.name,
                                       event.ds.name))
    print("%s" % events) 
Example #12
Source File: fcd_list_vdisk_snapshots.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
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
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Retrieve all Snapshots
        list_fcd_snapshots(content, vdisk)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0


# Start program 
Example #13
Source File: vmware.py    From DevOps with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #14
Source File: vsphere.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def apply_terraform(self, cluster, hosts_dict):
        vars = cluster.plan.mixed_vars
        st = connect.SmartConnectNoSSL(host=vars['vc_host'], user=vars['vc_username'],
                                       pwd=vars['vc_password'], port=vars['vc_port'])
        content = st.RetrieveContent()
        container = content.rootFolder
        dc = get_obj(content, [vim.Datacenter], container, vars['region'])
        folder = get_obj(content, [vim.Folder], container, 'kubeoperator')
        if not folder:
            dc.vmFolder.CreateFolder('kubeoperator')
        return super().apply_terraform(cluster, hosts_dict) 
Example #15
Source File: vsphere.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def get_service_instance(kwargs):
    host = kwargs.get('host')
    username = kwargs.get('username')
    password = kwargs.get('password')
    port = kwargs.get('port')
    service_instance = connect.SmartConnectNoSSL(host=host, user=username, pwd=password, port=port)
    if not service_instance:
        logger.error(msg='Could not connect to the specified host using specified username and password',
                     exc_info=True)
        raise Exception('Could not connect to the specified host using specified username and password')
    return service_instance 
Example #16
Source File: vsphere-monitor.py    From vsphere-monitor with Apache License 2.0 5 votes vote down vote up
def hello_vcenter(vchost,username,password,port):
    try:
        si = SmartConnectNoSSL(
            host=vchost,
            user=username,
            pwd=password,
            port=port)

        atexit.register(Disconnect, si)
        return True, "ok"
    except vmodl.MethodFault as error:
        return False, error.msg
    except Exception as e:
        return False, str(e) 
Example #17
Source File: add_nic_to_vm.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()

    # connect this thing
    serviceInstance = None
    if args.no_ssl:
        serviceInstance = SmartConnectNoSSL(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    else:
        serviceInstance = SmartConnect(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    # disconnect this thing
    atexit.register(Disconnect, serviceInstance)

    vm = None
    if args.uuid:
        search_index = serviceInstance.content.searchIndex
        vm = search_index.FindByUuid(None, args.uuid, True)
    elif args.vm_name:
        content = serviceInstance.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)

    if vm:
        add_nic(serviceInstance, vm, args.port_group)
    else:
        print("VM not found")


# start this thing 
Example #18
Source File: esxi.py    From esxi_stats with MIT License 5 votes vote down vote up
def esx_connect(host, user, pwd, port, ssl):
    """Establish connection with host/vcenter."""
    si = None

    # connect depending on SSL_VERIFY setting
    if ssl is False:
        si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port)
        current_session = si.content.sessionManager.currentSession.key
        _LOGGER.debug("Logged in - session %s", current_session)
    else:
        si = SmartConnect(host=host, user=user, pwd=pwd, port=port)
        current_session = si.content.sessionManager.currentSession.key
        _LOGGER.debug("Logged in - session %s", current_session)

    return si 
Example #19
Source File: vmutils.py    From devops with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, user, pwd):
        session = SmartConnectNoSSL(host=host, user=user, pwd=pwd)
        self.session = session 
Example #20
Source File: relocate_vm.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = SmartConnectNoSSL(host=args.host,
                                                 user=args.user,
                                                 pwd=args.password,
                                                 port=args.port)
        else:
            service_instance = SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=args.port)

        atexit.register(Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Assigning destination datastores
        datastore_dest = args.datastore_dest

        # Target compute resource
        host_dest = args.target_esx_host

        relocate_vm(args.vm_name,
                    content=content,
                    host_dest=host_dest,
                    datastore_dest=datastore_dest)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0


# Start program 
Example #21
Source File: upgrade_vm.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
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 
Example #22
Source File: getvmsbycluster.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Iterate through all datacenters and list VM info.
    """
    args = GetArgs()
    outputjson = True if args.json else False

    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                   'user %s: ' % (args.host, args.user))

    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=password,
                           port=int(args.port))
    if not si:
        print("Could not connect to the specified host using specified "
              "username and password")
        return -1

    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    children = content.rootFolder.childEntity
    for child in children:  # Iterate though DataCenters
        dc = child
        data[dc.name] = {}  # Add data Centers to data dict
        clusters = dc.hostFolder.childEntity
        for cluster in clusters:  # Iterate through the clusters in the DC
            # Add Clusters to data dict
            data[dc.name][cluster.name] = {}
            hosts = cluster.host  # Variable to make pep8 compliance
            for host in hosts:  # Iterate through Hosts in the Cluster
                hostname = host.summary.config.name
                # Add VMs to data dict by config name
                data[dc.name][cluster.name][hostname] = {}
                vms = host.vm
                for vm in vms:  # Iterate through each VM on the host
                    vmname = vm.summary.config.name
                    data[dc.name][cluster.name][hostname][vmname] = {}
                    summary = vmsummary(vm.summary, vm.guest)
                    vm2dict(dc.name, cluster.name, hostname, vm, summary)

    if not args.silent:
        print(json.dumps(data, sort_keys=True, indent=4))

    if outputjson:
        data2json(data, args)

# Start program 
Example #23
Source File: clone_vm.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Let this thing fly
    """
    args = get_args()

    # connect this thing
    si = None
    if args.no_ssl:
        si = SmartConnectNoSSL(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    else:
        si = SmartConnect(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    # disconnect this thing
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    template = None

    template = get_obj(content, [vim.VirtualMachine], args.template)

    if template:
        clone_vm(
            content, template, args.vm_name, si,
            args.datacenter_name, args.vm_folder,
            args.datastore_name, args.cluster_name,
            args.resource_pool, args.power_on, args.datastorecluster_name)
        if args.opaque_network:
            vm = get_obj(content, [vim.VirtualMachine], args.vm_name)
            add_nic(si, vm, args.opaque_network)
    else:
        print("template not found")


# start this thing 
Example #24
Source File: scheduled_poweroff.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    args = get_args()
    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

    atexit.register(connect.Disconnect, si)

    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]

    spec = vim.scheduler.ScheduledTaskSpec()
    spec.name = 'PowerOff vm %s' % args.vmname
    spec.description = ''
    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) 
Example #25
Source File: update_esxi_advanced_settings.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
   Simple command-line program demonstrating how to update
   ESXi Advanced Settings
   """

    args = 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)

        content = service_instance.RetrieveContent()

        cluster = get_obj(content,
                          [vim.ClusterComputeResource], args.cluster_name)

        hosts = cluster.host
        for host in hosts:
            optionManager = host.configManager.advancedOption
            option = vim.option.OptionValue(key=args.key,
                                            value=long(args.value))
            print("Updating %s on ESXi host %s "
                  "with value of %s" % (args.key, host.name, args.value))
            optionManager.UpdateOptions(changedValue=[option])

    except vmodl.MethodFault as e:
        print("Caught vmodl fault : " + e.msg)
        return -1
    except Exception as e:
        print("Caught exception : " + str(e))
        return -1

    return 0

# Start program 
Example #26
Source File: fcd_delete_vdisk.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for deleting a snapshot of 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()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Confirming FCD deletion
        if not args.yes:
            response = cli.prompt_y_n_question("Are you sure you want to "
                                               "delete vdisk '" + args.vdisk +
                                               "'?",
                                               default='no')
            if not response:
                print("Exiting script. User chose not to delete HDD.")
                exit()

        # Delete FCD
        storage = content.vStorageObjectManager
        task = storage.DeleteVStorageObject_Task(vdisk.config.id, datastore)
        tasks.wait_for_tasks(service_instance, [task])

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0


# Start program 
Example #27
Source File: detach_disk_from_vm.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for detaching a disk from a virtual machine.
    """

    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 VM
        vm = None
        if args.uuid:
            search_index = content.searchIndex
            vm = search_index.FindByUuid(None, args.uuid, True)
        elif args.vm_name:
            vm = disk.get_obj(content, [vim.VirtualMachine], args.vm_name)

        # Detaching Disk from VM
        if vm:
            task = detach_disk_from_vm(vm, args.disknumber, args.language)
            tasks.wait_for_tasks(service_instance, [task])
        else:
            raise RuntimeError("VM not found.")

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0


# Start program 
Example #28
Source File: getallvms.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
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_vm_info(child)
            else:
                if pat.search(child.summary.config.name) is not None:
                    print_vm_info(child)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0


# Start program 
Example #29
Source File: get_vm_storage_policy.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """Main program.
    """

    args = get_args()
    serviceInstance = None
    try:
        if args.disable_ssl_verification:
            serviceInstance = SmartConnectNoSSL(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))
        else:
            serviceInstance = SmartConnect(host=args.host,
                                           user=args.user,
                                           pwd=args.password,
                                           port=int(args.port))
        atexit.register(Disconnect, serviceInstance)
    except IOError as e:
        print(e)
        pass
    if not serviceInstance:
        raise SystemExit("Unable to connect to host with supplied info.")

    pbm_content = PbmConnect(serviceInstance._stub,
                             args.disable_ssl_verification)
    pm = pbm_content.profileManager

    vm_list = SearchVMByName(serviceInstance, args.vm_name, args.strict)
    for vm in vm_list:
        print("Virtual machine name: {}{}{}".format(bcolors.OKGREEN,
                                                    vm.name,
                                                    bcolors.ENDC))
        pmObjectType = pbm.ServerObjectRef.ObjectType("virtualMachine")
        pmRef = pbm.ServerObjectRef(key=vm._moId,
                                    objectType=pmObjectType)
        profiles = GetStorageProfiles(pm, pmRef)
        if len(profiles) > 0:
            print("Home Storage Profile:")
            ShowStorageProfile(profiles)

        print("\r\nVirtual Disk Storage Profile:")
        for device in vm.config.hardware.device:
            deviceType = type(device).__name__
            if deviceType == "vim.vm.device.VirtualDisk":
                pmObjectType = pbm.ServerObjectRef.ObjectType("virtualDiskId")
                pmRef = pbm.ServerObjectRef(key="{}:{}".format(vm._moId,
                                                               device.key),
                                            objectType=pmObjectType)
                profiles = GetStorageProfiles(pm, pmRef)
                if len(profiles) > 0:
                    print(device.deviceInfo.label)
                    ShowStorageProfile(profiles)
                    print("")
        print("") 
Example #30
Source File: vsphere-monitor.py    From vsphere-monitor with Apache License 2.0 4 votes vote down vote up
def run(host,user,pwd,port,interval):
    try:
        si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port)
        atexit.register(Disconnect, si)
        content = si.RetrieveContent()
        vchtime = si.CurrentTime()

        perf_dict = {}
        perfList = content.perfManager.perfCounter
        for counter in perfList:
            counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
            perf_dict[counter_full] = counter.key

        for datacenter in content.rootFolder.childEntity:
            datacenter_name = datacenter.name.encode("utf8")
            datastores = datacenter.datastore
            for ds in datastores:
                if (ds.name in config.datastore_names) or (len(config.datastore_names) == 0):
                    DatastoreInformation(ds,datacenter_name)

            if hasattr(datacenter.hostFolder, 'childEntity'):
                hostFolder = datacenter.hostFolder
                computeResourceList = []
                computeResourceList = getComputeResource(hostFolder,computeResourceList)
                for computeResource in computeResourceList:
                    ComputeResourceInformation(computeResource,datacenter_name,content,perf_dict,vchtime,interval)
         
        if config.vm_enable == True:
            obj = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
            for vm in obj.view:
                if (vm.name in config.vm_names) or (len(config.vm_names) == 0):
                    tags = "vm=" + vm.name
                    if vm.runtime.powerState == "poweredOn":
                        VmInfo(vm, content, vchtime, interval, perf_dict, tags)
                        add_data("vm.power",1,"GAUGE",tags)
                    else:
                        add_data("vm.power",0,"GAUGE",tags)               

    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return False, error.msg
    return True, "ok"