Created
April 9, 2025 11:10
-
-
Save jimklimov/6fdd497a421b559904249ee050fd5298 to your computer and use it in GitHub Desktop.
WSL2 Linux VM networking init
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# https://superuser.com/questions/1582234/make-ip-address-of-wsl2-static/1808525#1808525 | |
# https://superuser.com/a/1723531/433945 | |
# Add to /etc/wsl.conf as boot/command="/root/network-start.sh" for autostart | |
# (C) 2023-2025 by Jim Klimov (and other SO/GH/blog authors) | |
# | |
# This script assigns a fixed IP to the VM, fixes up DNS, | |
# allows fixed port on host for SSH dial-back into the VM | |
# and starts the SSH server. | |
PATH="/mnt/c/WINDOWS/System32/WindowsPowerShell/v1.0:$PATH" | |
export PATH | |
# Fenced with a separate touch-file, an IP address might be not | |
# available when this first runs - allow reentry until success! | |
# Assumes first IP is the one generated by WSL anew for each VM boot. | |
AUTOIP="`hostname -I | awk '{print $1}'`" | |
if [ -n "$AUTOIP" ] && [ ! -f /dev/shm/network-initialized-fwd ] ; then | |
powershell.exe -Command "Start-Process netsh.exe -ArgumentList \"interface portproxy add v4tov4 listenport=22099 connectport=22 connectaddress=$AUTOIP\" -Verb RunAs" | |
# Consider similar forwards for X11, VNC, etc. | |
touch /dev/shm/network-initialized-fwd | |
fi | |
# (Optionally) shield the rest of such init (assuming SSHD listens | |
# on IP_ANY, so starting it once suffices) | |
[ -f /dev/shm/network-initialized ] && exit | |
# https://gist.github.com/wllmsash/1636b86eed45e4024fb9b7ecd25378ce | |
# Custom IP might work or not, based on whims of Windows firewall du-jour | |
( ip a | grep 172.22.48.99 ) || sudo /usr/sbin/ip addr add 172.22.48.99/255.255.240.0 dev eth0 | |
ps -ef | grep -v grep | grep sshd || sudo service ssh start | |
# I've also had problems resolving Internet DNS, so this settled in | |
# (also works if /etc/resolv.conf is a dangling symlink to non-existent | |
# dir below, by default). Specifically, my problem was having the | |
# resolver re-generated from Windows host settings, and not having | |
# VPN etc. access to the domain DNS server to actually resolve stuff. | |
# Per my notes, https://github.com/microsoft/WSL/issues/6977 might | |
# also help: /etc/wsl.conf => [network] => generateResolvConf=false | |
grep 8.8.8.8 /etc/resolv.conf || { | |
sudo mkdir -p /run/resolvconf/ && \ | |
echo 'nameserver 8.8.8.8' | sudo tee -a /etc/resolv.conf | |
} | |
if [ ! -f /dev/shm/network-initialized ]; then | |
touch /dev/shm/network-initialized | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment