我在一个域名的配置文件中设置了autoport=yes
,这样在运行时会自动分配VNC端口(“libvirt”中的“虚拟机”)。
我需要获取这个端口,以便能够从外部连接到vm,但是我找不到合适的API来做到这一点。最好使用Python,因为我正在使用libvirt-python绑定。
我在一个域名的配置文件中设置了autoport=yes
,这样在运行时会自动分配VNC端口(“libvirt”中的“虚拟机”)。
我需要获取这个端口,以便能够从外部连接到vm,但是我找不到合适的API来做到这一点。最好使用Python,因为我正在使用libvirt-python绑定。
我没有找到任何针对VNC端口的API,不确定更新的libvirt版本是否有此接口?
然而,您可以使用命令virsh vncdisplay $domainName
来显示端口。注意:您必须修改/etc/libvirt/qemu.conf
以启用vnc_listen='0.0.0.0'
。
没有API可以获取VNC端口号。您需要获取并解析XML文件以找出该端口号。当然,如果虚拟机已经被销毁(关闭/离线),那么该端口号将是-1。
char * virDomainGetXMLDesc (virDomainPtr domain, unsigned int flags)
<domain>
<devices>
<graphics type='vnc' port='5900' autoport='yes'/>
</devices>
</domain>
如果有人需要,以下是使用 Python 的方法。
将文件保存为 vncport.py。
from xml.etree import ElementTree as ET
import sys
import libvirt
conn = libvirt.open()
domain = conn.lookupByName(sys.argv[1])
#get the XML description of the VM
vmXml = domain.XMLDesc(0)
root = ET.fromstring(vmXml)
#get the VNC port
graphics = root.find('./devices/graphics')
port = graphics.get('port')
print port
运行命令
python vncport.py <domain name>
这是针对PHP版本的,如果有人需要:
$res = libvirt_domain_lookup_by_name($conn, $domname);
$xmlString = libvirt_domain_get_xml_desc($res, '');
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml);
$data = json_decode($json,TRUE);
$port = intval($data["devices"]["graphics"]["@attributes"]["port"]);
5902
,即使基本配置为port=5000 autoport=yes
,您也会如预期一样。 - Joshua Boniface