Bash/Powershell – Killing an SSH Tunnel Running on a Specific Port

On Windows – I use Git Bash and my custom bash profile to create “quality of life” commands for various use cases.

Today I had need to be able to kill an SSH Tunnel Process running on a specific port.

What made this tricky is that I needed to be able to use Powershell Commands via Git Bash (which I know is excessive, but I like things the way I like them)

PROCESS_TO_KILL="ssh.exe"
PROCESS_TO_KILL_POWERSHELL_EXPRESSION="\"name = '$PROCESS_TO_KILL'\""
PORT_TO_KILL="1993"
PORT_TO_KILL_POWERSHELL_EXPRESSION="'*$PORT_TO_KILL*'"

echo "[INFO] Listing Active SSH Tunnels..."
powershell.exe -command "Get-WmiObject Win32_Process -Filter $PROCESS_TO_KILL_POWERSHELL_EXPRESSION"

echo "[INFO] Filtering down to $PORT_TO_KILL..."
powershell.exe -command "Get-WmiObject Win32_Process -Filter $PROCESS_TO_KILL_POWERSHELL_EXPRESSION | where {\$_.CommandLine -like $PORT_TO_KILL_POWERSHELL_EXPRESSION }"

echo "[INFO] Killing Found SSH Tunnels..."
powershell.exe -command "Get-WmiObject Win32_Process -Filter $PROCESS_TO_KILL_POWERSHELL_EXPRESSION | where {\$_.CommandLine -like $PORT_TO_KILL_POWERSHELL_EXPRESSION } | ForEach-Object { taskkill /f /pid \$_.ProcessId }"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s