WSL2 Static IP

I’m using WSL2 with Debian.

Create vbs script with the following data and then add this script to startup by Windows Task scheduler.

Set objShell = CreateObject ("Wscript.Shell") 

objShell.Run "wsl.exe -d Debian sudo ip route del default", 0, true
objShell.Run "wsl.exe -d Debian sudo ip addr flush dev eth0", 0, true

objShell.Run "wsl.exe -d Debian sudo ip address add 100.127.255.2/24 dev eth0", 0, true
objShell.Run "wsl.exe -d Debian sudo ip route add default via 100.127.255.1", 0, true

objShell.Run "powershell.exe -Command ""Remove-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetAdapter -Name 'vEthernet (WSL)' | Select-Object -ExpandProperty InterfaceIndex) -Confirm:$false""", 0, true
objShell.Run "powershell.exe -Command ""New-NetIPAddress -IPAddress 100.127.255.1 -PrefixLength 24 -InterfaceIndex $(Get-NetAdapter -Name 'vEthernet (WSL)' | Select-Object -ExpandProperty InterfaceIndex)""", 0, true
objShell.Run "powershell.exe -Command ""Get-NetNat 'WSLNat' | Remove-NetNat -Confirm:$false""", 0, true
objShell.Run "powershell.exe -Command ""New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 100.127.255.0/24""", 0, true
objShell.Run "powershell.exe -Command ""Get-NetFirewallRule -DisplayName 'WSL' | Remove-NetFirewallRule -Confirm:$false""", 0, true
objShell.Run "powershell.exe -Command ""New-NetFirewallRule -DisplayName 'WSL' -Direction Inbound -InterfaceAlias 'vEthernet (WSL)' -Action Allow""", 0, true
objShell.Run "powershell.exe -Command ""New-NetFirewallRule -DisplayName 'WSL' -Direction Outbound -InterfaceAlias 'vEthernet (WSL)' -Action Allow""", 0, true

WScript.Quit

My task configuration:

General tab
Triggers tab
Actions tab
#!/usr/bin/env bash
GWADDR="100.127.255.1"
IPADDR="100.127.255.2"
CURGW=$(ip route show default | awk '{print $3}')

NSCONF="/etc/resolv.conf"
NSADDR="100.127.255.1"
CURNS=$(cat /etc/resolv.conf 2>/dev/null | awk '{print $2}' )

if [[ $GWADDR != $CURGW ]]; then
    ip route del default
    ip addr flush dev eth0
    ip address add 100.127.255.2/24 dev eth0
    ip route add default via 100.127.255.1
fi

if [ ! -f $NSCONF ]; then
    echo "nameserver $NSADDR" > $NSCONF
elif [[ $NSADDR != $CURNS ]]; then
    echo "nameserver $NSADDR" > $NSCONF
fi

echo “sudo /usr/local/bin/network_wizard” >>~/.bashrc

Also you should add your user to run this script with su right without password:
echo “USERNAME ALL = NOPASSWD: /usr/local/bin/network_wizard” > /etc/sudoers.d/network_wizard
where USERNAME – your username