Correct Way to End SSH Tunnel

Abstract: Resolve orphaned SSH tunnel ports on macOS by identifying the process ID with lsof and terminating it gracefully using kill -TERM.

Created: 2026-09-16 by

The correct way to end an SSH tunnel on macOS using Zsh is to terminate the background process responsible for port forwarding. You can achieve this by identifying the process ID (PID) associated with the SSH session and sending a termination signal, ensuring that local ports are released cleanly without leaving orphaned connections.

Identifying Active SSH Tunnels

Before attempting to close a tunnel, it is essential to verify which processes are currently holding open your local ports. macOS manages network sockets through specific processes, and SSH tunnels create dedicated listening endpoints on your localhost interface. If you do not know the exact PID, you must first locate it. Open your terminal application running Zsh and use the lsof command to list open files and network connections. The syntax requires specifying the TCP protocol and the local address. For example, if your tunnel is forwarding local port 8080 to a remote server, you would run:
lsof -iTCP -sTCP:LISTEN -P | grep ssh
This command filters the output to show only TCP listeners and pipes the result through grep to isolate lines containing "ssh". Look for entries where the NAME column shows your local IP address and port (e.g., 127.0.0.1:8080). The second column in the output represents the PID of the process. Note this number down, as you will need it in the next step. If multiple tunnels are active, you may see several entries. Ensure you match the PID to the correct local port to avoid terminating unrelated SSH sessions. This diagnostic step is crucial because blindly killing all SSH processes could disconnect other active work sessions.

Terminating the Process Gracefully

Once you have identified the correct PID from the lsof output, the standard approach is to send a termination signal. The most common method is using the kill command with the -TERM signal, which allows the process to clean up resources before exiting. Run the following command in your Zsh terminal, replacing <PID> with the actual number you noted earlier:
kill -TERM <PID>
The -TERM signal gives the SSH client a chance to close the connection to the remote host gracefully. It sends a request to stop forwarding data and then exits. This is preferred over -KILL because it ensures that any pending data packets are flushed and the remote side knows the connection has been closed properly. After executing the kill command, wait a few seconds. You can verify that the tunnel is closed by running the lsof command again. The entry for your local port should no longer appear in the list. If the port is still listed, the process may be stuck in a zombie state or refusing to terminate.

Handling Stubborn Processes

In some cases, the SSH process may not respond to the -TERM signal immediately. This can happen if the network connection is unstable or if the remote server is unresponsive. If the tunnel persists after waiting ten seconds, you may need to escalate the signal strength. Use the -INT signal to simulate pressing Ctrl+C in the terminal. This often forces the SSH client to abort the current operation more aggressively than -TERM.
kill -INT <PID>
If even this fails, the last resort is the -KILL signal (signal 9). This command forcefully terminates the process without allowing it to perform cleanup routines. Use this only when necessary, as it may leave temporary socket states in limbo until the OS garbage collects them.
kill -9 <PID>
Forcing a kill can sometimes result in error messages regarding broken pipes or connection resets, but it guarantees the PID is removed from the process table. After using -KILL, check your local ports again to ensure they are free.

Preventing Orphaned Connections

To avoid the need for manual intervention in the future, consider using SSH options that manage tunnel lifecycles automatically. When creating a tunnel, you can specify the -f flag to put SSH into the background just before execution, combined with -N to indicate that no remote commands will be executed. This setup is ideal for pure port forwarding.
ssh -f -N -L 8080:localhost:3000 user@remote-server
While this makes starting the tunnel easier, it does not inherently solve the closing problem. However, combining this with a wrapper script or using tools like autossh can help monitor the connection health. If the connection drops, these tools can restart the tunnel automatically. Additionally, ensure your SSH configuration file (~/.ssh/config) does not have aggressive keepalive settings that might mask disconnection issues. Sometimes, tuning ServerAliveInterval helps detect dead connections faster, allowing you to terminate them sooner rather than later. For users encountering permission errors while trying to manage these processes, refer to our guide on Fixing ZSH Permission Error on MacOS to resolve access issues. Similarly, if you are troubleshooting broader connectivity issues related to jump servers, check out How to Manually Close SSH Ports/Bindings on a Mac 15.1 System for Troubleshooting Jump Server Connections.

Frequently Asked Questions

Why does my local port remain occupied after killing the SSH process?

This usually occurs because the operating system holds the socket in a TIME_WAIT state for a short period to ensure all delayed packets are handled. You can force immediate release by restarting the network services or waiting a minute for the kernel to clear the state. Using SO_REUSEADDR in custom scripts can also bypass this, but standard SSH clients do not support this flag directly.

Can I close an SSH tunnel without knowing the PID?

No, you must identify the specific process ID to target the correct tunnel. While you can use pkill to kill all processes matching a name, this is dangerous as it may terminate other unrelated SSH sessions. Always use lsof to map the local port to its unique PID before taking action.

What is the difference between kill -TERM and kill -KILL?

-TERM allows the process to catch the signal and perform cleanup tasks, such as closing database connections or flushing logs. -KILL (signal 9) cannot be caught or ignored by the process, resulting in immediate termination. Use -TERM first to preserve data integrity, and reserve -KILL for unresponsive processes.

Does using the -N flag affect how I close the tunnel?

The -N flag tells SSH not to execute a remote command, making it suitable for pure tunneling. It does not change the termination method; you still need to kill the PID. However, since no interactive shell is spawned, there is less risk of accidentally interrupting a working session if you misidentify the PID.

How do I prevent SSH tunnels from being killed by system sleep?

macOS may suspend network activity during sleep, causing the SSH connection to drop. To mitigate this, disable "Put hard disks to sleep" in Energy Saver settings and use a utility like caffeinate to keep the system awake while the tunnel is active. Alternatively, configure ServerAliveInterval in your SSH config to detect dropped connections quickly.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More