Пример #1
0
def main(vm):
    inputs = {
        'vcenter_ip': '192.168.32.98',
        'vcenter_password': '******',
        'vcenter_user': '******',
        'vm_name': vm,
        #create, remove,info,snap info or list
        'operation': 'snap info',
        'snapshot_name': 'test',
        'ignore_ssl': True
    }
    si = None
    try:
        print "Trying to connect to VCENTER SERVER . . ."

        context = None
        if inputs['ignore_ssl']:
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            context.verify_mode = ssl.CERT_NONE

        #si = connect.Connect(args.host, int(args.port), args.user, args.password, service="hostd")
        si = connect.Connect(inputs['vcenter_ip'],
                             443,
                             inputs['vcenter_user'],
                             inputs['vcenter_password'],
                             sslContext=context)
    except IOError, e:
        pass
        atexit.register(Disconnect, si)
def main():

    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."
            si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'], version="vim.version.version8")
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER !"

        content = si.RetrieveContent()

        host = get_obj(content, [vim.HostSystem], inputs['host_name'])

        host_network_system = host.configManager.networkSystem

#         for pnic in host.config.network.pnic:
#             if pnic.device == inputs['nic_name']:
#                 pnic_key = pnic.key

        create_vswitch(host_network_system, inputs['switch_name'], inputs['num_ports'], inputs['nic_name'])

        create_port_group(host_network_system, inputs['port_group_name'], inputs['switch_name'])
Пример #3
0
    def _vmware_connect(self, vmware, ignore_ssl=True):
        """
        Connect to Vcenter and get connection
        """
        context = None
        if ignore_ssl and hasattr(ssl, "_create_unverified_context"):
            context = ssl._create_unverified_context()

        try:
            logger.info('[PID-{0}] Begin connecting to vmware {1}'.format(
                os.getpid(), vmware['host']))

            si = connect.Connect(vmware['host'],
                                 443,
                                 vmware['username'],
                                 vmware['password'],
                                 sslContext=context)

            logger.info('[PID-{0}] Connect to vmware {1} successfully.'.format(
                os.getpid(), vmware['host']))
            return si
        except Exception as e:
            if isinstance(e, vmodl.MethodFault):
                logger.error(
                    "[PID-{0}] Caught vmodl fault when connect to vmware: {1}".
                    format(os.getpid(), e.message))
            else:
                logger.error(
                    '[PID-{0}] Connection to vmware {1} failed: {2}'.format(
                        os.getpid(), vmware['host'], e.message))
            return None
Пример #4
0
def main(ip, password, user, vm_name, snap_name):
    string = ""
    inputs = {'vcenter_ip': ip,
          'vcenter_password': password,
          'vcenter_user': user,
          'vm_name' : vm_name, #'test_TSAM',
          #create, remove,info,snap info or list
          'operation' : 'create',
          'snapshot_name' : snap_name,   
          'ignore_ssl': True
          }
    si = None
    try:
        #print "Trying to connect to VCENTER SERVER . . ."
        
        context = None
        if inputs['ignore_ssl']:
          context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
          context.verify_mode = ssl.CERT_NONE
          
        #si = connect.Connect(args.host, int(args.port), args.user, args.password, service="hostd")
        si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'],
        sslContext=context)
    except IOError, e:
        pass
        atexit.register(Disconnect, si)
def main():

    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."

            context = None
            if inputs['ignore_ssl']:
                context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
                context.verify_mode = ssl.CERT_NONE

            #si = connect.Connect(args.host, int(args.port), args.user, args.password, service="hostd")
            si = connect.Connect(inputs['vcenter_ip'],
                                 443,
                                 inputs['vcenter_user'],
                                 inputs['vcenter_password'],
                                 sslContext=context)
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER !"

        content = si.RetrieveContent()

        operation = inputs['operation']

        vm_name = inputs['vm_name']
        snapshot_name = inputs['snapshot_name']

        vm = get_obj(content, [vim.VirtualMachine], vm_name)

        if operation == 'create':

            description = "Test snapshot"
            # Read about dumpMemory : http://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.VirtualMachine.html#createSnapshot
            dumpMemory = False
            quiesce = True

            invoke_and_track(
                vm.CreateSnapshot(snapshot_name, description, dumpMemory,
                                  quiesce))

        elif operation == 'remove':
            snapshots = vm.snapshot.rootSnapshotList

            for snapshot in snapshots:
                if snapshot_name == snapshot.name:
                    snap_obj = snapshot.snapshot
                    print "Removing snapshot ", snap_obj
                    invoke_and_track(snap_obj.RemoveSnapshot_Task(True))
                else:
                    print "Couldn't find any snapshots"

        if operation == 'list':
            print 'Display list of snapshots on virtual machine ' + vm.name
            snapshot_paths = get_snapshots(vm)
            for snapshot_path in snapshot_paths:
                print snapshot_path
