예제 #1
0
def _connect_server(bot):
    try:
        server = VIServer()
        server.connect(bot.config.pysphere.server, bot.config.pysphere.login, bot.config.pysphere.password)        
    except Exception, e:
        bot.say("No connection to the server")
        return False
예제 #2
0
파일: vm_include.py 프로젝트: prwitt/python
def connectToHost(host,host_user,host_pw):
    #create server object
    s=VIServer()
    #connect to the host
    try:
        s.connect(host,host_user,host_pw)
        return s
예제 #3
0
def main(argv=None):

    if argv is None:
    argv=sys.argv

    server = VIServer()
    try:
        server.connect(sys.argv[1], sys.argv[2], sys.argv[3])

    hosts = server.get_hosts()
        for h_mor, h_name in hosts.items():
            props = VIProperty(server, h_mor)
        try:
            f = open("/tmp/esxi_hosts_" + sys.argv[1] + ".txt", "w")
            try:
            f.write("memorySize=" + str(props.hardware.memorySize) + "\n")
            f.write("overallCpuUsage=" + str(props.summary.quickStats.overallCpuUsage) + "\n")
                    f.write("overallMemoryUsage=" + str(props.summary.quickStats.overallMemoryUsage) + "\n")
            f.write("uptime=" + str(props.summary.quickStats.uptime) + "\n")
                # $CPUTotalMhz = $_.Summary.hardware.CPUMhz * $_.Summary.Hardware.NumCpuCores
                # $row."CpuUsage%" = [math]::round( ($row.CpuUsageMhz / $CPUTotalMhz), 2) * 100
                f.write("cpuMhz=" + str(props.summary.hardware.cpuMhz) + "\n")
                f.write("numCpuCores=" + str(props.summary.hardware.numCpuCores) + "\n")
            finally:
                f.close()
        except IOError:
            print "0"
            sys.exit(0)	
예제 #4
0
파일: esxi.py 프로젝트: corrupt952/pyxenter
def main():
    u"""Main method

    Create session.
    Excute subcommand.
    """
    # Import
    import socket
    import getpass
    import sys
    from pysphere import VIApiException, VIServer
    import argument

    # Get argument
    args = argument.args()
    s = VIServer()

    # Set information
    host = args.host if args.host else raw_input('Host> ')
    user = args.user if args.user else raw_input('User> ')
    passwd = args.passwd if args.passwd else getpass.getpass('Password> ')
    try:
        print 'Connecting...'
        s.connect(host, user, passwd)

        # Execute function
        args.func(args, s)
    except socket.error:
        print >> sys.stderr, "Cannot connected."
    except VIApiException:
        print >> sys.stderr, "Incorrect user name or password."
    except Exception, e:
        print >> sys.stderr, e.message
예제 #5
0
def viConnect(vCenter,username,password,vmname):
	server = VIServer()
	server.connect(vCenter,username,password)
	#print "vCenter: {} User: {} Pass: {}".format(vCenter,username,password)
	#return server
	#print viConnect("192.168.219.129","root","vmware")
	return getVm(server,vmname)
예제 #6
0
def get_connection(host_ip, username, password):
    server = VIServer()
    if host_ip is not None and username is not None and password is not None:
        server.connect(host_ip, username, password)
    else:
        return None
    return server
예제 #7
0
def host_connect(host):
    """ Connect to a host. """
    server = VIServer()
    server.connect(host, CREDS.get('Host', 'user'),
                   CREDS.get('Host', 'pass'))

    return server
def main():
    vm = None

    module = AnsibleModule(
        argument_spec=dict(
            vcenter_hostname=dict(required=True, type='str'),
            vcenter_username=dict(required=True, type='str'),
            vcenter_password=dict(required=True, type='str'),
            datacenter_name=dict(required=True, type='str'),
            folder_structure=dict(required=True, type='list'),
            guest_list=dict(required=True, type='list'),
        ),
        supports_check_mode=False,
    )

    if not HAS_PYSPHERE:
        module.fail_json(msg='pysphere module required')

    vcenter_hostname = module.params['vcenter_hostname']
    vcenter_username = module.params['vcenter_username']
    vcenter_password = module.params['vcenter_password']
    guest_list = module.params['guest_list']
    folder_structure = module.params['folder_structure']
    base_datacenter = module.params['datacenter_name']

    # CONNECT TO THE SERVER
    viserver = VIServer()
    try:
        viserver.connect(vcenter_hostname, vcenter_username, vcenter_password)
    except VIApiException, err:
        module.fail_json(msg="Cannot connect to %s: %s" %
                         (vcenter_hostname, err))
예제 #9
0
def connect_VI(vcenter_hostname, user, password):
    # Create the connection to vCenter Server
    server = VIServer()
    try:
        server.connect(vcenter_hostname, user, password)
    except VIApiException, err:
        module.fail_json(msg="Cannot connect to %s: %s" % (vcenter_hostname, err))
