I am running an SSH server within WSL2 on a WIN10 machine. To make that work I am using:
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=22 connectaddress=172.19.237.178 connectport=22
This works fine initially.
172.19.237.178
is the IP of the WSL2 VM.There is just one problem. I have the sshd set to run when the PC boots, and every time I boot the machine WSL2 has a different IP. Is there any way to configure WSL2 to use a static IP?
Edit: See this question for a workaround to determine the WSL machine’s IP.
Solution:
The IP address of a WSL2 machine cannot be made static, however it can be determined using wsl hostname -I
Based on this I was able to create the following powershell script that will start sshd on my WSL machine and route traffic to it.
wsl.exe sudo /etc/init.d/ssh start$wsl_ip = (wsl hostname -I).trim()Write-Host "WSL Machine IP: ""$wsl_ip"""netsh interface portproxy add v4tov4 listenport=22 connectport=22 connectaddress=$wsl_ip
I added the following to my sudoers file via visudo to avoid needing a password to start sshd
%sudo ALL=(ALL) NOPASSWD: /etc/init.d/ssh
Finally, from an administrative powershell terminal, I scheduled my script to run at startup
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:15Register-ScheduledJob -Trigger $trigger -FilePath C:route_ssh_to_wsl.ps1 -Name RouteSSHtoWSL