Пример #6
0
 def test_unknown_fault(self):
     # see: http://python3porting.com/noconv.html
     si = connect.Connect(host='vcsa',
                          user='******',
                          pwd='my_password')
     content = si.RetrieveContent()
     lm = content.licenseManager
     # NOTE (hartsock): assertIsNotNone does not work in Python 2.6
     self.assertTrue(lm is not None)
     lam = lm.licenseAssignmentManager
     # NOTE (hartsock): assertIsNotNone does not work in Python 2.6
     self.assertTrue(lam is not None)
     # cassette is altered to raise a fault here:
     fault = None
     try:
         lam.QueryAssignedLicenses()
     except Exception as ex:
         # NOTE (hartsock): not using 'assertRaises' so we can inspect obj
         fault = ex
     # NOTE (hartsock): assertIsNotNone does not work in Python 2.6
     self.assertTrue(fault is not None)  # only until 2.6 support is dropped
     # Observe that the malformed XML was reported up the stack to the
     # user so that field reports will contain SOAP message information.
     self.assertTrue('<detail> '
                     '<UnknownLicenseProblemFaultFault '
                     'xsi:type="UnknownLicenseProblemFault"> '
                     '<reason>unknownReason</reason>'
                     '</UnknownLicenseProblemFaultFault> '
                     '</detail>' in str(fault))
Пример #7
0
 def connect(self, vcenter, username, password):
     vcenter_ses = connect.Connect(vcenter,
                                   443,
                                   username,
                                   password,
                                   sslContext=self.context)
     return vcenter_ses
Пример #8
0
def get_all_vms(host, usr, pwd):
    vms_list = []
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        for vm in vm_view.view:
            summary = vm.summary
            dt = summary.config.vmPathName.split(" ")[0]
            dt = dt[1:(len(dt) - 1)]
            vm_config = {
                "name": summary.config.name,
                "datastore": dt,
                "status": summary.runtime.powerState[7:],
                "ip": [],
                "uuid": summary.config.instanceUuid
            }
            if len(vm.guest.net) > 0:
                for nic in vm.guest.net:
                    if len(nic.ipAddress) == 0:
                        continue
                    elif len(nic.ipAddress[0]) > 15:
                        pass
                    else:
                        vm_config["ip"].append(nic.ipAddress[0])
            vms_list.append(vm_config)
        connect.Disconnect(si)
    except Exception, e:
        return "Get vms failed!"
Пример #9
0
def get_vm_info(host, usr, pwd, vm_name):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        uuid = ""
        for vm in vm_view.view:
            if vm.summary.config.name == vm_name:
                uuid = vm.summary.config.instanceUuid
                break
        if uuid == "":
            connect.Disconnect(si)
            return "Can't find VM(%s)!" % vm_name

        vm = si.content.searchIndex.FindByUuid(None, uuid, True, True)
        vm_details = {
            "cpu": vm.config.hardware.numCPU,
            "memory": vm.config.hardware.memoryMB,
            "drive": [],
            "network": []
        }
        for device in vm.config.hardware.device:
            if device.backing is not None:
                if device.deviceInfo.label.find("disk") > 0:
                    vm_details["drive"].append(device.deviceInfo.label)
                elif device.deviceInfo.label.find("adapter") > 0:
                    vm_details["network"].append(device.deviceInfo.label)
                else:
                    pass
        connect.Disconnect(si)
    except Exception, e:
        return "Get VM(%s) details failed!" % vm_name