예제 #10
0
def esx_connect(host, user, password):
    esx = VIServer()
    try:
        esx.connect(host, user, password)
    except VIApiException, e:
        print("There was an error while connecting to esx: %s" % e)
        return 1
예제 #11
0
def vcenter_connect():
    """ Connect to the vcenter. """
    server = VIServer()
    server.connect(CREDS.get('Vcenter', 'server'),
                   CREDS.get('Vcenter', 'user'),
                   CREDS.get('Vcenter', 'pass'))

    return server
예제 #12
0
 def __init__(self, vcip, vcuser, vcpassword, dc, clu):
     self.vcip = vcip
     self.translation = {'POWERED OFF':'down', 'POWERED ON':'up'}
     s = VIServer()
     s.connect(vcip, vcuser, vcpassword)
     self.s = s
     self.clu = clu
     self.dc = dc
예제 #13
0
class VSphereConnection(ConnectionUserAndKey):
    def __init__(self, user_id, key, secure=True,
                 host=None, port=None, url=None, timeout=None, **kwargs):
        if host and url:
            raise ValueError('host and url arguments are mutually exclusive')

        if host:
            host_or_url = host
        elif url:
            host_or_url = url
        else:
            raise ValueError('Either "host" or "url" argument must be '
                             'provided')

        self.host_or_url = host_or_url
        self.client = None
        super(VSphereConnection, self).__init__(user_id=user_id,
                                                key=key, secure=secure,
                                                host=host, port=port,
                                                url=url, timeout=timeout,
                                                **kwargs)

    def connect(self):
        self.client = VIServer()

        trace_file = os.environ.get('LIBCLOUD_DEBUG', None)

        try:
            self.client.connect(host=self.host_or_url, user=self.user_id,
                                password=self.key,
                                sock_timeout=DEFAULT_CONNECTION_TIMEOUT,
                                trace_file=trace_file)
        except Exception:
            e = sys.exc_info()[1]
            message = e.message
            if hasattr(e, 'strerror'):
                message = e.strerror
            fault = getattr(e, 'fault', None)

            if fault == 'InvalidLoginFault':
                raise InvalidCredsError(message)
            raise LibcloudError(value=message, driver=self.driver)

        atexit.register(self.disconnect)

    def disconnect(self):
        if not self.client:
            return

        try:
            self.client.disconnect()
        except Exception:
            # Ignore all the disconnect errors
            pass

    def run_client_method(self, method_name, **method_kwargs):
        method = getattr(self.client, method_name, None)
        return method(**method_kwargs)
예제 #14
0
파일: vcenter_vx.py 프로젝트: 0z-cloud/vx
def main():
    module = AnsibleModule(
        argument_spec=dict(
            vcenter_vx=dict(required=True, type='str'),
            user=dict(required=True, type='str'),
            password=dict(required=True, type='str'),
            ansible_resource_pool=dict(required=False,
                                       default=None,
                                       type='str'),
            cluster=dict(required=False, default=None, type='str'),
            datacenter=dict(required=True, type='str'),
            datastore=dict(required=True, type='str'),
            esxi_hostname=dict(required=True, type='str'),
            power_on=dict(required=False, default='no', type='bool'),
            vm_name=dict(required=True, type='str'),
            vm_memory_mb=dict(required=False, default=1024),
            vm_num_cpus=dict(required=False, default=1),
            vm_scsi=dict(required=False, default="paravirtual", type='str'),
            vm_disk=dict(required=False, default=None, type='dict'),
            vm_nic=dict(required=False, default=None, type='dict'),
            vm_notes=dict(required=False, default=None, type='str'),
            vm_cdrom=dict(required=False, default=None, type='dict'),
            vm_extra_config=dict(required=False, default=None, type='dict'),
            guestosid=dict(required=True, type='str'),
        ),
        supports_check_mode=False,
        required_together=[['ansible_resource_pool', 'cluster']],
    )

    if not HAS_PYSPHERE:
        module.fail_json(msg="pysphere is not installed")

    vcenter_vx = module.params['vcenter_vx']
    user = module.params['user']
    password = module.params['password']
    ansible_resource_pool = module.params['ansible_resource_pool']
    cluster_name = module.params['cluster']
    datacenter = module.params['datacenter']
    datastore = module.params['datastore']
    esxi_hostname = module.params['esxi_hostname']
    power_on = module.params['power_on']
    vm_name = module.params['vm_name']
    vm_memory_mb = int(module.params['vm_memory_mb'])
    vm_num_cpus = int(module.params['vm_num_cpus'])
    vm_scsi = module.params['vm_scsi']
    vm_disk = module.params['vm_disk']
    vm_nic = module.params['vm_nic']
    vm_notes = module.params['vm_notes']
    vm_cdrom = module.params['vm_cdrom']
    vm_extra_config = module.params['vm_extra_config']
    guestosid = module.params['guestosid']

    # CONNECT TO THE SERVER
    s = VIServer()
    try:
        s.connect(vcenter_vx, user, password)
    except VIApiException, err:
        module.fail_json(msg="Cannot connect to %s: %s" % (vcenter_vx, err))
