Show Table of Contents
2.16. 示例:使用 Python 为虚拟机附加一个 ISO 镜像
在一个新建虚拟机上开始安装操作系统前,需要附加包括了操作系统安装介质的 ISO 镜像文件。
例 2.15. 指定 ISO 镜像
ISO 镜像包括在附加到 ISO 存储域中的
files 集合中。这个示例列出了一个 ISO 存储域中的 files 集合中的内容。
from ovirtsdk.api import API
from ovirtsdk.xml import params
try:
api = API(url="https://HOST",
username="USER@DOMAIN",
password="PASS",
ca_file="ca.crt")
sd = api.storagedomains.get(name="iso1")
iso = sd.files.list()
for i in iso:
print "%s" % i.get_name()
except Exception as ex:
print "Unexpected error: %s" % ex
如果运行成功,脚本会为在
files 集合中找到的每个文件输出和以下相似的内容:
RHEL6.3-Server-x86_64-DVD1.iso
请注意,因为 ISO 域中的每个文件的名称必须是唯一的,所以文件的
id 和 name 属性是相同的。
例 2.16. 使用 Python 为虚拟机附加一个 ISO 镜像
这个 Python 示例把
RHEL6.3-Server-x86_64-DVD1.iso ISO 镜像文件附加到 vm1 虚拟机上。使用虚拟机的 cdroms 集合的 add 方法可以把指定的镜像文件附加到虚拟机上。
from ovirtsdk.api import API
from ovirtsdk.xml import params
try:
api = API(url="https://HOST",
username="USER@DOMAIN",
password="PASS,
ca_file="ca.crt")
sd = api.storagedomains.get(name="iso1")
cd_iso = sd.files.get(name="RHEL6.3-Server-x86_64-DVD1.iso")
cd_vm = api.vms.get(name="vm1")
cd_params = params.CdRom(file=cd_iso)
try:
cd_vm.cdroms.add(cd_params)
print "Attached CD to '%s'." % cd_vm.get_name()
except Exception as ex:
print "Failed to attach CD to '%s': %s" % (cd_vm.get_name(), ex)
api.disconnect()
except Exception as ex:
print "Unexpected error: %s" % ex
如果
add 请求成功,脚本会输出以下信息:
Attached CD to 'vm1'.
注意
上面的示例是把一个 ISO 镜像附加到一个状态为
Down 的虚拟机上。如果需要把 ISO 附加到一个状态为 Up 的虚拟机上时,把第 2 个 try 中的代码改为:
try: cdrom=cd_vm.cdroms.get(id="00000000-0000-0000-0000-000000000000") cdrom.set_file(cd_iso) cdrom.update(current=True) print "Attached CD to '%s'." % cd_vm.get_name() except: print "Failed to attach CD to '%s': %s" % (cd_vm.get_name(), ex)
例 2.17. 使用 Python 从虚拟机上弹出一个 cdrom
从虚拟机的
cdrom 集合中弹出一个 ISO。
from ovirtsdk.api import API
from ovirtsdk.xml import params
try:
api = API(url="https://HOST",
username="USER@DOMAIN",
password="PASS,
ca_file="ca.crt")
sd = api.storagedomains.get(name="iso1")
vm = api.vms.get(name="vm1")
try:
vm.cdroms.get(id="00000000-0000-0000-0000-000000000000").delete()
print "Removed CD from '%s'." % vm.get_name()
except Exception as ex:
print "Failed to remove CD from '%s': %s" % (vm.get_name(), ex)
api.disconnect()
except Exception as ex:
print "Unexpected error: %s" % ex
Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.