Пример #10
0
def main():
   """ This is the main program, obviously """

   # Command parser
   cmdOptionsList = [
      make_option("--host", default="localhost",
                   dest="host", help="Host name"),
      make_option("--port", type="int", default=443,
                   dest="port", help="Port number"),
      make_option("--user", default="root", dest="user", help="User name"),
      make_option("--pwd", "--password",
                  default="ca$hc0w", dest="pwd", help="Password"),
      make_option("-?", action="help")
   ]
   cmdParser = OptionParser(option_list=cmdOptionsList)

   # Get command line options
   (options, args) = cmdParser.parse_args()
   # cmdParser should have a cmdParser.destroy() method, but it is missing
   del cmdParser

   # Get stub generator
   stubGenerator = lambda ns: \
                     connect.Connect(host=options.host, port=options.port,
                                     namespace=ns,
                                     user=options.user, pwd=options.pwd)._stub

   # Run test
   TestDriver.RunTest(stubGenerator)
Пример #11
0
def esxi_destory_vm(host, usr, pwd, vm_name):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        vm_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.VirtualMachine], True)
        uuid = ""
        for vm in vm_view.view:
            if vm.summary.config.name == vm_name:
                uuid = vm.summary.config.instanceUuid
                break
        if uuid == "":
            connect.Disconnect(si)
            return "Can't find VM(%s)!" % vm_name

        vm = si.content.searchIndex.FindByUuid(None, uuid, True, True)
        if vm.runtime.powerState == "poweredOn":
            task = vm.PowerOffVM_Task()
            tasks.wait_for_tasks(si, [task])

        task = vm.Destroy_Task()
        tasks.wait_for_tasks(si, [task])
        connect.Disconnect(si)
    except Exception, e:
        print e
        return "Destory VM(%s) failed!" % vm_name
Пример #12
0
 def revert(vmname):
     context = None
     if inputs['ignore_ssl'] and hasattr(ssl, "_create_unverified_context"):
         context = ssl._create_unverified_context()
     si = connect.Connect(inputs['vcenter_ip'],
                          443,
                          inputs['vcenter_user'],
                          inputs['vcenter_password'],
                          sslContext=context)
     atexit.register(Disconnect, si)
     content = si.RetrieveContent()
     vm_name = vmname
     vm = get_obj(content, [vim.VirtualMachine], vm_name)
     if not vm:
         raise Exception("Virtual Machine %s doesn't exists" % vm_name)
     snapshot_name = inputs['snapshot_name']
     snap_obj = get_snapshots_by_name_recursively(
         vm.snapshot.rootSnapshotList, snapshot_name)
     if len(snap_obj) == 1:
         snap_obj = snap_obj[0].snapshot
         WaitForTask(snap_obj.RevertToSnapshot_Task())
         WaitForTask(vm.PowerOn())
     else:
         raise Exception(("No snapshots found with name: %s on VM: %s" %
                          (snapshot_name, vm.name)))
     return
Пример #13
0
def main():
    args = get_args()
    inputs = {
        'vcenter_ip': args.host,
        'vcenter_password': args.password,
        'vcenter_user': args.user,
        'vm_name': 'testvm',
        # Start, Stop(force), Suspend(force)
        'operation': args.action,
        'force': True,
    }
    try:
        si = None
        try:
            print "Trying to connect to  SERVER . . ."
            si = connect.Connect(inputs['vcenter_ip'], 443,
                                 inputs['vcenter_user'],
                                 inputs['vcenter_password'])
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to  SERVER !"

        content = si.RetrieveContent()

        #if inputs['operation'] == 'stop' or inputs['operation'] == 'suspend':
        force = inputs['force']

        vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name'])

        #current_state = vm.runtime.powerState

        if inputs['operation'] == 'start':
            invoke_and_track(vm.PowerOn, None)

        elif inputs['operation'] == 'stop':
            if not force:
                invoke_and_track(vm.ShutdownGuest)
            else:
                invoke_and_track(vm.PowerOff)

        elif inputs['operation'] == 'suspend':
            if not force:
                invoke_and_track(vm.StandbyGuest)
            else:
                invoke_and_track(vm.Suspend)

        elif inputs['operation'] == 'destroy':
            print vm.runtime.powerState
            if format(vm.runtime.powerState) == "poweredOn":
                if not force:
                    invoke_and_track(vm.ShutdownGuest)
                else:
                    invoke_and_track(vm.PowerOff)
            print vm.runtime.powerState
            invoke_and_track(vm.Destroy_Task())