예제 #15
0
class VSphereConnection(ConnectionUserAndKey):
    def __init__(self, user_id, key, secure=True,
                 host=None, port=None, url=None, timeout=None, **kwargs):
        if host and url:
            raise ValueError('host and url arguments are mutually exclusive')

        if host:
            host_or_url = host
        elif url:
            host_or_url = url
        else:
            raise ValueError('Either "host" or "url" argument must be '
                             'provided')

        self.host_or_url = host_or_url
        self.client = None
        super(VSphereConnection, self).__init__(user_id=user_id,
                                                key=key, secure=secure,
                                                host=host, port=port,
                                                url=url, timeout=timeout,
                                                **kwargs)

    def connect(self):
        self.client = VIServer()

        trace_file = os.environ.get('LIBCLOUD_DEBUG', None)

        try:
            self.client.connect(host=self.host_or_url, user=self.user_id,
                                password=self.key,
                                sock_timeout=DEFAULT_CONNECTION_TIMEOUT,
                                trace_file=trace_file)
        except Exception as e:
            message = e.message
            if hasattr(e, 'strerror'):
                message = getattr(e, 'strerror', e.message)

            fault = getattr(e, 'fault', None)

            if fault == 'InvalidLoginFault':
                raise InvalidCredsError(message)
            raise LibcloudError(value=message, driver=self.driver)

        atexit.register(self.disconnect)

    def disconnect(self):
        if not self.client:
            return

        try:
            self.client.disconnect()
        except Exception:
            # Ignore all the disconnect errors
            pass

    def run_client_method(self, method_name, **method_kwargs):
        method = getattr(self.client, method_name, None)
        return method(**method_kwargs)
예제 #16
0
 def serverVersion(self):
     self.server = VIServer()
     try:
         self.server.connect_no_auth(self.ip.get())
         self.serverFullname = self.server.get_server_fullname()
         self.server.disconnect()
         self.version_text.insert('end', self.serverFullname)
     except:
         print "Maybe the remote host is not a ESX/ESXi Server."
예제 #17
0
def connectToHost(host,host_user,host_pw):
    #create server object
    s=VIServer()
    #connect to the host
    try:
        s.connect(host,host_user,host_pw)
        return s
    except VIApiException:
        print ("Cannot connect to host: ")+host+(" error message: ")+err
예제 #18
0
def vcenter_connect(host, username, password):
    print 'Connecting to vcenter "%s"...' % (host)
    sys.stdout.flush()
    server = VIServer()
    server.connect(host.strip(), username.strip(), password.strip())
    sys.stdout.flush()
    print 'Vcenter connected'
    sys.stdout.flush()
    return server
예제 #19
0
def connectToHost(host, host_user, host_pw):
    #create server object
    s = VIServer()
    #connect to the host
    try:
        s.connect(host, host_user, host_pw)
        return s
    except VIApiException, err:
        print "Cannot connect to host: '%s', error message: %s" % (host, err)
예제 #20
0
파일: host.py 프로젝트: dvinazza/esxi-tools
    def conexion_viserver(self):
        self.logger.debug(self)
        esxi = VIServer()
        esxi.connect(self.creds['ip'], self.creds['user'],
                     self.creds['pw'], trace_file=self.config.logpysphere)

        self.logger.debug("Conectado a %s %s", esxi.get_server_type(),
                          esxi.get_api_version())
        return esxi
def connectToHost(host,host_user,host_pw):
    #create server object
    s=VIServer()
    #connect to the host
    try:
        s.connect(host,host_user,host_pw)
        return s
    except VIApiException, err:
        print "Cannot connect to host: '%s', error message: %s" %(host,err)    
예제 #22
0
def create_vmware_connection(vmware_settings):
    try:
        server = VIServer()
        server.connect(vmware_settings['host'], vmware_settings['user'],
                       vmware_settings['password'])
    except:
        print traceback.format_exc()
        raise
    return server
예제 #23
0
def vs_connect(host, user, password, unverify=True):
    if unverify:
        try:
            ssl._create_default_https_context = ssl._create_unverified_context
        except:
            pass
    con = VIServer()
    con.connect(host, user, password, '/var/log/pysphere.log')
    return con
