0

Is there a way to force virsh to print information in a parseable way? like json?

I want to write a one-liner shell command that gets the IP address of a VM but the way virsh prints it out is not very friendly to scripts:

# virsh domifaddr myvm
 Name       MAC address          Protocol     Address
-------------------------------------------------------------------------------
 vnet1      52:54:00:b9:58:64    ipv4         192.168.130.156/24

I'm looking for a way to force it to not print the headers at least so I can get '192.168.130.156' from the output easily

This is the best I could do:

# virsh -q domifaddr myvm | awk '{print $4}' | cut -d/ -f 1
192.168.130.156
Jeff Saremi
  • 2,674
  • 3
  • 33
  • 57
  • Did a quick search in virsh man pages and it seems there's nothing like printing the output in json or xml format. There's a --pretty option, but not available with domifaddr. I guess your approach is correct and can't think about another way for doing it. Similar to yours, since the ip info is the last word in the line, you could also do: `awk 'NF>1{print $NF}' | cut -d/ -f1` – lainatnavi Aug 28 '20 at 18:51
  • Thank you for looking into this. I think I'll just settle with what i have. – Jeff Saremi Aug 29 '20 at 19:32

1 Answers1

1

One option is to install qemu-guest-agent on the domains you would like to extract IP information from.

From there, you can execute the following command on the host to get a detailed network interface listing in JSON:

ubuntu@host:~$ virsh qemu-agent-command my-guest '{"execute":"guest-network-get-interfaces"}'
{"return":[{"name":"lo","ip-addresses":[{"ip-address-type":"ipv4","ip-address":"127.0.0.1","prefix":8},{"ip-address-type":"ipv6","ip-address":"::1","prefix":128}],"statistics":{"tx-packets":22,"tx-errs":0,"rx-bytes":2816,"rx-dropped":0,"rx-packets":22,"rx-errs":0,"tx-bytes":2816,"tx-dropped":0},"hardware-address":"00:00:00:00:00:00"},{"name":"eth0","ip-addresses":[{"ip-address-type":"ipv4","ip-address":"1.2.3.4","prefix":22},{"ip-address-type":"ipv6","ip-address":"abcd::1234:ee:ab12:e31d","prefix":64}],"statistics":{"tx-packets":11231,"tx-errs":0,"rx-bytes":40717370,"rx-dropped":0,"rx-packets":19744,"rx-errs":0,"tx-bytes":890354,"tx-dropped":0},"hardware-address":"01:02:00:03:04:05"}]}

Your json can be parsed however you'd like from there.

Ali haider
  • 31
  • 1
  • 3