hans

hans

【WSL】Setting up automatic host mapping in WSL2


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:

  1. 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.

  2. 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
    
  3. Edit vim /etc/rc.local and add the following:

    #!/bin/bash
    service ssh start
    exit 0
    
  4. 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.

  5. In applications that require SSH remote access, use "wslhost" instead of the original IP address.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.