This is a shameless copy of this blog post, but I felt like I need to put it here as well, so that I can find it the next time I need it 🙂
libvirt approach
When you run a lot of VMs, especially for testing, every time with a fresh operating system, connecting to them is a pain, because you always need to figure out their IP address first. Turns out that is no longer true. I simply added this snippet to my ~/.ssh/config
:
# https://penguindroppings.wordpress.com/2017/09/20/easy-ssh-into-libvirt-vms-and-lxd-containers/ # NOTE: doesn't work with uppercase VM names Host *.vm CheckHostIP no Compression no UserKnownHostsFile /dev/null StrictHostKeyChecking no ProxyCommand nc $(virsh domifaddr $(echo %h | sed "s/\.vm//g") | awk -F'[ /]+' '{if (NR>2 && $5) print $5}') %p
and now I can simply execute ssh test.vm
for a VM named test and I’m connected! A huge time saver. It doesn’t work with uppercase letters in VM names and I didn’t bother to try to fix that. Also, since I run VMs just for testing purposes, I disabled all ssh security checks (you should not do that for important machines).
avahi approach
There’s also a second approach I used for persistent VMs (those that survive for longer than a single install&reboot cycle). You can use Avahi to search for a hostname on the .local domain to find the IP address. Fedora has this enabled by default (if you have nss-mdns package installed, I believe, which should be by default). So, in the VM, set a custom hostname, for example f27:
$ sudo hostnamectl set-hostname f27 $ reboot
Now, you can run ssh f27.local
and it should connect you to the VM automatically.
For the first solution, you can use
nc -F
with SSHProxyUseFdpass
and avoid keeping an extranc
proces around.Recent versions of libvirt provide a NSS module: http://libvirt.org/nss.html. This allows to easily SSH, by providing either the hostname of the guest, or its libvirt name.
Interesting, thanks. But I guess I prefer the ‘.vm’ or ‘.local’ suffix, so that I can clearly distinguish a network host from a VM host and their names won’t potentially clash.
Nice trick thanks. I mean what Kamil found is great, but I just love http://libvirt.org/nss.html 🙂