#! /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