Permanently Forwarding Specific Port Remote Access to QEMU Guest Linux on Host
QEMU (Quick Emulator) is a powerful open-source machine emulator and virtualizer that can run operating systems and programs on a host computer. This article will discuss how to permanently forward a specific port for remote access to a QEMU guest Linux on a host machine.
Prerequisites
Ensure that you have the following installed and configured:
- QEMU
- KVM (Kernel-based Virtual Machine) acceleration
- Linux distribution as the guest operating system
- SSH (Secure Shell) server installed and running on the guest Linux OS
Port Forwarding in QEMU
QEMU provides the ability to forward host ports to guest virtual machines using the -redir option. By using this option, you can specify the host and guest ports to be forwarded. For instance, if you want to forward host port 2222 to guest port 22 (SSH), you would use the following command:
-redir tcp:2222::22However, this configuration is not persistent and will be lost upon rebooting the host machine. To make it permanent, you need to modify the QEMU startup script.
Making Port Forwarding Permanent
To make the port forwarding permanent, you need to modify the QEMU startup script. The location of this script depends on your Linux distribution. For example, on Ubuntu, the script is located at /etc/init/qemu-system-x86.conf.
Open the script with your preferred text editor and add the following lines at the beginning of the script:
pre-start script
if [ ! -f /etc/qemu-ifup ]; then
touch /etc/qemu-ifup
chmod +x /etc/qemu-ifup
fi
if [ ! -f /etc/qemu-ifdown ]; then
touch /etc/qemu-ifdown
chmod +x /etc/qemu-ifdown
fi
cat >> /etc/qemu-ifup << EOF
#!/bin/sh
iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 10.0.2.15:22
EOF
cat >> /etc/qemu-ifdown << EOF
#!/bin/sh
iptables -t nat -D PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 10.0.2.15:22
EOFReplace 2222 with the host port number you want to use, and 10.0.2.15:22 with the IP address and port number of the guest Linux SSH server. Save and close the file.
Now, restart the QEMU service to apply the changes:
sudo service qemu-kvm restartTesting the Configuration
To test the configuration, connect to the host machine using an SSH client and specify the forwarded port:
ssh -p 2222 user@hostYou should now be able to access the guest Linux SSH server via the forwarded port.
In this article, we have discussed how to permanently forward a specific port for remote access to a QEMU guest Linux on a host machine. The process involves using the -redir option in QEMU and modifying the QEMU startup script to make the configuration persistent across reboots.