# WSL2设置自动更改hosts映射

By [Hans](https://paragraph.com/@dr-ai) · 2022-01-03

---

每次关机开机后，WSL默认会自动更换IP地址，对于远程访问编程很不友好。

下面几步是自动更改wsl中Ubuntu20.04系统的hosts映射：

1.  将一下内容复制到/etc/profile或者~/.bashrc中；
    
        ipaddr=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}')
        sed '/wslhost/d' /mnt/c/Windows/System32/drivers/etc/hosts > /tmp/tmphosts
        cat /tmp/tmphosts > /mnt/c/Windows/System32/drivers/etc/hosts
        echo "$ipaddr wslhost" >> /mnt/c/Windows/System32/drivers/etc/hosts
        
    
    如果重新打开ubuntu，发现提示permission deny。在windows下找到hosts，右键，属性，安全，给user用户权限。
    
2.  我还发现ssh竟然也不是默认自动开启的，执行下面命令设置自动启动ssh服务；
    
        ln -fs /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service
        
    
    编辑 `vim /etc/rc.local`， 写入
    
        #!/bin/bash
        service ssh start
        exit 0
        
    
    设置权限
    
        chmod 755 /etc/rc.local
        
    
3.  唯一额外的要求是，每次开启wsl请使用管理员权限，否则会报错；
    
4.  在需要ssh远程访问的应用中，用wslhost替代原本的ip地址即可。

---

*Originally published on [Hans](https://paragraph.com/@dr-ai/wsl2-hosts)*
