本文整理汇总了Python中pysphere.VIServer.get_vm_by_name方法的典型用法代码示例。如果您正苦于以下问题:Python VIServer.get_vm_by_name方法的具体用法?Python VIServer.get_vm_by_name怎么用?Python VIServer.get_vm_by_name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pysphere.VIServer
的用法示例。
在下文中一共展示了VIServer.get_vm_by_name方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
def main():
opts = options()
# CONNECTION PARAMTERS
server = opts.esx_host
user = opts.user
password = opts.passwd
# REQUIRED PARAMETERS
vmname = opts.name
template = opts.template
cd_iso_location = opts.iso
datastorename = opts.datastore # if None, will use the first datastore available
# CONNECT TO THE SERVER
s = VIServer()
s.connect(server, user, password)
# Clone the VM.
try:
template_vm = s.get_vm_by_name(template)
except Exception as e:
print "Failed to locate the template."
print "Exception:", str(e)
sys.exit(1)
vm = template_vm.clone(vmname, power_on=False)
cdrom = None
for dev in vm.properties.config.hardware.device:
if dev._type == "VirtualCdrom":
cdrom = dev._obj
break
change_cdrom_type(cdrom, "ISO", "[%s] %s" % (datastorename, cd_iso_location))
apply_changes(vm, s, cdrom)
# Here you should power your VM (refer to the pysphere documentation)
# So it boots from the specified ISO location
try:
new_vm = s.get_vm_by_name(opts.name)
connect_vm_cdroms(new_vm, s)
try:
new_vm.power_on()
except Exception as e:
print "Failed to power-on the new VM using:", opts.name
print "Exception:", str(e)
except Exception as e:
print "Failed to locate the new VM using:", opts.name
print "Exception:", str(e)
# disconnect from the server
s.disconnect()
示例2: main
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
def main():
opts = options()
# CONNECTION PARAMTERS
server = opts.esx_host
user = opts.user
password = opts.passwd
# REQUIRED PARAMETERS
vmname = opts.name
# CONNECT TO THE SERVER
s = VIServer()
s.connect(server, user, password)
try:
vm = s.get_vm_by_name(opts.name)
vm.shutdown_guest()
count = 1
wait_for = 60
try:
while count < wait_for and vm.is_powered_off() == False:
count += 1
time.sleep(1)
print "Elapsed %s seconds ..." % str(count)
except Exception as e:
if count >= wait_for:
print "Failed to shutdown the VM (%s) even after %s seconds." % (vmname, str(wait_for))
print "Please login to the EXSi server and fix the issue. Exception: %s" % str(e)
sys.exit(1)
check_count(count, wait_for)
except Exception as e:
print "Failed to locate and shutdown the new VM using:", opts.name
print "VM could not be deleted."
print "Exception:", str(e)
# Invoke Destroy_Task
request = VI.Destroy_TaskRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
ret = s._proxy.Destroy_Task(request)._returnval
# Wait for the task to finish
task = VITask(ret, s)
status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])
if status == task.STATE_SUCCESS:
print "VM successfully deleted from disk"
elif status == task.STATE_ERROR:
print "Error removing vm:", task.get_error_message()
# disconnect from the server
s.disconnect()
示例3: vm_stop
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
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
示例4: main
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
def main():
"""Sets up the module parameters, validates them and perform the change"""
module = AnsibleModule(
argument_spec=dict(
vcenter_hostname=dict(required=True),
username=dict(required=True),
password=dict(required=True),
guest=dict(required=True),
resource_pool=dict(required=True),
cluster=dict(required=True),
sync=dict(required=False, type='bool', default=True)
),
supports_check_mode=True
)
server = VIServer()
server.connect(
module.params['vcenter_hostname'],
module.params['username'],
module.params['password'])
virtualmachine = server.get_vm_by_name(module.params['guest'])
old_name = virtualmachine.get_resource_pool_name()
new_name = module.params['resource_pool']
# find the clusters ManagedObjectReference
cluster = None
clusters = server.get_clusters()
for mor, name in clusters.iteritems():
if name == module.params['cluster']:
cluster = mor
break
if cluster is None:
module.fail_json(msg='Cluster %s not found on server %s' %
(module.params['cluster'], module.params['vcenter_hostname']))
# find the new resource pools Managed Object Reference and migrate the VM
rps = server.get_resource_pools(from_mor=cluster)
for mor, path in rps.iteritems():
if re.match('.*%s$' % new_name, path):
if not re.match('.*%s$' % old_name, path):
if not module.check_mode:
virtualmachine.migrate(
resource_pool=mor,
host=virtualmachine.get_property('hostname'),
sync_run=module.params['sync'])
module.exit_json(changed=True, changes=module.params)
module.exit_json(changed=False, changes=module.params)
module.fail_json(msg='Resource pool %s not found' %
module.params['resource_pool'])
示例5: vm_state
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
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"
示例6: set_ip_via_vsphere
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
def set_ip_via_vsphere(vm_name, fqdn):
#Connect to vSphere
server = VIServer()
server.connect(settings.VSPHERE_HOSTNAME, settings.VSPHERE_USERNAME, settings.VSPHERE_PASSWORD)
#Connect to the new vm. Call the object vm1
vm1 = server.get_vm_by_name(vm_name)
vm1.login_in_guest(settings.VSPHERE_TEMPLATE_USERNAME, settings.VSPHERE_TEMPLATE_PASSWORD)
#login and set the IP and restart networking to get it on the air
vm1.send_file(settings.TEMP_LOCATION_CONFIG_NETWORK.format(fqdn=fqdn), '/etc/sysconfig/network', overwrite=True)
vm1.send_file(settings.TEMP_LOCATION_CONFIG_ETH0.format(fqdn=fqdn), '/etc/sysconfig/network-scripts/ifcfg-eth0', overwrite=True)
vm1.start_process("/sbin/service", args=["network", "restart"])
vm1.start_process("/bin/hostname", args=[fqdn])
#disconnect from vSphere
server.disconnect()
示例7: vm_migrate
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
def vm_migrate():
"""Migrate the VMs based on the list given"""
user, passwd, vcenter = get_user_info()
host, servers, servercount = get_serverlist()
s = VIServer()
s.connect(vcenter, user, passwd)
getserver_type_api()
esxhost_input = raw_input('Enter target ESX Host: ')
esxhost = s.get_hosts().items()
for k,v in esxhost:
if v == esxhost_input:
for host in servers:
host = host.strip()
vm = s.get_vm_by_name(host)
vm.migrate(host=k)
time.sleep(10)
s.disconnect()
示例8: ERROR
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
if(not vm in vm_d):
if(is_replica):
ERROR(ErrorCode.E_MISSING_REPLICA,appid," (%s)" % vm)
else:
ERROR(ErrorCode.E_MISSING_VM,appid," (%s)" % vm)
continue
m = re.match('(\S+-\S+-\S+-\S+-(AMP|MGMT))',appid)
clstrid = m.group(1)
if(clstrid_d[clstrid] != host_d[vm_d[vm]]):
ERROR(ErrorCode.E_WRONG_CLUSTER,appid,"| Actual %s" % clstrname_d[host_d[vm_d[vm]]])
vmo = None
try:
vmo = vc.get_vm_by_name(vm)
osstr = vmo.get_property('guest_full_name')
except:
raise Exception("Failed to get VM object %s (%s)",appid,vm)
if(is_replica and (not re.match('.+-(M|LS)$',appid))):
if(vmo.is_powered_off()):
logger.info ("VERIFIED %s (%s/%s)",appid,vm,osstr)
else:
logger.error ("Replica VM is running %s (%s)",appid,vm)
else:
if(vmo.is_powered_on()):
logger.info ("VERIFIED %s (%s/%s)",appid,vm,osstr)
else:
logger.error ("VM not running %s (%s)",appid,vm)
示例9:
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
print server.get_api_version()
print server.get_clusters()
print server._get_resource_pools
#Get all the hosts
print server.get_hosts()
#Get VM`s in Prod resource pool which are in poweredon state
vmachines = server.get_registered_vms()
vmachines = server.get_registered_vms(resource_pool='Prod', status='poweredOn')
#Get virtual machine status
vm1 = server.get_vm_by_name('rhel5.3_prod')
print vm1.get_status()
#Also you can ask the following:
print vm1.is_powering_off()
print vm1.is_powered_off()
print vm1.is_powering_on()
print vm1.is_powered_on()
print vm1.is_suspending()
print vm1.is_suspended()
print vm1.is_resetting()
print vm1.is_blocked_on_msg()
print vm1.is_reverting()
#For power options:
示例10: VIServer
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
server = VIServer()
server.connect(vcenter, vcuser, password)
# Actions:
# 1. Shut the VM off
# 2. Delete existing VM snapshots
# 3. Create a new snapshot with VM name and current date.
# 4. Turn the VM back on
vm = server.get_vm_by_name('vm_name')
if vm.is_powered_on():
vm.power_off()
if vm.is_powered_off():
try:
vm.delete_current_snapshot(remove_children=True)
except:
示例11: len
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
import sys
sys.path.append("./pysphere")
from pysphere import VIServer
from pysphere.resources.vi_exception import VIException, VIApiException, \
FaultTypes
import sys
if len(sys.argv) != 6:
sys.exit("error = please check arguments")
serverName = sys.argv[1]
login = sys.argv[2]
passwd = sys.argv[3]
vm_name = sys.argv[4]
snap_name = sys.argv[5]
server = VIServer()
server.connect(serverName, login, passwd)
myVm = server.get_vm_by_name(vm_name)
try:
deleteTask = myVm.delete_named_snapshot(snap_name)
server.disconnect()
except (VIException), err:
print "DeleteResult = " + err.message
sys.exit(1)
if deleteTask is None:
print "DeleteResult = success"
else:
print "DeleteResult = failure"
示例12: main
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
def main():
####### MAIN #######
t0 = time.clock()
if len(sys.argv) == 3:
vm1Guest = sys.argv[1]
vm1DataCenter = sys.argv[2]
else:
print "Usage: ./script guestName dataCenter \n\n dataCenter is ABC, DEF or FGH \n\n"
exit()
print " -->> Begin"
server = VIServer()
server.connect(server1, userLDAP, passLDAP)
print "VMGuest : %s" % vm1Guest
print "Datacenter : %s" % vm1DataCenter
vm1 = server.get_vm_by_name(vm1Guest, vm1DataCenter)
vm1Path = vm1.get_property('path', from_cache=False)
vm1Path = vm1Path.split(' ', 1);
vm1DataStore = vm1Path[0].strip('[]')
vm1FolderTmp = vm1Path[1].split('/')
vm1Folder = vm1FolderTmp[0].strip()
print "VMDataStore: %s" % vm1DataStore
print "VMFolder : %s" % vm1Folder
print "VMStatus : %s" % vm1.get_status(basic_status=True)
if vm1.is_powered_on():
print "%s is powered ON" % vm1Guest
vm1.power_off()
t1 = time.clock()
while vm1.is_powering_off():
print "waiting power of..."
t = time.clock() - t1
print "%f seconds", t
print "%s is NOW powered OFF" % vm1Guest
if vm1.is_powered_off() and vm1DataStore is not None and vm1Folder is not None:
server.disconnect()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "Connecting to %s" % splitOrigemHost
ssh.connect(splitOrigemHost, username=userLDAP, password=passLDAP, timeout=5)
vm1Path = '/vmfs/volumes/%s/%s/' % (vm1DataStore, vm1Folder)
print "Copying files from %s to %s" % (vm1Path, splitDestPath)
stdin, stdout, stderr = ssh.exec_command('scp -p -r [email protected]%s:"\'%s\'" %s && echo "Scp Done!" && chmod -R 755 %s/"%s"/ ' % (vmOrigemHost, vm1Path, splitDestPath, splitDestPath, vm1Folder) )
for i in stdout.readlines():
print i.strip()
for i in stderr.readlines():
print i.strip()
print "We got something on stderr, aborting script. Probably errors on SCP."
exit()
stdin1, stdout1, stderr1 = ssh.exec_command('ls -1sSh %s"%s"/' % (splitDestPath, vm1Folder) )
for i in stdout1.readlines():
print i.strip()
stdin2, stdout2, stderr2 = ssh.exec_command('ls -1 %s"%s"/' % (splitDestPath, vm1Folder) )
filesArray = []
for i in stdout2.readlines():
filesArray.append(i.strip())
ssh.close()
print "Everything DONE for first copy phase, now get files on other side"
print "Connecting to %s" % splitDestHost
ssh.connect(splitDestHost, username=userLDAP, password=passLDAP, timeout=5)
for i in filesArray:
print "\nDownloading at %s, from %s. File: %s" % (splitDestHost, splitOrigemHostFr, i)
stdin, stdout, stderr = ssh.exec_command('aria2c --conditional-get=true --max-concurrent-downloads=16 --max-connection-per-server=16 --split=16 --continue=true --connect-timeout=300 --max-tries=5 --dir="%s%s/" \'http://%s/%s/%s\' && echo "Download OK!"' % (splitDestPath, vm1Folder, splitOrigemHostFr, vm1Folder, i) )
for j in stdout.readlines():
print "ARIA2C log: %s" % j.strip()
for j in stderr.readlines():
print "ARIA2C stderr log: %s" % j.strip()
print "Download at %s was OK!" % splitDestHost
if vmDestDataStore is not None and vm1Folder is not None:
vm1Path = '/vmfs/volumes/%s/' % (vmDestDataStore)
print "Sending files from %s:%s%s/, to %s:%s" % (splitDestHost, splitDestPath, vm1Folder, vmDestHost, vm1Path)
stdin, stdout, stderr = ssh.exec_command('scp -p -r \'%s%s/\' [email protected]%s:"%s" && echo "Scp Done!" ' % (splitDestPath, vm1Folder, vmDestHost, vm1Path) )
for i in stderr.readlines():
print i.strip()
print "Registering guest on VMWare"
vm1Path = '/vmfs/volumes/%s/%s/' % (vmDestDataStore, vm1Folder)
stdin, stdout, stderr = ssh.exec_command('ssh [email protected]%s ls -1 "\'%s\'"*.vmx' % (vmDestHost, vm1Path) )
vmxArray = []
for i in stdout.readlines():
vmxArray.append(i.strip())
#default guests name are guest01-abc, guest02-def, guest01-fgh , so "name-datacenter"
#just replace datacenter string
#.........这里部分代码省略.........
示例13: VIServer
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
#!/usr/bin/python
"""
Author: Pryz
Description: Get current status and properties of a VM with pysphere
"""
from pysphere import VIServer
# Connect to the vcenter
LOGIN = "user"
PWD = "password"
VCENTER = "vcenter.labo.fr"
SERVER = VIServer()
SERVER.connect(VCENTER, LOGIN, PWD)
VMNAME = "vm1.labo.fr"
VM = SERVER.get_vm_by_name(VMNAME)
print VM.get_status()
print VM.get_property("ip_address")
print VM.get_properties()
# Close connection
SERVER.disconnect()
示例14: main
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
def main():
global vCenter, user, password, problem_keys
(options, args) = parse_args()
vCenter = options.vsphere
user = options.user
password = getpass.getpass("Please provide the password for "+user+":")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
svr = VIServer()
for host in options.hostname:
print colors.yellow+"Starting fix for "+host+colors.endc
if options.pretend is True:
print colors.green+"This system will not be harmed during the course of this script."
print "Meaning: it will "+colors.red+"NOT"+colors.green+" be shutdown, changed, reloaded and powered on again."+colors.endc
print ""
print "Searching vCenter membership"
vmobj = None
for e in options.vsphere:
svr.connect(e,options.user,password)
try:
vm = svr.get_vm_by_name(host)
vCenterHost = e
break
except:
vm = None
if vm is None:
print colors.red+"'"+host+"' could not be found on any of the vCenter servers. Aborting."+colors.endc
continue
else:
print colors.green+"Found: "+vCenterHost+colors.endc
print "Determining ESX host"
try:
temp = vm.properties
esxhost = temp.runtime.host.name
except:
print colors.red+"Could not determine the physical host for '"+host+"'. Aborting."+colors.endc
continue
print colors.green+"Found:", esxhost, colors.endc
print "Determining local path to vmx file"
try:
vmxpath = vm.get_property("path").replace("[","/vmfs/volumes/").replace("] ","/")
except:
print colors.red+"Could not determine the vmx file path for '"+host+"'. Aborting."+colors.endc
continue
print colors.green+"Found:", vmxpath, colors.endc
print "Retrieving vmx file"
try:
ssh.connect(esxhost, username="root")
except:
print colors.red+"Could not connect to "+esxhost+" over ssh. Aborting."+colors.endc
continue
stdin, stdout, stderr = ssh.exec_command("cat "+vmxpath)
out = stdout.read()
print colors.green+"Done"+colors.endc
print "Looking for problem keys"
severity = 0
for key in problem_keys:
if key in out:
print colors.yellow+"Found: "+key+colors.endc
severity = severity +1
print colors.green+"Done"+colors.endc
if severity == 0:
print colors.yellow+"None of the offending keys have been found"+colors.endc
if options.force == False:
print colors.red+"Aborting"+colors.endc
continue
if options.pretend is not True:
print "Powering off the vm"
try:
if vm.get_status(basic_status=True) == 'POWERED ON':
vm.shutdown_guest()
count = 0
ret = ''
while ret != "POWERED OFF":
sleep(1)
ret = vm.get_status(basic_status=True)
count = count +1
if count > 300:
print "The system did not gracefully shutdown. Please fix. Aborting all."
exit(1)
elif vm.get_status(basic_status=True) == 'POWERED OFF':
print "The system is either already shutdown, or there are no vmware tools installed."
raw_input("Press ENTER to continue or CTRL+C to abort")
except:
print colors.red+"Something went wrong powering off "+host+". Aborting."+colors.endc
break
else:
print "Pretending to power off the vm"
#.........这里部分代码省略.........
示例15: raw_input
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_vm_by_name [as 别名]
options.vcenter = raw_input("Enter the vCenter to connect to: ")
try:
options.username
except NameError:
options.username = raw_input("Enter the usename to use: ")
try:
options.password
except NameError:
options.password = getpass()
try:
options.vm_path
except NameError:
options.vm_path = raw_input("Enter the Template/VM to convert: ")
# Make the vcenter connection
server = VIServer()
server.connect(options.vcenter, options.username, options.password)
vm = server.get_vm_by_name(options.vm_path)
request = VI.MarkAsTemplateRequestMsg()
_this = request.new__this(vm._mor)
_this.set_attribute_type(vm._mor.get_attribute_type())
request.set_element__this(_this)
server._proxy.MarkAsTemplate(request)
server.disconnect()