当前 Win10 用户添加修改 hosts 文件的权限
-
打开C:\Windows\System32\drivers\etc文件夹找到hosts文件,右键选择属性,找到安全选项卡;
-
点击编辑找到当前用户组,为其添加完全控制权限;
-
点击确定,在弹出的提示框中选择是;
-
此时当前用户应该可以直接修改 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查看