예제 #24
0
def connectToHost(host, hostUsername, hostPassword):
    # create server object
    server = VIServer()

    try:
        server.connect(host, hostUsername, hostPassword)
        return server

    except VIApiException:
        raise
예제 #25
0
def GetHostConfig(host, user, password):
    from pysphere import VIServer
    server = VIServer()

    try:
        server.connect(host, user, password)
    except Exception, e:
        print "Error while connecting to %s:" % host
        print "%s" % e
        return None, False
예제 #26
0
파일: server.py 프로젝트: iii80/autovm
def get_center():
  
  serve = VIServer()
  
  try:
    serve.connect(get_arg('server[vcenter_ip]'), get_arg('server[vcenter_username]'), get_arg('server[vcenter_password]'), sock_timeout=60)
  except:
    return None
  
  return serve
예제 #27
0
def connect_vcenter(vcenter):
    #default_context = ssl._create_default_https_context
    server = VIServer()
    try:
        #ssl._create_default_https_context = ssl._create_unverified_context
        server.connect(vcenter.host_name, vcenter.user_name, vcenter.user_password)
        return server
    except AttributeError, e:
        print "ERROR: " + str(e)
        pass
예제 #28
0
def vm_stop(server, username, password, vmID):
        s_server=str(server)
        s_username=str(username)
        s_password=str(password)
        s_vm=str(vmID)
        server = VIServer()
        server.connect(s_server, s_username, s_password)
        vm1 = server.get_vm_by_name(s_vm)
        vm1.suspend()
        return
예제 #29
0
 def connect_server(self, ip, name, pwd):
     self.server_ip = ip
     self.user_name = name
     self.password = pwd
     self.server = VIServer()
     self.server.connect(self.server_ip, self.user_name, self.password)
     self.connect_flag = self.server.is_connected()
     if self.connect_flag:
         return True
     return False
예제 #30
0
파일: pysph.py 프로젝트: BwRy/sandy
def revert(datastore):
  #vmsphear username and password
  server = VIServer()
  server.connect("101.91.1.21", "root", "Vsphear_root_password")

  vm1 = server.get_vm_by_path(datastore)
  print "Cuurrent Status",vm1.get_status()
  print "Reverting VM:", datastore 
  vm1.revert_to_snapshot()
  print "Vm reverted"
예제 #31
0
def create_vmware_connection(vmware_settings):
    try:
        server = VIServer()
        server.connect(vmware_settings['host'],
                       vmware_settings['user'],
                       vmware_settings['password'])
    except:
        print traceback.format_exc()
        raise
    return server
예제 #32
0
 def StartConnect(self):
     vc_info = self.GetVcenterInfo()
     if vc_info != 1:
         Server = VIServer()
         try:
             Server.connect(**vc_info)
             self.server = Server
         except Exception, e:
             self.VCErrorReport(e.message)
         return Server if Server.is_connected() else 1
예제 #33
0
파일: pysph.py 프로젝트: tharani29/sandy
def revert(datastore):
    #vmsphear username and password
    server = VIServer()
    server.connect("101.91.1.21", "root", "Vsphear_root_password")

    vm1 = server.get_vm_by_path(datastore)
    print "Cuurrent Status", vm1.get_status()
    print "Reverting VM:", datastore
    vm1.revert_to_snapshot()
    print "Vm reverted"
예제 #34
0
    def vmaction(self, vm_name, vm_hz):

        server_obj = VIServer()
        try:
            server_obj.connect(self.host_ip, self.user, self.password)
        except Exception as e:
            print e

        # 通过名称获取vm的实例
        try:
            vm = server_obj.get_vm_by_name(vm_name)
        except Exception as e:
            return 0
        if vm.is_powered_off() == False:
            try:
                vm.reset()
                # print (type(int(vm_hz)))
                for i in range(1, int(vm_hz)):
                    print u'虚拟机%s 正在重置中。。。。,请等待注册\n' % (vm_name)
                    time.sleep(1)
                print u'重置完成'
                server_obj.disconnect()

                return 1
            except Exception as e:
                print e

        if vm.is_powered_off() == True:
            try:
                vm.power_on()
                print u'虚拟机%s 正在开机中。。。。' % (vm_name)
                server_obj.disconnect()

            except Exception as e:
                return 2
예제 #35
0
 def esxi_version(self):
     server_obj = VIServer()
     try:
         server_obj.connect(self.host_ip, self.user, self.password)
         servertype, version = server_obj.get_server_type(
         ), server_obj.get_api_version()
         server_obj.disconnect()
         return servertype, version
     except Exception as e:
         server_obj.disconnect()
         print e
예제 #36
0
def setupConnection(host, user, password):
        server = VIServer()

        try:
                server.connect(host, user, password)
                print "Host: " + host
                print "Version: " + server.get_server_type() + " " + server.get_api_version() + "\n"
                return server
        except Exception, err:
                print "Cannot connect to host: "+host+" error message: " +err.message
                sys.exit(2)
