List VM names with spice ports

With multiple VMs (kvm/qemu) running on a host I need to know the port a VM is on in order to connect.

It is possible to get there with

[root@devpc vmStorage]# netstat -tulpn | grep qemu
tcp        0      0*               LISTEN      2050708/qemu-kvm    
tcp        0      0*               LISTEN      3307043/qemu-kvm 


[root@devpc vmStorage]# ps -eo pid,command | grep qemu
2050708 /usr/libexec/qemu-kvm -name guest=fedoraSRVR,de .......(goes on for quite a bit)

where you can cross ref the pids to match VM by name with port.

Does anyone know of an existing standard command to get the info in one go ? ie. to output : fedoraSRVR fedoraWS

I rarely connect to VM’s, but when I do, I do it from Virtual Machine Manager. Python-based and supposedly deprecated. I run it on my machine and it connects to host with ssh. (This is rare cases where I’m ok with clickety clack GUI crap …)

What do you get with:

virsh dumpxml fedoraSRVR | grep spice

yeah, that is cleaner…

[root@devpc vmStorage]# virsh list
 Id   Name         State
 4    fedoraSRVR   running
 8    fedoraWS     running

[root@devpc vmStorage]# virsh dumpxml fedoraWS | grep -m 1 graphics
    <graphics type='spice' port='5900' autoport='yes' listen=''>

but still 2 steps and stuff to remember…

In lieu of there being a command / option for it here’s my new approach:


function vmpt () { # active vm qemu / spice guest connection ports
    # line 1: join extract of pid and vm guest names sorted by pid with ..
    # line 2: extract of pid, address and port sorted by pid
    # line 3: remove pid, sort by guest name, align columns
    join <(ps -eo pid,command | grep qemu | sed -En 's/(^\s*[[:digit:]]+).*guest=([^\s,]+).*$/\1 \2/p' | sort) \
         <(netstat -tulpn | grep qemu | sed 's/\// /' | awk  '{print $7,$4}' | sort) \
         | awk '{print $2,$3}' | sort | column -t 
export -f vmpt

to /etc/profile.d/

then log out/ back in to shell and …

[root@devpc bob]# vmpt

EDITED above since original post as indents in ps output started breaking it - optional whitespace at start of line accounted for in sed.


join <(ps -eo pid,command | grep qemu | sed -En 's/(^\s*[[:digit:]]+).*guest=([^[:space:],]+).*$/\1 \2/p' | sort) \
         <(netstat -tulpn | grep qemu | sed 's/\// /' | awk  '{print $7,$4}' | sort) \
         | awk '{print $2,$3}' | sort | column -t 

sed -E handles \s but not inside []