Пример #14
0
def main():

    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."
            si = connect.Connect(inputs['vcenter_ip'],
                                 443,
                                 inputs['vcenter_user'],
                                 inputs['vcenter_password'],
                                 service="hostd")
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER !"

        content = si.RetrieveContent()

        vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name'])
        vm_dest = get_obj(content, [vim.VirtualMachine], inputs['vm_dest'])

        destination_host = get_obj(content, [vim.HostSystem],
                                   inputs['destination_host'])

        resource_pool = vm_dest.resourcePool
        print resource_pool

        # if vm.runtime.powerState != 'poweredOn':
        #     print "WARNING:: Migration is only for Powered On VMs"
        #     sys.exit()

        migrate_priority = vim.VirtualMachine.MovePriority.defaultPriority

        msg = "Migrating %s to destination host %s" % (
            inputs['vm_name'], inputs['destination_host'])
        print msg

        #Live Migration :: Change host only
        task = vm.Migrate(pool=resource_pool,
                          host=destination_host,
                          priority=migrate_priority)
        #         Live Migration :: Change both host and datastore
        #         vm_relocate_spec = vim.vm.RelocateSpec()
        #         vm_relocate_spec.host = destination_host
        #         vm_relocate_spec.pool = resource_pool
        #         datastores = destination_host.datastore
        #         Assuming Migrating between local datastores
        #         for datastore in datastores:
        #             if datastore.summary.type == 'VMFS':
        #                 vm_relocate_spec.datastore = datastor
        #                 break
        #
        #         task = vm.Relocate(spec=vm_relocate_spec)

        # Wait for Migrate to complete
        wait_for_task(task, si)
Пример #15
0
def connectVC(vcenter,user,password):
 try:
  print "Trying to connect to VCENTER SERVER . . ."
  context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  context.verify_mode = ssl.CERT_NONE
  si = connect.Connect(vcenter,443,user,password,sslContext=context)
 except IOError, e:
  pass
  atexit.register(Disconnect, si)
Пример #16
0
	def reconnect(self):
		try:
			if self.vs != None:
				connect.Disconnect(self.vs)
			self.vs = connect.Connect(self.host, self.port, self.user, self.password)
			return True
		except Exception as e:
			print str(e)
			return False
def main():

    args = get_args()
    inputs['vcenter_ip'] = args.host
    inputs['vcenter_user'] = args.user
    inputs['vcenter_password'] = args.password
    inputs['vm_name'] = args.name
    inputs['datastor_iso_path'] = args.iso

    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."
            si = connect.Connect(inputs['vcenter_ip'],
                                 443,
                                 inputs['vcenter_user'],
                                 inputs['vcenter_password'],
                                 version="vim.version.version8")
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER !"

        content = si.RetrieveContent()

        vm_name = inputs['vm_name']
        vm = get_obj(content, [vim.VirtualMachine], vm_name)

        print "Attaching iso to CD drive of ", vm_name
        cdspec = None
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualCdrom):
                cdspec = vim.vm.device.VirtualDeviceSpec()
                cdspec.device = device
                cdspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit

                cdspec.device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(
                )
                for datastore in vm.datastore:
                    cdspec.device.backing.datastore = datastore
                    break
                cdspec.device.backing.fileName = inputs['datastor_iso_path']
                cdspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
                )
                cdspec.device.connectable.startConnected = True
                cdspec.device.connectable.allowGuestControl = True

        vmconf = vim.vm.ConfigSpec()
        vmconf.deviceChange = [cdspec]

        task = vm.ReconfigVM_Task(vmconf)

        wait_for_task(task, si)

        print "Successfully attached iso to the CD drive of VM ", vm_name
Пример #18
0
def _connect( paramaters ):
  # work arround invalid SSL
  import ssl
  _create_unverified_https_context = ssl._create_unverified_context
  ssl._create_default_https_context = _create_unverified_https_context
  # TODO: flag fortrusting SSL of connection, also there is a paramater to Connect for verified SSL

  logging.debug( 'vcenter: connecting to "{0}" with user "{1}"'.format( paramaters[ 'host' ], paramaters[ 'username' ] ) )

  return connect.Connect( host=paramaters[ 'host' ], user=paramaters[ 'username' ], pwd=paramaters[ 'password' ] )