예제 #37
0
def setupConnection(host, user, password):
        server = VIServer()

        try:
                server.connect(host, user, password)
                print "[+] Host: " + host + " Version: " + server.get_server_type() + " " + server.get_api_version() + "\n"
                closeConnection(server)
                return True
        except Exception, err:
                print "[-] Cannot connect to host: "+host+" error message: " +err.message
                return None
예제 #38
0
 def __init__(self, host, user, password, exit_if_failed=True):
     try:
         self.server = VIServer()
         self.server.connect(host, user, password)
         self.host = host
         print('Logged into %s as %s' % (host, user))
     except VIApiException as e:
         print('Cannot login to vCenter (%s) as \'%s\' due to: %s' %
               (host, user, e))
         if exit_if_failed:
             sys.exit(1)
예제 #39
0
	def __init__(self, host, name, passwd):
		self.host = host 		# the host's ip
		self.name = name 		# the host's name
		self.passwd = passwd 	# the host's password
		self.esxiInst = None	# the esxi's handler 
		self.VMBuf = []  		# the all vms in the vcenter
		self.datastores = {}	# the host's datastores
		self.hosts = {}			# the host's host 
		self.esxiInst = VIServer() # get init the handles of the host
		self.esxiType = ""		# the type(esxi or vcneter) of the  host connected
		self.VGList = [] 		# the vms you get from the vm's buffer
		self.vm = None			# the handler of the vm you got
    def check(self):
        super(zstack_vcenter_image_file_checker, self).check()

        server = VIServer()
        server.connect(vcenter_ip, domain_name, password)
        all_vms = server._get_managed_objects(MORTypes.VirtualMachine)

        for mor, name in all_vms.iteritems():
            if name == sync_image_name:
                return self.judge(True)
        else:
            return self.judge(False)
예제 #41
0
 def __init__(self, host, user, passwd):
     self._connection = VIServer()
     logger.info("%s:connecting to '%s' as '%s'", __name__, host, user)
     try:
         ssl._create_default_https_context = ssl._create_unverified_context
         self._connection.connect(host, user, passwd)
         logger.debug("%s:host reports '%s V.%s'", __name__,
                      self._connection.get_server_type(), self._connection.get_api_version())
         self.host_config, n, n, n = self._get_host_config()
     except Exception, err:
         logger.critical("%s:%s", __name__, err)
         quit(2)
    def check(self):
        super(zstack_vcenter_image_file_checker, self).check()

        server = VIServer()
        server.connect(vcenter_ip, domain_name, password)
        all_vms = server._get_managed_objects(MORTypes.VirtualMachine)

        for mor, name in all_vms.iteritems():
            if name == sync_image_name:
                return self.judge(True)
        else:        
            return self.judge(False)
예제 #43
0
    def del_datas(self, vm_name, guster_user, guster_pwd, del_dir):
        server_obj = VIServer()
        try:
            server_obj.connect(self.host_ip, self.user, self.password)
        except Exception as e:
            print(e)
        # 通过名称获取vm的实例
        try:
            vm = server_obj.get_vm_by_name(vm_name)
        except Exception as e:
            # print(e)
            return 0
        print(vm.get_tools_status())
        if vm.get_tools_status() == 'RUNNING':  #判断tools状态
            print(f'{vm_name} tools is  RUNING--------------------')
            try:
                vm.login_in_guest(guster_user, guster_pwd)
                # vm.delete_directory(del_dir, recursive=True)  # 清空数据盘
                path_list = vm.list_files(del_dir)
                new_list = []
                #排除目录或文件
                not_list = [
                    '.', '..', '$RECYCLE.BIN', 'pagefile.sys', 'pvsvm', 'size',
                    'System Volume Information', 'vdiskdif.vhdx', 'desktop.ini'
                ]
                for list_ctent in path_list:
                    if list_ctent['path'] not in not_list:
                        new_list.append(list_ctent)
                if len(new_list) > 0:
                    for filter_list in new_list:
                        print(filter_list)
                        if filter_list['type'] == 'file':
                            try:
                                vm.delete_file(del_dir + filter_list['path'])
                            except Exception as e:
                                print(e)
                        if filter_list['type'] == 'directory':
                            try:
                                vm.delete_directory(del_dir +
                                                    filter_list['path'],
                                                    recursive=True)
                            except Exception as e:
                                print(e)

            except Exception as e:
                print(e)

            finally:

                print(f'{vm_name} 数据盘清空完毕!!!!!')
        else:
            print(f'{vm_name} tools is not RUNING--------------------')
