Make a SecureCRT connection to connect to WSL2 without having to change the IP every time

securecrtsshwsl2

Is there a way to make the WSL2 ip static? I read about it and I was told there was no way to make the IP static, then is there a way to make a SecureCRT connection to WSL2 without having to change the IP adddress in the configs so I don't have to re-enter the ip every time?

Best Answer

The solution to not redo again everything with a new IP address is found in the post
WSL 2 NIC Bridge mode #4150.

Unfortunately, the solution is only to relegate the work to a script that is run automatically after each login.

Description of the problem:

The work around is to forward the TCP ports of WSL 2 services to the host OS.
The virtual adapter on WSL 2 machine changes its IP address during reboot which makes it tough to implement a run once solution.
Also a side note, windows firewall will block the redirected port.

The solution is to write a PowerShell script that does :

  • Get Ip Address of WSL 2 machine
  • Remove previous port forwarding rules
  • Add port Forwarding rules
  • Remove previously added firewall rules
  • Add new Firewall Rules

The script also removes unwanted firewall rules.
Here is the script as copied from that post:

$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';

if( $found ){
  $remoteport = $matches[0];
} else{
  echo "The Script Exited, the ip address of WSL 2 cannot be found";
  exit;
}

#[Ports]

#All the ports you want to forward separated by coma
$ports=@(80,443,10000,3000,5000);


#[Static ip]
#You can change the addr to your ip config to listen to a specific address
$addr='0.0.0.0';
$ports_a = $ports -join ",";


#Remove Firewall Exception Rules
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";

#adding Exception Rules for inbound and outbound Rules
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";

for( $i = 0; $i -lt $ports.length; $i++ ){
  $port = $ports[$i];
  iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
  iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}

You need to schedule the script to run after login, as follows:

Go to search, search for task scheduler. In the actions menu on the right, click on create task.
Enter Name, go to triggers tab. Create a new trigger, with a begin task as you login, set delay to 10s.
Go to the actions and add the script. If you are using Laptop, go to settings and enable run on power.

Related Question