wsl2 使用体验
优点1. docker 正常工作
wsl2其实是一个完整的虚拟机, docker 在里面工作正常。
坑1. wsl ip 不固定
wsl 重启后, ip 变动。
这个坑也有人遇到:[WSL 2] NIC Bridge mode 🖧 (Has Workaround🔨).
研究微软的说明,才发现这个是feature: User Experience Changes Between WSL 1 and WSL 2.
解决思路,win10通过域名wsl.wsl
访问wsl; wsl内部负责将ip写入win10的hosts文件中。使用python实现这个逻辑:
import subprocess
import re
def get_address_info():
s1 = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
out_string = s1.stdout.read().decode("utf-8")
# address name
address_name_list = []
for line in out_string.split("\n"):
if line and line.find("flags=") > -1:
address_name_list.append(line.split(":")[0])
# ip
re_address = re.compile(r'(?<=inet )[\d\.]{3,20}?(?= netmask)')
all_address = re_address.findall(out_string)
#
assert len(address_name_list) == len(all_address)
return {address_name_list[i]: ip for i, ip in enumerate(all_address)}
def get_wsl_ip() -> str:
add_info = get_address_info()
return add_info["eth0"]
def update_wsl_ip(new_ip: str):
""" update ip """
host_file = "/mnt/c/Windows/System32/drivers/etc/hosts"
with open(host_file, "r") as f:
lines = f.readlines()
change = False
found = False
for i, line in enumerate(lines):
if len(line) > 5 and line.find("wsl.wsl") > -1:
found = True
if line.find(new_ip) > -1:
print("not change: ip is same!")
else:
lines[i] = "{}\twsl.wsl\n".format(new_ip)
print("change: ip is different!")
change = True
break
if not found:
lines.append("{}\twsl.wsl\n".format(new_ip))
print("change: ip not exists!")
change = True
if lines and change:
with open(host_file, "w") as f:
f.write("".join(lines))
if __name__ == '__main__':
update_wsl_ip(new_ip=get_wsl_ip())
wsl2 中 设置定时任务:
*/15 * * * * cat ~/.ssh/sss.dat | sudo -S python3 ~/refresh_hosts.py