def main():

    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."
            si = connect.Connect(inputs['vcenter_ip'],
                                 443,
                                 inputs['vcenter_user'],
                                 inputs['vcenter_password'],
                                 version="vim.version.version8")
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER !"

        content = si.RetrieveContent()

        vm_name = inputs['vm_name']
        vm = get_obj(content, [vim.VirtualMachine], vm_name)

        print "Attaching iso to CD drive of ", vm_name
        cdspec = None
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualCdrom):
                cdspec = vim.vm.device.VirtualDeviceSpec()
                cdspec.device = device
                cdspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit

                cdspec.device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(
                )
                for datastore in vm.datastore:
                    cdspec.device.backing.datastore = datastore
                    break
                cdspec.device.backing.fileName = inputs['datastor_iso_path']
                cdspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
                )
                cdspec.device.connectable.startConnected = True
                cdspec.device.connectable.allowGuestControl = True

        vmconf = vim.vm.ConfigSpec()
        vmconf.deviceChange = [cdspec]
        print "Giving first priority for CDrom Device in boot order"
        vmconf.bootOptions = vim.vm.BootOptions(
            bootOrder=[vim.vm.BootOptions.BootableCdromDevice()])

        task = vm.ReconfigVM_Task(vmconf)

        wait_for_task(task, si)

        print "Successfully changed boot order priority and attached iso to the CD drive of VM ", vm_name

        print "Power On the VM to boot from iso"
        vm.PowerOnVM_Task()
Пример #20
0
 def test_basic_connection(self):
     # see: http://python3porting.com/noconv.html
     si = connect.Connect(host='vcsa', user='******', pwd='my_password')
     cookie = si._stub.cookie
     session_id = si.content.sessionManager.currentSession.key
     # NOTE (hartsock): The cookie value should never change during
     # a connected session. That should be verifiable in these tests.
     self.assertEqual(cookie, si._stub.cookie)
     # NOTE (hartsock): assertIsNotNone does not work in Python 2.6
     self.assertTrue(session_id is not None)
     self.assertEqual('52b5395a-85c2-9902-7835-13a9b77e1fec', session_id)
Пример #21
0
def esxi_get_network(host, usr, pwd):
    """ Get the Network information of 1 ESXi. """
    network_list = []
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        views = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.Network], True)
        for view in views.view:
            network_list.append(view.name)
        connect.Disconnect(si)
    except Exception, e:
        return "Get Network failed!"
Пример #22
0
def main():

    options, remainingOptions = ParseArgs(sys.argv[1:])

    # Connect to hosts.
    si = connect.Connect(host=options.host, user=options.user, pwd=options.pwd)

    atexit.register(Disconnect, si)

    if options.verbose:
        logger.setLevel(logging.DEBUG)

    logger.info("Starting test run")
    vm1 = None
    status = "FAIL"
    try:
        logger.info("Retrieving vm: %s", options.vmname)
        vm1 = vm.CreateOrReturnExisting(options.vmname)
        config = vm1.GetConfig()
        cspec = Vim.Vm.ConfigSpec()
        files = config.files
        logger.info("Changing %s 's snapshotDir to %s", options.vmname,
                    options.dspath)
        try:
            m = re.match('\[([^\]]+)\] .*', options.dspath)
        except:
            logger.error('path "%s" is not valid datastore path',
                         options.dspath)
            raise Exception, "dspath is not valid"
        files.snapshotDirectory = options.dspath
        dsListOld = [ds for ds in vm1.datastore if ds.name == m.groups()[0]]
        if not dsListOld:
            cspec.SetFiles(files)
            vm.Reconfigure(vm1, cspec)
            dsListNew = [
                ds for ds in vm1.datastore if ds.name == m.groups()[0]
            ]
            if dsListNew:
                logger.info("%s has been added to vm.datastore property",
                            options.dspath)
                status = "PASS"
            else:
                logger.info("%s has not been added to vm.datastore property",
                            options.dspath)
        else:
            logger.info("%s is already present in the vm.datastore property",
                        options.dspath)

    except Exception as e:
        logger.error("Caught exception: " + str(e))
        status = "FAIL"

    logger.info("Test run complete: " + status)
