How to Securely Log Out of SSH on Ubuntu

This article provides a straightforward guide on how to securely and cleanly terminate an active SSH session on Ubuntu Linux. You will learn the standard commands to close a session, keyboard shortcuts for quick disconnection, how to handle frozen or unresponsive SSH connections, and how to safely leave background tasks running before you log out.

Standard Methods to Log Out of SSH

When you are finished working on your remote Ubuntu server, you should always close the session to free up system resources and prevent unauthorized access. The most common and secure methods to do this include:

1. The exit Command

The simplest way to close your SSH session is by typing exit in the terminal and pressing Enter:

exit

This command safely terminates the shell session and closes the secure tunnel.

2. The logout Command

Alternatively, you can use the logout command, which functions identically to exit in a login shell:

logout

3. Keyboard Shortcut (Ctrl + D)

If you prefer using keyboard shortcuts, press Ctrl + D on your keyboard. This sends an EOF (End of File) marker to the shell, signaling it to close the session immediately.


How to Force Close a Frozen SSH Session

Sometimes, a network disruption or a hung process can cause your SSH terminal to freeze, making standard commands unresponsive. In this scenario, you can use an SSH escape sequence to force the connection to close:

  1. Press Enter (to ensure you are on a new line).
  2. Press the tilde key (~).
  3. Press the period key (.).

Your terminal will instantly terminate the connection and return you to your local prompt.


Running Long Tasks Securely Before Logging Out

If you log out of an SSH session while a process is running in the foreground, that process will be terminated. To securely log out without stopping your active tasks, use one of the following methods:

Terminal multiplexers like tmux allow you to run processes in a session that persists even after you disconnect.

  1. Start a new tmux session:

    tmux
  2. Run your command or script inside the tmux session.

  3. Detach from the session by pressing Ctrl + B, then D.

  4. You can now safely run exit to log out. The process will continue running in the background.

  5. To resume the session next time you log in, run:

    tmux attach

Using the nohup Command

If you do not have tmux installed, you can append nohup (no hangup) to the beginning of your command and run it in the background by adding & to the end:

nohup python3 script.py &

This diverts output to a file named nohup.out and prevents the process from closing when you log out of your SSH session.