解决 Win10 Wsl2 IP 变化问题

当前 Win10 用户添加修改 hosts 文件的权限

  1. 打开C:\Windows\System32\drivers\etc文件夹找到hosts文件,右键选择属性,找到安全选项卡;

  2. 点击编辑找到当前用户组,为其添加完全控制权限;
    在这里插入图片描述
    在这里插入图片描述

  3. 点击确定,在弹出的提示框中选择是;

  4. 此时当前用户应该可以直接修改 hosts 文件了。

编写脚本

#!/usr/bin/bash

/etc/init.d/ssh start
/etc/init.d/docker start

# set wsl host for Windows
# win hosts file path
win_hosts_path="/mnt/c/Windows/System32/drivers/etc/hosts"
# 获取当前日期并赋值给变量
execution_date=$(date +"%Y-%m-%d %H:%M:%S")
# 为 wsl2 设置的域名
wsl_domain="wsl2"
# 网卡名称
wsl_netcard_name="eth0"
# 获取 wsl2 的 ip
wsl_ip=$(ifconfig $wsl_netcard_name | grep -w inet | awk '{print $2}')
# 判断是否已存在 wsl2 的域名,如果存在则修改,否则追加
if grep -wq "$wsl_domain" $win_hosts_path
then
    # 此处因为权限问题没有直接用 sed 修改 hosts 文件,.*表示匹配任意字符
    win_hosts=$(sed -s "s/.* $wsl_domain  .*/$wsl_ip $wsl_domain  # $execution_date/g" $win_hosts_path)
    echo "Windows系统中 wsl域名存在,重新设置映射"
    echo "$win_hosts" > $win_hosts_path
else
    echo "Windows系统中 wsl域名不存在,直接添加${wsl_ip} ${wsl_domain}"
    echo "$wsl_ip $wsl_domain  # $execution_date" >> $win_hosts_path
fi

# 为 wsl 设置 win host
wsl_hosts_path="/etc/hosts"
win_domain="win"
win_ip=$(cat /etc/resolv.conf | grep "nameserver" | awk '{print $2}')
if grep -wq "$win_domain" $wsl_hosts_path
then
    wsl_hosts=$(sed -s "s/.* $win_domain  .*/$win_ip $win_domain  # $execution_date/g" $wsl_hosts_path)
    echo "Linux系统中 windows域名存在,重新设置映射"
    echo $wsl_hosts > $wsl_hosts_path
else
    echo "Linux系统中 windows域名不存在,直接添加${win_ip} ${win_domain}"
    echo "$win_ip $win_domain  # $execution_date" >> $wsl_hosts_path
fi

开机启动配置

常规做法
通常在Linux中开机启动可以通过
1.编辑/etc/rc.loacl
2.在/etc/init.d/ 下添加启动脚本
3.配置systemd
但这几种方式在子系统中无法使用,我们可以通过Windows 间接的启动子系统中的服务。

设置可执行

sudo chmod +x /etc/init.sh

在Windows中创建脚本
在Windows下 输入快捷键 WIN+R 打开运行窗口
输入 shell:startup
打开Windows 启动脚本目录
在该目录下新建 linux-start.vbs
内容如下

Set ws = WScript.CreateObject("WScript.Shell")        
ws.run "wsl -d Ubuntu-18.04 -u root /etc/init.wsl"

上面脚本中的 wsl -d 后面的参数是你所安装的子系统的版本可以通过wsl -l查看

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值