Пример #23
0
def esxi_get_datastores(host, usr, pwd):
    """ Get all datastore information of 1 ESXi. """
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)

        datacenter_obj = si.content.rootFolder.childEntity[0]
        datastore_list = datacenter_obj.datastoreFolder.childEntity
        dt_list = []
        for dt in datastore_list:
            dt_list.append(dt.name)
        connect.Disconnect(si)
    except Exception, e:
        return "Get Datastore Failed!"
Пример #24
0
def esxi_list_hardware(host, usr, pwd):
    try:
        si = connect.Connect(host=host, user=usr, pwd=pwd)
        host_view = si.content.viewManager.CreateContainerView(
            si.content.rootFolder, [vim.HostSystem], True)
        info = {
            "cores": host_view.view[0].hardware.cpuInfo.numCpuCores,
            "freq": host_view.view[0].hardware.cpuInfo.hz,
            "threads": host_view.view[0].hardware.cpuInfo.numCpuThreads,
            "memory": host_view.view[0].hardware.memorySize
        }
        connect.Disconnect(si)
    except Exception, e:
        return "Get ESXi Hardware Info Failed!"
Пример #25
0
def main():
    fields = {
        "vcenter_host": {
            "required": True,
            "type": "str"
        },
        "vcenter_user": {
            "required": True,
            "type": "str"
        },
        "vcenter_pass": {
            "required": True,
            "type": "str"
        },
        "dvs_name": {
            "required": True,
            "type": "str"
        },
        "pg_vlanid": {
            "required": True,
            "type": "int"
        },
    }

    try:
        module = AnsibleModule(argument_spec=fields)
        si = None
        data = module.params
        try:
            si = connect.Connect(data['vcenter_host'],
                                 443,
                                 data['vcenter_user'],
                                 data['vcenter_pass'],
                                 version="vim.version.version8",
                                 sslContext=s)
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        content = si.RetrieveContent()

        dvs = find_dvs_by_name(content, data['dvs_name'])
        pg = find_vdspg_by_vlanid(dvs, data['pg_vlanid'])

        response = {
            "name": pg.name,
            "vlan": pg.config.defaultPortConfig.vlan.vlanId
        }
        module.exit_json(changed=False, meta=response)
 def __connect_to_vcenter(self):
     """
     Connect to Vcenter Server with specified credentials
     @return: Service Instance
     """
     self.logger.info("Trying to connect to Vcenter Server %s" %
                      self.settings['vcenter_ip'])
     si = None
     try:
         si = connect.Connect(self.settings['vcenter_ip'],
                              443,
                              self.settings['vcenter_username'],
                              self.settings['vcenter_password'],
                              service="hostd")
     except IOError, e:
         pass
Пример #27
0
def process_affected_vms_with_signatures(sig_list):
    for sig in sig_list:
        print ("Checking for Effected VMs for Signature: " + str(sig))
        # Retrieved affected VMs and process
        base_url = "https://" + nsx_ip + "/api/v1/intrusion-services/affected-vms"
        mydata = '{ "filters": [ { "field_names": "signature_detail.signature_id", "value": "'+ str(sig) +'" } ] }'
        json_object = json.loads(mydata)
        json_formatted_str = json.dumps(json_object, indent=2)
        response = post(base_url, mydata)
        nsx_content = response.json()

        si = None
        context = context = ssl._create_unverified_context()
        si = connect.Connect(vc_ip, 443, vc_user, vc_pass, sslContext=context)
        atexit.register(Disconnect, si)

        content = si.RetrieveContent()

        for vm_name in nsx_content['results']:
            vm = get_obj (content, [vim.VirtualMachine], vm_name)

            if not vm:
                print ("Virtual Machine %s doesn't exists" % vm_name)
                sys.exit()

            # Add tag to the VM
            if (vm_name in vm_list):
                if (tag_workload):
                    print ("Adding NSX Tag to VM: %s ..." % vm_name)
                    base_url = "https://" + nsx_ip + "/api/v1/fabric/virtual-machines?action=add_tags"
                    mydata = '{ "external_id": "' + vm_dict[vm_name] + '", \
                                 "tags": [ \
                                   { "tag": "' + nsx_tag + '", "scope": "' + nsx_scope + '" } \
                                 ] } '
                    json_object = json.loads(mydata)
                    json_formatted_str = json.dumps(json_object, indent=2)
                    post (base_url, mydata)

                if (snapshot_workload):
                    print ("Taking a snapshot of VM: %s ..." % vm_name)
                    WaitForTask(vm.CreateSnapshot( "vm_name" + "_IDS_snapshot", "Snapshot by NSX IDS", False, False))

                if (shutdown_workload):
                    if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
                        print ("Powering off VM: %s ..." % vm_name)
                        WaitForTask(vm.PowerOff())
    return True
