参考:
https://zhuanlan.zhihu.com/p/515068209
============================
Wsl Ubuntu的IP地址会随着宿主机Windows的重启而更换IP,为此会对远程ssh连接造成一定的麻烦,为此考虑对其设置固定IP。
给出windows宿主机上的命令操作:
wsl.bat 文件,内容如下,运行该脚本后 WSL Ubuntu Ip: 172.18.54.10, Windows 宿主机IP:172.18.54.1
@ECHO OFF
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c ""%~s0"" ::","","runas",1)(window.close)&&exit
setlocal enabledelayedexpansion
wsl --shutdown ubuntu
wsl -u root service ssh start
if !errorlevel! equ 0 (
wsl -u root ip addr | findstr "172.18.54.10" > nul
if !errorlevel! equ 0 (
echo wsl ip has set: 172.18.54.10
) else (
wsl -u root ip addr add 172.18.54.10/16 broadcast 172.18.54.0 dev eth0 label eth0:1
echo set wsl ip success: 172.18.54.10
)
ipconfig | findstr "172.18.54.1" > nul
if !errorlevel! equ 0 (
echo windows ip has set: 172.18.54.1
) else (
netsh interface ip add address "vEthernet (WSL)" 172.18.54.1 255.255.0.0
echo set windows ip success: 172.18.54.1
)
)
ping 172.18.54.10
pause
---------------------------------------------------------------
资料2:
https://zhuanlan.zhihu.com/p/515068209
给出的bat命令:(设置WSL ubuntu固定IP为192.168.120.181,宿主windows额外IP为192.168.120.100)
@echo off
setlocal enabledelayedexpansion
::不管三七二十一先停掉可能在跑的wsl实例
wsl --shutdown ubuntu
::重新拉起来,并且用root的身份,启动ssh服务和docker服务
wsl -u root service ssh start
wsl -u root service docker start | findstr "Starting Docker" > nul
if !errorlevel! equ 0 (
echo docker start success
:: 看看我要的IP在不在
wsl -u root ip addr | findstr "192.168.120.181" > nul
if !errorlevel! equ 0 (
echo wsl ip has set
) else (
::不在的话给安排上
wsl -u root ip addr add 192.168.120.181/24 broadcast 192.168.120.0 dev eth0 label eth0:1
echo set wsl ip success: 192.168.120.181
)
::windows作为wsl的宿主,在wsl的固定IP的同一网段也给安排另外一个IP
ipconfig | findstr "192.168.120.100" > nul
if !errorlevel! equ 0 (
echo windows ip has set
) else (
netsh interface ip add address "vEthernet (WSL)" 192.168.120.100 255.255.255.0
echo set windows ip success: 192.168.120.100
)
)
pause
=====================================