def setUpClass(cls): config_path = os.path.join(os.path.dirname(__file__), "config.ini") cls.config = configparser.ConfigParser() cls.config.read(config_path) host = cls.config.get("READ_ONLY_ENV", "host") user = cls.config.get("READ_ONLY_ENV", "user") pswd = cls.config.get("READ_ONLY_ENV", "password") host2 = cls.config.get("SANDBOX_ENV", "host") user2 = cls.config.get("SANDBOX_ENV", "user") pswd2 = cls.config.get("SANDBOX_ENV", "password") cls.server = VIServer() cls.server.connect(host, user, pswd) cls.server2 = VIServer() cls.server2.connect(host2, user2, pswd2) cls.vm_tools_path = cls.config.get("SANDBOX_ENV", "windows_vm_with_tools") cls.vm_tools_snap = cls.config.get("SANDBOX_ENV", "windwos_vm_snapshot") cls.vm_tools_user = cls.config.get("SANDBOX_ENV", "windows_vm_username") cls.vm_tools_pass = cls.config.get("SANDBOX_ENV", "windows_vm_password") cls.vm_tools = cls.server2.get_vm_by_path(cls.vm_tools_path) cls.vm_toy_path = cls.config.get("SANDBOX_ENV", "writable_vm") cls.vm_toy = cls.server2.get_vm_by_path(cls.vm_toy_path)
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')
def main(): module = AnsibleModule(argument_spec=dict( vcenter_hostname=dict(required=True), username=dict(required=True), password=dict(required=True), guest=dict(required=True), validate_certs=dict(required=False, type='bool', default=True), ), supports_check_mode=True) host = module.params.get('vcenter_hostname') login = module.params.get('username') password = module.params.get('password') guest = module.params.get('guest') validate_certs = module.params['validate_certs'] server = VIServer() if not validate_certs: default_context = ssl._create_default_https_context ssl._create_default_https_context = ssl._create_unverified_context try: server.connect(host, login, password) except Exception, e: module.fail_json(msg='Failed to connect to %s: %s' % (host, e))
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
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(argv): try: opts, args = getopt.getopt( argv, "i:u:p:n:h", ["iphost=", "vuser="******"vpass="******"vmname=", "help"]) except getopt.GetoptError: print 'test.py -i <vhost> -u <name> -p <vpass> -n <vmname>' sys.exit(4) for opt, arg in opts: if opt == '-h': print 'test.py -i <vhost> -u <vname> -p <vpass> -n <vmname>' sys.exit() elif opt in ("-i", "--vhost"): iphost = arg elif opt in ("-u", "--vname"): vuser = arg elif opt in ("-p", "--vpass"): vpass = arg elif opt in ("-n", "--vmname"): vmname = arg ssl._create_default_https_context = ssl._create_unverified_context server = VIServer() server.connect(iphost, vuser, vpass) vm1 = server.get_vm_by_name(vmname) print vm1.get_properties().get('ip_address')
def vm_status(self, vm_name): 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() except Exception as e: server_obj.disconnect() print e # 通过名称获取vm的实例 try: vm = server_obj.get_vm_by_name(vm_name) if vm.is_powered_off() == False: server_obj.disconnect() return 1 if vm.is_powered_off() == True: server_obj.disconnect() return 2 except Exception as e: server_obj.disconnect() return 3
def connect(self): # SSL_VERIFY_ERROR fix # https://gist.github.com/gkhays/2e1c06e1bfee95cb8f705f82ba8e48fe default_context = ssl._create_default_https_context ssl._create_default_https_context = ssl._create_unverified_context 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 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
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) # 清空数据盘 except Exception as e: # print(e) pass finally: print(f'{vm_name} 数据盘清空完毕!!!!!') else: print(f'{vm_name} tools is not RUNING--------------------')
def vm_status(self, vm_name): 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() except Exception as e: server_obj.disconnect() log.info(e) # 通过名称获取vm的实例 try: vm = server_obj.get_vm_by_name(vm_name) if vm.is_powered_off() == False: server_obj.disconnect() return 1 if vm.is_powered_off() == True: server_obj.disconnect() return 2 except Exception as e: server_obj.disconnect() return 3
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))
def main(): module = AnsibleModule(argument_spec=dict( vcenter_hostname=dict(required=True, aliases=['vcenter']), username=dict(required=True, aliases=['user']), password=dict(required=True), guest=dict(required=True), validate_certs=dict(required=False, type='bool', default=True), disk=dict(required=True, aliases=['unit']), size=dict(required=True)), supports_check_mode=True) host = module.params.get('vcenter_hostname') login = module.params.get('username') password = module.params.get('password') guest = module.params.get('guest') validate_certs = module.params['validate_certs'] disk_unit = int(module.params.get('disk')) disk_size = int(module.params.get('size')) if disk_unit < 1 or disk_unit > 6: module.fail_json(msg='Dubious disk unit') if disk_size < 8 or disk_unit > 2000: module.fail_json(msg='Dubious disk size') server = VIServer() if not validate_certs: default_context = ssl._create_default_https_context ssl._create_default_https_context = ssl._create_unverified_context try: server.connect(host, login, password) except Exception, e: module.fail_json(msg='Failed to connect to %s: %s' % (host, e))
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))
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
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
def __init__(self): self.host = config.vmware_host self.user = config.vmware_user self.pwd = config.vmware_pass self.connection = VIServer() self.connection.connect(self.host, self.user, self.pwd) self.props = VIProperty(self.connection, self.connection._do_service_content.CustomFieldsManager) self.custom_fields = dict((cf.key, cf.name) for cf in self.props.field)
def connect_host(host, user, pswd): server = VIServer() try: server.connect(host, user, pswd) LOG.info("Connected to %s %s", server.get_server_type(), host) return server except: print "unable to connect to host: " + host + " error message: "
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 _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
def connect_vcenter(vcenter_address, vcenter_username, vcenter_password): ssl._create_default_https_context = ssl._create_unverified_context vcenter_server = VIServer() vcenter_server.connect(host=vcenter_address, user=vcenter_username, password=vcenter_password) print "connect to vcenter." return vcenter_server
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))
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
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
def test_vmware_version_vcenter(self): """ Is the Vmware version at 5.1?""" server = VIServer() server.connect(CREDS.get('Vcenter', 'server'), CREDS.get('Vcenter', 'user'), CREDS.get('Vcenter', 'pass')) api = server.get_api_version() self.assertEqual('5.1', api) server.disconnect()
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
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."
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: print e
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
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)