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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值