Search code examples
network-programmingsshqemuportforwardingkvm

How do I ssh into a KVM with minimal configuration/infrastructure?


As per another QA, it's possible to setup a Ubuntu KVM with minimal infrastructure, directly with qemu / kvm alone (without virsh or any some such).

What's missing is the ability to ssh into it. (Using the default serial console is slow and some key bindings don't work, e.g., cannot go to the start of the line with control+A.)

What's the simplest hackish way to bind a single port on the host machine (e.g., 8022) to a given port on the virtualised one (e.g., 22), without setting up extra bridge networks, firewall rules or configuration files?

The simplest non-KVM-specific way I could think of would be to use ssh to ssh from the guest back to the host, with using the -R [bind_address:]port:host:hostport option of ssh, e.g., ssh -R "8022:[::1]:22" [email protected], but then this requires setting up a new user on the host and sharing login credentials between the host and the guest. Is there a simpler way?

P.S. The network on the guest already works, and you can already access the host from the guest, but I couldn't find a way to access the guest from within the host through IP (without setting up complex bridge networks).


Solution

  • The answer appears to be pretty straightfoward — as per https://unix.stackexchange.com/questions/124681/how-to-ssh-from-host-to-guest-using-qemu, just add the following to the kvm options, to forward the port 1810 on the host to 22 on the guest:

    -net nic -net user,hostfwd=tcp::1810-:22

    E.g.,

    kvm -m 2048 -smp 2 -hda ubuntu-18.10-server-cloudimg-amd64.img -hdb user-data.img -net nic -net user,hostfwd=tcp::1810-:22 -nographic

    Then you can ssh into the machine w/ ssh ubuntu@localhost -p1810.