Skip to content

Instantly share code, notes, and snippets.

@lseongjoo
Last active July 13, 2024 23:06
Show Gist options
  • Save lseongjoo/4be8a592b3685ee1673d708bf086322c to your computer and use it in GitHub Desktop.
Save lseongjoo/4be8a592b3685ee1673d708bf086322c to your computer and use it in GitHub Desktop.
WSL SSH Server Setup
# Function to get WSL IP address
function Get-WSLIP {
return (wsl hostname -I).Trim()
}
# Function to add port forwarding rule
function Add-PortForwardingRule {
param (
[int]$HostPort = 22,
[int]$WSLPort = 22,
[string]$ListenAddress = "0.0.0.0"
)
$WSL_IP = Get-WSLIP
netsh interface portproxy add v4tov4 listenport=$HostPort listenaddress=$ListenAddress connectport=$WSLPort connectaddress=$WSL_IP
}
# Function to delete port forwarding rule
function Remove-PortForwardingRule {
param (
[int]$HostPort = 22,
[string]$ListenAddress = "0.0.0.0"
)
netsh interface portproxy delete v4tov4 listenport=$HostPort listenaddress=$ListenAddress
}
# Function to ensure firewall rule
function Ensure-FirewallRule {
param (
[int]$HostPort = 22,
[string]$RuleName = "AllowSSH-$HostPort",
[string]$DisplayName = "Allow SSH on port $HostPort"
)
$rule = Get-NetFirewallRule -Name $RuleName -ErrorAction SilentlyContinue
if (-not $rule) {
New-NetFirewallRule -Name $RuleName -DisplayName $DisplayName -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort $HostPort
} else {
Write-Host "Firewall rule $RuleName already exists."
}
}
# Function to list port forwarding rules
function List-PortForwardingRules {
netsh interface portproxy show all
}
# Main script execution
param (
[string]$Action = "add", # Default action is "add", can be "add" or "remove"
[int]$HostPort = 22 # Default host port is 22
)
if ($Action -eq "add") {
Add-PortForwardingRule -HostPort $HostPort
Ensure-FirewallRule -HostPort $HostPort
Write-Host "Port forwarding rule added and firewall rule ensured for port $HostPort."
} elseif ($Action -eq "remove") {
Remove-PortForwardingRule -HostPort $HostPort
Write-Host "Port forwarding rule removed for port $HostPort."
} else {
Write-Host "Invalid action. Use 'add' or 'remove'."
}
# List current port forwarding rules
List-PortForwardingRules
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment