12

I set autoport=yes in a domain's("virtual machine" in libvirt) config file so the VNC port is assigned automatically in the run time.

I need to get this port so I can connect to the vm from outside, but I can't find the proper API to do so. Better in python because I'm using the libvirt-python bindings.

can.
  • 2,098
  • 8
  • 29
  • 42

4 Answers4

22

I have not found any API for the VNC port, not sure if the newer version of libvirt has this interface?

However, you can use the command virsh vncdisplay $domainName to show the port. NOTE: you must modify /etc/libvirt/qemu.conf enable vnc_listen='0.0.0.0'.

slm
  • 15,396
  • 12
  • 109
  • 124
liuzhijun
  • 4,329
  • 3
  • 23
  • 27
7

There's no API to get the VNC port. You have to take and parse the XML file to find out that port. Of course if the guest is destroyed (powered off/offline) that port will be a value of -1.

char * virDomainGetXMLDesc (virDomainPtr domain, unsigned int flags)

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

References

slm
  • 15,396
  • 12
  • 109
  • 124
Cyb.org
  • 101
  • 1
  • 3
4

Here's how you do it in python, in case anyone needs this.

Save as 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

Run Command

python vncport.py <domain name>
Mike Glenn
  • 3,359
  • 1
  • 26
  • 33
Pandrei
  • 4,843
  • 3
  • 27
  • 44
  • It's worth mentioning for clarity's sake because I wasn't and found this via trial-and-error: This value, since it's coming from the *live* XML info, will properly handle dynamic ports. So if the VM is 3rd VNC VM to start up, this XML definition will show `5902` as you would expect even if the base configuration is `port=5000 autoport=yes`. – Joshua Boniface Dec 20 '20 at 21:03
0

Here is one for the PHP version, if anyone needs this:

    $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"]);
slm
  • 15,396
  • 12
  • 109
  • 124
Benjamin Piette
  • 3,645
  • 1
  • 27
  • 24