예제 #44
0
    def retrieve(self, request, *args, **kwargs):
        host_ip_r = kwargs['host_ip']
        try:
            host_serializer = serializers.VMwareHostSerializer(self.queryset.get(host_ip=host_ip_r))
            instances_set = models.VMwareInstance.objects.filter(host_ip=host_serializer.data['host_ip'])
            instances_count = instances_set.count()
            mem_used = 0
            vcpus = 0
            ecu = 0
            for instance in instances_set:
                mem_used += int(instance.mem[0:len(instance.mem)-2])
                a = int(instance.cpu[0:instance.cpu.find("vcpu")])
                vcpus += a
                ecu += int(instance.cpu[instance.cpu.find("ecu")-1:instance.cpu.find("ecu")]) * a
            host_serializer.data['memory_used'] = str(mem_used/1024) + "GB"
            host_serializer.data['vcpus_used'] = vcpus
            host_serializer.data['ecus_used'] = ecu
            host_serializer.data['instances_count'] = instances_count

            server = VIServer()
            server.connect(host_serializer.data['host_ip'], 'root', 'P@ssw0rd')
            properties = ['capability.maxSupportedVMs',
                          'capability.maxSupportedVcpus',
                          'runtime.bootTime',
                          'runtime.powerState',
                          'summary.config.product.osType',
                          'summary.config.product.fullName',
                          'summary.config.product.licenseProductVersion',
                          'summary.config.product.licenseProductName',
                          'summary.config.product.instanceUuid',
                          'hardware.cpuPowerManagementInfo.hardwareSupport']
            results = server._retrieve_properties_traversal(property_names=properties, obj_type=MORTypes.HostSystem)
            for result in results:
                for p in result.PropSet:
                    if p.Name == 'hardware.cpuInfo.hz':
                        value = str(p.Val/(1024*1024*1024)) + " GHz"
                    elif p.Name == 'hardware.memorySize':
                        value = str(p.Val/(1024*1024)) + " MB"
                    elif p.Name == 'config.certificate':
                        value = str(p.Val)
                    elif p.Name == 'runtime.bootTime':
                        value = str(p.Val[0]) + "-" + str(p.Val[1]) + "-" + str(p.Val[2]) + " "
                        value = value + str(p.Val[3]) + ":" + str(p.Val[4])
                    else:
                        value = str(p.Val)
                    name = p.Name.split('.')[-1]
                    host_serializer.data[name] = value

            return Response(host_serializer.data)
        except VMwareHost.DoesNotExist:
            raise Http404
예제 #45
0
def vm_state(server, username, password, vmID):
        s_server=str(server)
        s_username=str(username)
        s_password=str(password)
        s_vm=str(vmID)
        server = VIServer()
        server.connect(s_server, s_username, s_password)
        vm1 = server.get_vm_by_name(s_vm)
        if vm1.is_suspended() or vm1.is_powered_off():
                return "OFF"
        elif vm1.is_powered_on():
                return "ON"
        else:
                return "UNK"
예제 #46
0
def vConnect(VIHost, VIUser, VIPassword):
    """Verbindungs Funktion zum Server
    Baut eine Verbindung mit VCS Server auf und speichert die Verbindungsinformationen in der VISerever variable des Typs "VIServer".
    """
    logger.info("Connecting to vSphere: " + VIHost)
    VirtualServerInstance = VIServer()
    VirtualServerInstance.connect(VIHost, VIUser, VIPassword)
    if VirtualServerInstance:
        logger.info("Connected to vSphere: " + VIHost)
        logger.info(VirtualServerInstance.get_api_type() + " API " + VirtualServerInstance.get_api_version())
        return VirtualServerInstance
    else:
        logger.error("Connection to the vSphere failed.")
        sys.exit(2)
예제 #47
0
class CheckVCenter():
    def __init__(self):
        self.server = VIServer()
        self.STAT_OK=0
        self.STAT_WARNING=1
        self.STAT_CRITICAL=2
        self.vc = sys.argv[1]
        self.user = sys.argv[2]
        self.password = sys.argv[3]


    @staticmethod
    def PrintDict(i,status):
        for k,v in i.items():
            print "VMFS %s lun:%s -----*----*---- usage:%d%%" %(status,k,v)

    def Check(self):
        self.server.connect(self.vc,self.user,self.password)
        Value = self.server.get_datastores()
        c = {}
        w = {}
        n = {}
        for k,v in Value.items():
            props = self.server._retrieve_properties_traversal(property_names=['name','summary.capacity',
                                                                               'summary.freeSpace'],
                                                          from_node=k,obj_type='Datastore')
            for p_set in props:
                for p1 in p_set.PropSet:
                    if p1.Name == "summary.capacity":
                        DatastoreCapacity = (p1.Val/1073741824)
                    elif p1.Name == "summary.freeSpace":
                        DatastoreFreespace = (p1.Val/1073741824)

            Percent = (((DatastoreCapacity - DatastoreFreespace) * 100)/DatastoreCapacity)
            if  Percent > 90 and 'ISO' not in v:
                c[v] = Percent
            elif Percent > 85  < 90 and 'ISO' not in v:
                w[v] = Percent
            elif Percent < 85 and 'ISO' not in v:
                n[v] = Percent
        if dict(c):
            CheckVCenter.PrintDict(c,'CRITICAL')
            sys.exit(self.STAT_CRITICAL)
        elif dict(w):
            CheckVCenter.PrintDict(w,'WARNING')
            sys.exit(self.STAT_WARNING)
        else:
            print("All Lun is OK")
            sys.exit(self.STAT_OK)