Пример #28
0
def main():
    parser = OptionParser()
    parser.add_option('-v',
                      '--vc',
                      dest='vc',
                      default='localhost',
                      help='VC to connect to')
    parser.add_option('-u',
                      '--user',
                      dest='user',
                      default='root',
                      help='User name')
    parser.add_option('-p',
                      '--password',
                      dest='password',
                      default='vmware',
                      help='Password')
    parser.add_option('-e', '--esx', dest='host', help='Host name')
    parser.add_option('-m', '--vm', dest='vm', help='VM name')
    parser.add_option('-i',
                      '--iteration',
                      dest='iteration',
                      default='1000',
                      help='Number of iterations')
    parser.add_option('-b',
                      '--bench',
                      dest='bench',
                      help='comma-separated benchmark names')

    (options, args) = parser.parse_args()
    connect.Connect(host=options.vc, user=options.user,\
                    pwd=options.password, version='vpx.version.version9')
    si = connect.GetSi()
    if si is None:
        return

    vpxSi = Vpx.ServiceInstance("VpxdInternalServiceInstance", si._GetStub())
    benchMgr = vpxSi.debugManager.benchmarkManager
    host = FindHostByName(si, options.host)  # could be None
    vm = FindVmByName(si, options.vm)  # could be None

    nanobench = NanoBench(benchMgr, options.iteration, host, vm)
    try:
        nanobench.setRunList(options.bench)
        nanobench.run()
    finally:
        si.content.sessionManager.Logout()
def main():
    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."
            #si = connect.Connect(args.host, int(args.port), args.user, args.password, service="hostd")
            si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'])
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER %s " % inputs['vcenter_ip']

        content = si.RetrieveContent()

        vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name'])

        cluster = get_obj(content, [vim.ClusterComputeResource], inputs['cluster'])
        settings = []
        cluster_spec = vim.cluster.ConfigSpec()
        config_spec = vim.cluster.DasVmConfigSpec()
        config_spec.operation = vim.option.ArrayUpdateSpec.Operation.edit
        config_info = vim.cluster.DasVmConfigInfo()
        config_info.key = vm
        config_info.restartPriority = vim.cluster.DasVmConfigInfo.Priority.disabled

        vm_settings = vim.cluster.DasVmSettings()
        #vm_settings.isolationResponse = vim.cluster.DasVmSettings.IsolationResponse.shutdown
        vm_settings.restartPriority = vim.cluster.DasVmSettings.RestartPriority.disabled
        monitor = vim.cluster.VmToolsMonitoringSettings()
        monitor.vmMonitoring = vim.cluster.DasConfigInfo.VmMonitoringState.vmMonitoringDisabled
        monitor.clusterSettings = False
        vm_settings.vmToolsMonitoringSettings = monitor

        config_info.dasSettings = vm_settings

        config_spec.info = config_info

        settings.append(config_spec)

        cluster_spec.dasVmConfigSpec = settings

        print "Disabling HA for VM ", vm.name
        task = cluster.ReconfigureCluster_Task(cluster_spec, True)
        wait_for_task(task, si)
        print "Successfully reconfigured HA priority"
Пример #30
0
 def retrieve_content(self):
     """
     Establish SSL session to vSphere and retrieve the content
     """
     context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
     context.verify_mode = ssl.CERT_NONE
     si = None
     try:
         # print "Trying to connect to VCENTER SERVER . . ."
         si = connect.Connect(self.vsphere_ip,
                              443,
                              self.login,
                              self.pswd,
                              sslContext=context)
         atexit.register(Disconnect, si)
     except IOError, e:
         pass