How to get VNC port number using libvirt?
Asked Answered
L

4

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.

Lateen answered 1/11, 2012 at 8:5 Comment(0)
D
23

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'.

Darciedarcy answered 14/11, 2012 at 5:29 Comment(0)
I
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

Ita answered 17/10, 2013 at 23:1 Comment(0)
F
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>
Flattish answered 9/12, 2015 at 14:27 Comment(1)
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.Expellee
P
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"]);
Payson answered 30/3, 2015 at 17:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.