예제 #48
0
def add_port_group(name, vlan_id, vswitch, network_system, vCenterserver,
                   username, password):
    s = VIServer()
    s.connect(vCenterserver, username, password)
    request = VI.AddPortGroupRequestMsg()
    _this = request.new__this(network_system)
    _this.set_attribute_type(network_system.get_attribute_type())
    request.set_element__this(_this)
    portgrp = request.new_portgrp()
    portgrp.set_element_name(name)
    portgrp.set_element_vlanId(vlan_id)
    portgrp.set_element_vswitchName(vswitch)
    portgrp.set_element_policy(portgrp.new_policy())
    request.set_element_portgrp(portgrp)
    s._proxy.AddPortGroup(request)
예제 #49
0
    def esxi_version(self):

        m = Info_log(time.strftime('%Y-%m-%d', time.localtime(time.time())))
        log = m.log()
        server_obj = VIServer()
        try:
            server_obj.connect(self.host_ip, self.user, self.password)
            servertype, version = server_obj.get_server_type(
            ), server_obj.get_api_version()
            server_obj.disconnect()
            return servertype, version, self.flag
        except Exception as e:
            server_obj.disconnect()

            log.info(e)
예제 #50
0
 def connect_server(self, ip, name, pwd, ssl_no_verify=True):
     logger.debug(ip)
     logger.debug(name)
     logger.debug(pwd)
     self.server_ip = ip
     self.user_name = name
     self.password = pwd
     self.server = VIServer()
     if ssl_no_verify:
         self.set_ssl_no_verify()
     self.server.connect(self.server_ip, self.user_name, self.password)
     self.connect_flag = self.server.is_connected()
     if self.connect_flag:
         return True
     return False
예제 #51
0
class VcenterInterface:
    """
    Communication and representation of vCenter's API
    """
    def __init__(self, host, user, password, exit_if_failed=True):
        try:
            self.server = VIServer()
            self.server.connect(host, user, password)
            self.host = host
            print('Logged into %s as %s' % (host, user))
        except VIApiException as e:
            print('Cannot login to vCenter (%s) as \'%s\' due to: %s' %
                  (host, user, e))
            if exit_if_failed:
                sys.exit(1)
예제 #52
0
class Server:
        def __init__(self):
                self.server = VIServer()
                self.connect()

        def connect(self):
                try:
                        # monkey-patch SSL module (uncomment if unneeded)
                        #ssl._create_default_https_context = ssl._create_unverified_context
                        self.server.connect('vsphere-host', 'user', 'password')
                except Exception as e:
                        return str(e)
                return False

        def disconnect(self):
                self.server.disconnect()
예제 #53
0
파일: VMRun.py 프로젝트: BwRy/test-av2
 def __enter__(self):
     self.server = VIServer()
     self.server.connect(self.sdk_host, self.sdk_user, self.sdk_passwd)
     if config.verbose:
         logging.debug("connected to vSphere")
     vm = self.server.get_vm_by_path(self.vm_path)
     return vm
예제 #54
0
    def sdk_connect(self):

        self.ip = self.configuration.get('vcenter_url', None)
        self.user = self.configuration.get('username', None)
        self.password = self.configuration.get('password', None)
        self.datacenter = self.configuration.get('datacenter', None)

        logger.info('url %s user %s password %s' %
                    (self.ip, self.user, self.password))
        logger.info('datacenter %s' % (self.datacenter))
        server = VIServer()
        server.connect(self.ip,
                       self.user,
                       self.password,
                       trace_file='/tmp/debug.txt')
        return server
예제 #55
0
def get_conn():
    '''
    Return a conn object for the passed VM data
    '''
    server = VIServer()
    server.connect(
        config.get_cloud_config_value(
            'url', get_configured_provider(), __opts__, search_global=False
        ),
        config.get_cloud_config_value(
            'user', get_configured_provider(), __opts__, search_global=False
        ),
        config.get_cloud_config_value(
            'password', get_configured_provider(), __opts__, search_global=False
        ),
    )
    return server
