解决 WSL2 重启后 IP 变化的问题


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#! /bin/bash

### BEGIN INIT INFO
# Provides:          hybors.com
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Output the IP of wsl2 to the host
# Description:       When wsl2 starts, output the IP address to the hosts file of the host, the entry
#  format is "xxx.xxx.xxx.xxx wsl2-distro-name.wsl", and delete the entries that no longer exist
### END INIT INFO

# Enter the path where the hosts file is located
cd /mnt/c/Windows/System32/drivers/etc/

# check hosts permission
ls -l hosts | grep "^-rw.rw.rw."
result=$?
if [ ${result} == 1 ]
then
  echo "[error] Please add read and write permissions to hosts for the current user in the Windows system !"
  exit 1
fi

# check package "iproute2"
apt list iproute2 | grep "installed"
result=$?
if [ ${result} == 1 ]
then
  apt update
  apt install -y iproute2
fi

# get wsl distro's name and ip
# WSL_DISTRO_NAME is a built-in variable
host_name="${WSL_DISTRO_NAME}.wsl"
ip=$(ip a show eth0 | grep "inet " | awk '{print $2}' | awk -F "/" '{print $1}')

# check hosts's content
cat hosts | grep ${host_name}
result=$?
if [ ${result} == 1 ] # add a new record
then
  echo ${ip} ${host_name} >> hosts
else # modify an existing record
  cat hosts | sed -r "s/^[0-9.]+\s+${host_name}/${ip} ${host_name}/" > hosts
fi

# get all wsl distro names
result=$(wsl.exe -l -q)

# get all host-names ending in "wsl"
for i in `sed -r -n "s/^[0-9.]+\s//p" hosts | sed -r -n "s/\.wsl$//p"`
do
  # If the host-name is not in the existing distros, delete
  if ! [[ "${result}" =~ "$i" ]]
  then
    cat hosts | sed -r "/$i/d" > hosts
  fi
done
exit 0

保存到/etc/init.d中,文件名wsl2-hosts,开机启动:update-rc.d wsl2-hosts defaults 99