# WSL2设置自动更改hosts映射 **Published by:** [Hans](https://paragraph.com/@dr-ai/) **Published on:** 2022-01-03 **URL:** https://paragraph.com/@dr-ai/wsl2-hosts ## Content 每次关机开机后,WSL默认会自动更换IP地址,对于远程访问编程很不友好。 下面几步是自动更改wsl中Ubuntu20.04系统的hosts映射:将一下内容复制到/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用户权限。我还发现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 唯一额外的要求是,每次开启wsl请使用管理员权限,否则会报错;在需要ssh远程访问的应用中,用wslhost替代原本的ip地址即可。 ## Publication Information - [Hans](https://paragraph.com/@dr-ai/): Publication homepage - [All Posts](https://paragraph.com/@dr-ai/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@dr-ai): Subscribe to updates - [Twitter](https://twitter.com/hans_rss3): Follow on Twitter