예제 #56
0
def vmwareplugin_datastores(request):
    from pysphere import VIServer
    data = {
        'error': False,
    }
    if request.POST.get('oid'):
        vmware = models.VMWarePlugin.objects.get(id=request.POST.get('oid'))
    else:
        vmware = None
    try:
        if request.POST.get('password'):
            password = request.POST.get('password')
        elif not request.POST.get('password') and vmware:
            password = vmware.get_password()
        else:
            password = ''
        server = VIServer()
        server.connect(
            request.POST.get('hostname'),
            request.POST.get('username'),
            password,
            sock_timeout=7,
        )
        data['value'] = server.get_datastores().values()
        server.disconnect()
    except Exception, e:
        data['error'] = True
        data['errmsg'] = unicode(e).encode('utf8')
예제 #57
0
class ConnHelper(object):
    """Connect the VCENTER SERVER"""
    def __init__(self):
        """The way pySphere connects to vcenter is to use an HTTPS form of SSL connection, preferably with a vcenter
        encryption certificate.Otherwise, the certificate validation failed, after the code import, if the certificate
        is not correct. Add: SSL. _create_default_https_context = ssl._create_unverified_context is used to set
        SSL unverifiable.
        """
        self.ssl = ssl._create_default_https_context = ssl._create_unverified_context
        self.server = VIServer()

    def start_connect_server(self):
        """The address, username, and password to connect to the VC server are set in conf. Py"""
        try:
            self.server.connect(VC.HOST, VC.USER, VC.PASSWORD)
            return self.server
        except Exception, err:
            print "Cannot connect to host: " + VC.HOST + " error message: " + err
예제 #58
0
    def __init__(self, servername=None, password=None, username='******'):
        # Initialize viserver
        self.vi_server = VIServer()

        # Specify excluding VMs' preffix
        self.p = re.compile('xx|yy', re.I)

        self.class_name = self.__class__.__name__
        self.servername = servername
        self.username = username
        self.password = password
        self.vmlist = []
        self.vmstatusdict = {}
        self.inUse_vmstatusdict = {}
        self.vmfullnamelist = {}
        self.inUse_vmfullnamelist = {}
        self.vmdict = {}
        self.inUseDict = {}
예제 #59
0
    def __init__(self):
        try:
            LOGGER.info('vSphereTools version used: {}'.format(__version__))
            LOGGER.debug('vSphereTools Sphere() class initializing...')
            self.vSphereServerInstance = VIServer(
            )  # Initialize main vSphere Server
            self.vSphereServerInstance.connect(
                VC_SERVER, VC_LOGIN, VC_PASSWORD)  # Connect vSphere Client
            self.vmInstance = self.vSphereServerInstance.get_vm_by_name(
                VM_NAME)  # Get instance of virtual machine

        except Exception as e:
            LOGGER.debug(e)
            LOGGER.error(traceback.format_exc())
            self.vSphereServerInstance = None
            self.vm = None
            LOGGER.error(
                'Can not connect to vSphere! Maybe incorrect command? Show examples: vspheretools -h'
            )
예제 #60
0
def set_vm_datastore(host_ip, host_name, host_password, vm_name, reservation):
    #DebugInfo.objects.create(text_info=host_ip+host_name+host_password+vm_name+reservation)
    server = VIServer()
    server.connect(host_ip, host_name, host_password)
    vm_mor = server.get_vm_by_name(vm_name)
    request = VI.ReconfigVM_TaskRequestMsg()
    _this = request.new__this(vm_mor._mor)
    _this.set_attribute_type(vm_mor._mor.get_attribute_type())
    request.set_element__this(_this)
    spec = request.new_spec()

    disk_size = get_disk_size(vm_mor)

    new_hdd = reservation
    device_config_specs = []

    if new_hdd * 1024 * 1024 > disk_size:
        disk = get_disks(vm_mor)[-1]
        hdd_in_GB = new_hdd * 1024 * 1024
        new_disk_size = hdd_in_GB - disk_size + disk.capacityInKB

        device_config_spec = spec.new_deviceChange()
        device_config_spec.set_element_operation('edit')
        disk._obj.set_element_capacityInKB(new_disk_size)
        device_config_spec.set_element_device(disk._obj)
        device_config_specs.append(device_config_spec)

    if len(device_config_specs) != 0:
        spec.set_element_deviceChange(device_config_specs)

    request.set_element_spec(spec)
    ret = server._proxy.ReconfigVM_Task(request)._returnval
    task = VITask(ret, server)
    status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
    ret_flag = False
    if status == task.STATE_SUCCESS:
        #ret = "VM <" + vm_name + "> successfully reconfigured"
        ret_flag = True
    elif status == task.STATE_ERROR:
        #ret = "Error reconfiguring vm <" + vm_name + ">: %s" % task.get_error_message()
        ret_flag = False

    return ret_flag