After each shutdown and startup, WSL automatically changes the IP address, which is not friendly for remote programming.
The following steps are for automatically changing the hosts mapping in the Ubuntu 20.04 system in WSL:
-
Copy the following content to /etc/profile or ~/.bashrc:
ipaddr=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') sed -i '/wslhost/d' /mnt/c/Windows/System32/drivers/etc/hosts echo "$ipaddr wslhost" >> /mnt/c/Windows/System32/drivers/etc/hosts
If you reopen Ubuntu and encounter a permission deny prompt, find the hosts file in Windows, right-click, go to Properties, Security, and grant user permissions.
-
I also found that SSH is not automatically enabled by default. Execute the following command to set up automatic startup of the SSH service:
ln -fs /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service
-
Edit vim /etc/rc.local and add the following:
#!/bin/bash service ssh start exit 0
-
Set permissions:
chmod 755 /etc/rc.local
The only additional requirement is to open WSL with administrator privileges each time, otherwise, an error will occur.
-
In applications that require SSH remote access, use "wslhost" instead of the original IP address.