WSL2固定Host 连接

说明

WSL2 启动时会自动变换IP,IP地址不可固定。使用Localhost有时候可以连接上去,有时候连接不上去。
现在设置一个固定的host来配置WSL2

1. 配置Linux 获取IP启动脚本

cd /etc
touch initWsl.bash
chmod 775 initWsl.bash
vim initWsl.bash

initWsl.bash

#! /bin/sh

# 启动对应服务
service ssh ${1}
service docker ${1}

# 设置本地Wsl2域名,默认为wsl2host
ipaddr=$(ip -4 addr show dev eth0 | egrep 'inet ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})' | awk '{print $2}' | awk -F/ '{print $1}')
hostName='wsl2host'
sed -i '/wsl2host/d' /mnt/c/Windows/System32/drivers/etc/hosts
echo "${ipaddr} ${hostName}" >> /mnt/c/Windows/System32/drivers/etc/hosts

sed -i '/wsl2host/d' /etc/hosts
echo "${ipaddr} ${hostName}" >> /etc/hosts
./initWsl.bash start

2. 配置Windows 启动运行脚本

  1. 进入 C:\Users\hanli\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
  2. 创建Ubuntu.vbs
Set ws = CreateObject("Wscript.Shell")
ws.run "wsl -d Ubuntu -u root /etc/initWsl.bash start", vbhide
  1. 执行Ubuntu.vbs

你可能感兴趣的:(WSL,ubuntu,linux,bash)