Skip to content

Instantly share code, notes, and snippets.

@goffinf
Last active September 19, 2022 00:30
Show Gist options
  • Save goffinf/b545abdb865e90297a36b89ea1398681 to your computer and use it in GitHub Desktop.
Save goffinf/b545abdb865e90297a36b89ea1398681 to your computer and use it in GitHub Desktop.
Powershell scripts to update the Windows hosts file to match the IP allocated to WSL2 and to create Inbound and optionally outbound firewall rules to allow externals clients to access ports exposed by WSL (e.g. k8s api). Create a desktop shortcut to configure-wsl.ps1
Param(
[string]$distro = "ADD-YOUR-DEFAULT-WLS2-DISTRO-NAME-HERE"
)
filter timestamp {"$(Get-Date -Format "yyyy/MM/dd HH:mm:ss") $_"}
$runningDirectory = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
Write-Output "`n"
Write-Output "Starting host file processing for WSL`n" | timestamp
Write-Output "Running script in: $runningDirectory`n" | timestamp
Write-Output "Retrieving the IP address from WSL distro: $distro`n" | timestamp
$wslIpAddr = wsl -d $distro -- ip addr
Write-Output "Assuming a match pattern of 172.* or 192.*`n" | timestamp
$match = [System.Text.RegularExpressions.Regex]::Match($wslIpAddr, "(?<ip>172\.[\d\.]*)\/")
$ip = $match.Groups["ip"]
if ([string]::IsNullOrWhiteSpace($ip) -or $ip.Length -eq 0) {
Write-Output "An IP address in the range 172.* was NOT FOUND. Trying 192 !`n"
$match = [System.Text.RegularExpressions.Regex]::Match($wslIpAddr, "(?<ip>192\.[\d\.]*)\/")
$ip = $match.Groups["ip"]
if ([string]::IsNullOrWhiteSpace($ip) -or $ip.Length -eq 0) {
Write-Output "An IP address in the range 192.* was NOT FOUND.`n" | timestamp
Write-Output "The IP address used by the WSL distro could not be detected ... open a teriminal to check the IP`n" | timestamp
pause
exit
}
}
Write-Output "The IP Address for WSL instances is: $ip`n" | timestamp
Start-Process -FilePath Powershell -Verb RunAs -ArgumentList '-File', "$runningDirectory\update-hosts.ps1", '-ip', $ip, $distro
Pause
Start-Process -FilePath Powershell -Verb RunAs -ArgumentList '-File', "$runningDirectory\wsl2-enable-lan-access.ps1", '-ip', $ip, $distro
#Requires -RunAsAdministrator
Param(
[string]$ip,
[string]$distro
)
filter timestamp {"$(Get-Date -Format "yyyy/MM/dd HH:mm:ss") $_"}
function GetHostsFileAsText {
$hostfile = Get-Content "c:\windows\system32\drivers\etc\hosts" -Encoding UTF8 -Raw
return $hostfile
}
function GetMatchedCount {
Param (
[string]$hostfile,
[string]$ipOctet1,
[string]$hostnamePrefix
)
$rx = [System.Text.RegularExpressions.Regex] "(?<ip>$ipOctet1\.[\d\.]*).*$hostnamePrefix"
$matches = $rx.Matches($hostfile).Count
return $matches
}
function UpdateHostfileText {
Param (
[string]$hostfile,
[string]$ipOctet1,
[string]$hostnamePrefix
)
$replaced = [System.Text.RegularExpressions.Regex]::Replace($hostfile, "(?<ip>$ipOctet1\.[\d\.]*).*$hostnamePrefix", "$ip $hostnamePrefix")
return $replaced
}
$hosts_file_backup_path = "c:\windows\system32\drivers\etc\hosts.backup"
$iam = whoami
Write-Output "`n"
Write-Output "Running with user $iam`n" | timestamp
Write-Output "Searching for matches in the Windows hosts file.`n" | timestamp
Write-Output "IMPORTANT NOTE:`n" | timestamp
Write-Output "---------------`n" | timestamp
Write-Output "All dns names MUST START WITH 'wsl2'`n" | timestamp
$hostfile = GetHostsFileAsText
# Backup current hosts file
Write-Output "Backing up current hosts file to $hosts_file_backup_path"
$hostfile | Set-Content -Path $hosts_file_backup_path
# Gather entries that match the ip pattern 172.* or 192.* AND have a host name that starts with wsl2
$matches172 = GetMatchedCount $hostfile "172" "wsl2"
$matched172 = $false
$matched192 = $false
if ( $matches172 -gt 0 ) {
Write-Output "$matches172 MATCHES to 172.*"
$matched172 = $true
} else {
$matches192 = GetMatchedCount $hostfile "192" "wsl2"
if ( $matches192 -gt 0 ) {
Write-Output "$matches192 MATCHES to 192.*"
$matched192 = $true
} else {
Write-Output "NO MATCHES TO EITHER 172.* OR 192.* FOUND - ABORTING !"
}
}
if ( $matched172 ) {
Write-Output "Replacing all 172.* wsl entries"
$replaced = UpdateHostfileText $hostfile "172" "wsl2"
} else {
if ( $matched192 ) {
Write-Output "Replacing all 192.* wsl entries"
$replaced = UpdateHostfileText $hostfile "192" "wsl2"
} else {
Write "No matches found - aborting !!!"
exit
}
}
Write-Output "NEW hosts file:`n`n" | timestamp
Write-Output "---------------------------REPLACED FILE ---------------------------"
Write-Output "replaced = $replaced"
#$updateHosts = Read-Host -Prompt "Do you want to proceed with the update to the Windows hosts file ? [y/n]"
#if ( $updateHosts -match "[yY]" ) {
Write-Output "Updating the Windows hosts file ...`n" | timestamp
Start-Sleep -Seconds 4
$replaced | Set-Content -Path "c:\windows\system32\drivers\etc\hosts"
#} else {
# Write-Output "Skipping the Windows hosts file update.`n" | timestamp
#}
#Pause
Write-Output "Running replacement for a SECOND time for DNS name: host.k3d.internal`n" | timestamp
$hostfile = GetHostsFileAsText
$matches172 = GetMatchedCount $hostfile "172" "host.k3d.internal"
$matched172 = $false
$matched192 = $false
if ( $matches172 -gt 0 ) {
Write-Output "$matches172 MATCHES to 172.*"
$matched172 = $true
} else {
$matches192 = GetMatchedCount $hostfile "192" "host.k3d.internal"
if ( $matches192 -gt 0 ) {
Write-Output "$matches192 MATCHES to 192.*"
$matched192 = $true
} else {
Write-Output "No matches to either 172.* OR 192.* found - aborting !"
}
}
if ( $matched172 ) {
Write-Output "Replacing all 172.* wsl entries"
$replaced = UpdateHostfileText $hostfile "172" "host.k3d.internal"
} else {
if ( $matched192 ) {
Write-Output "Replacing all 192.* wsl entries"
$replaced = UpdateHostfileText $hostfile "192" "host.k3d.internal"
} else {
Write "No matches found - aborting !!!"
exit
}
}
Write-Output "NEW hosts file:`n`n" | timestamp
Write-Output "---------------------------REPLACED FILE ---------------------------"
Write-Output $replaced
#$updateHosts = Read-Host -Prompt "Do you want to proceed with the update to the Windows hosts file ? [y/n]"
#if ( $updateHosts -match "[yY]" ) {
Write-Output "Updating the Windows hosts file ...`n" | timestamp
Start-Sleep -Seconds 4
$replaced | Set-Content -Path "c:\windows\system32\drivers\etc\hosts"
#} else {
# Write-Output "Skipping the Windows hosts file update.`n" | timestamp
#}
Write-Output "Terminating the distro ($distro) so that etc/hosts is updated"
wsl --terminate $distro
#Requires -RunAsAdministrator
Param(
[string]$ip,
[string]$distro
)
$docker_desktop_distro = 'docker-desktop'
filter timestamp {"$(Get-Date -Format "yyyy/MM/dd HH:mm:ss") $_"}
$iam = whoami
Write-Output "`n"
Write-Output "Running with user $iam`n" | timestamp
$runningDirectory = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
Write-Output "Running script in: $runningDirectory`n" | timestamp
Write-Output "`n"
Write-Output "The IP Address for WSL instances is: $ip`n" | timestamp
Write-Output "Setting $distro as default distro`n" | timestamp
wslconfig /setdefault $distro
#[Ports]
#All the ports you want to forward separated by coma
$ports=@(22,53,80,443,5000,5900,6443,8081,8443);
#[Static ip]
# Change the addr to a single ip to listen to a specific address
$addr='0.0.0.0';
$ports_a = $ports -join ",";
$firewall_Rule_Name = 'WSL2 Lan Access'
#Remove Firewall Exception Rules
Write-Output "Removing existing Windows firewall rule ($firewall_Rule_Name)`n" | timestamp
iex "Remove-NetFireWallRule -DisplayName '$firewall_Rule_Name' ";
#adding Exception Rules for inbound and outbound Rules
Write-Output "Adding new Windows firewall rule ($firewall_Rule_Name)`n" | timestamp
#iex "New-NetFireWallRule -DisplayName '$firewall_Rule_Name' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName '$firewall_Rule_Name' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
Write-Output "Removing portproxy port $port on $addr`n" | timestamp
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
Write-Output "Binding listenport $port for source host ip address $addr to target WSL ip address $ip`n" | timestamp
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$ip";
}
Write-Output "Re-setting $docker_desktop_distro as default distro`n" | timestamp
wslconfig /setdefault $docker_desktop_distro
Pause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment