Show Table of Contents
2.14. 示例:使用 Python 创建虚拟机 NIC
要使新创建的虚拟机可以访问网络资源,您需要创建一个虚拟 NIC 并把它附加到虚拟机上。
例 2.13. 使用 Python 创建虚拟机 NIC
这个 Python 示例创建一个名为
在使用
nic1 的 NIC,并把它附加到名为 vm1 的虚拟机上。这个 NIC 满足以下条件:
- 必须是
virtio网络设备。nic_interface = "virtio"
- 必须连接到
ovirtmgmt管理网络。nic_network = api.networks.get(name="ovirtmgmt")
nics 集合的 add 方法创建 NIC 前,把这些选项组合在一起作为 NIC 参数项。
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")
vm = api.vms.get(name="vm1")
nic_name = "nic1"
nic_interface = "virtio"
nic_network = api.networks.get(name="ovirtmgmt")
nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network)
try:
nic = vm.nics.add(nic_params)
print "Network interface '%s' added to '%s'." % (nic.get_name(), vm.get_name())
except Exception as ex:
print "Adding network interface to '%s' failed: %s" % (vm.get_name(), ex)
api.disconnect()
except Exception as ex:
print "Unexpected error: %s" % ex
如果
add 请求成功,脚本会输出以下信息:
Network interface 'nic1' added to 'vm1'.

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.