如何使用libvirt获取VNC端口号?

12

我在一个域名的配置文件中设置了autoport=yes,这样在运行时会自动分配VNC端口(“libvirt”中的“虚拟机”)。

我需要获取这个端口,以便能够从外部连接到vm,但是我找不到合适的API来做到这一点。最好使用Python,因为我正在使用libvirt-python绑定。

4个回答

23

我没有找到任何针对VNC端口的API,不确定更新的libvirt版本是否有此接口?

然而,您可以使用命令virsh vncdisplay $domainName来显示端口。注意:您必须修改/etc/libvirt/qemu.conf以启用vnc_listen='0.0.0.0'


7

没有API可以获取VNC端口号。您需要获取并解析XML文件以找出该端口号。当然,如果虚拟机已经被销毁(关闭/离线),那么该端口号将是-1。

char * virDomainGetXMLDesc (virDomainPtr domain, unsigned int flags)

<domain>
  <devices>
    <graphics type='vnc' port='5900' autoport='yes'/>
  </devices>
</domain>

References


4

如果有人需要,以下是使用 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>

值得一提的是,出于清晰起见,我并没有通过试错找到这个:由于该值来自实时XML信息,因此将正确处理动态端口。因此,如果VM是第三个启动的VNC VM,则此XML定义将显示5902,即使基本配置为port=5000 autoport=yes,您也会如预期一样。 - Joshua Boniface

0

这是针对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"]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接