Keep Your SSH Connection Alive with Auto-SSH and Screen on Ubuntu Server

Abstract: Resolve dropped SSH connections and lost background processes on Ubuntu by using Auto-SSH for automatic reconnection and Screen for session persistence.

Created: 2026-10-04 by
Use Auto-SSH to automatically restart SSH sessions when they drop, and Screen to detach from long-running processes so you can safely close your local terminal without interrupting server tasks. This combination ensures that critical background jobs continue running even if your internet connection becomes unstable or your laptop goes to sleep.

Why Standard SSH Connections Fail

Standard SSH connections are fragile when dealing with poor internet connectivity, NAT timeouts, or mobile networks. When a network interruption occurs, the TCP session is terminated, killing any foreground processes attached to that terminal. While you might attempt to use tools like nohup or & to run commands in the background, these methods do not provide an interactive shell if you need to monitor progress or send signals later. Furthermore, if the connection drops entirely, you lose access to the process control until you manually reconnect, which may be impossible if the service itself crashed during the disconnect.

Installing the Required Tools

Before configuring persistence, you must ensure both autossh and screen are installed on your Ubuntu Server. These packages are available in the default repositories for most Ubuntu versions. Open a terminal and run the following command to install them:
sudo apt update
sudo apt install autossh screen
Once installed, verify the installations by checking their versions. Running autossh -V should display the version number, confirming that the auto-restart daemon is ready. Similarly, screen --version confirms the multiplexer is available. If either command fails, check your repository sources or ensure you have administrative privileges via sudo.

Configuring Auto-SSH for Automatic Reconnection

Auto-SSH works by monitoring the SSH connection and restarting it if it detects a failure. It uses a secondary "monitor" port to check the health of the primary SSH tunnel. To set this up, you need to create a wrapper script or configure your shell profile to launch Auto-SSH instead of standard SSH. Create a new file named ~/ssh-autoreconnect.sh using a text editor like nano:
nano ~/ssh-autoreconnect.sh
Add the following content to the file. Replace username with your actual Linux username and server_ip with the IP address of your Ubuntu server. The -M 0 flag tells Auto-SSH to use a TCP ping method rather than creating a dedicated monitor port, which is useful if firewalls block additional ports.
#!/bin/bash
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N username@server_ip
Make the script executable by running:
chmod +x ~/ssh-autoreconnect.sh
The options ServerAliveInterval and ServerAliveCountMax are crucial. They instruct the SSH client to send a keep-alive packet every 30 seconds. If three consecutive packets fail to receive a response, Auto-SSH assumes the connection is dead and initiates a restart. This proactive monitoring prevents long periods of silence that often lead to dropped connections. For deeper insights into troubleshooting initial connection failures, see our guide on Troubleshooting SSH Connection Issues on a Fresh Install of Ubuntu Server 23.10 on a Raspberry Pi.

Using Screen for Session Persistence

While Auto-SSH keeps the pipe open, screen allows you to detach from active programs. This means you can start a long compilation, a data transfer, or a web server, detach from the session, and close your laptop lid. The process continues running on the server. When you connect via Auto-SSH, immediately start a new screen session by typing:
screen -S mysession
This creates a session named mysession. Inside this environment, you can run any command as usual. To detach from the session without stopping the processes inside it, press Ctrl+A followed by D. You will return to your normal shell prompt, but the screen session remains active on the server. If your internet cuts out, Auto-SSH will reconnect you. Once reconnected, you can reattach to your previous work by running:
screen -r mysession
If multiple sessions are active, you may need to specify the session name or ID. For more information on managing remote sessions effectively, consider reading about Permission denied when trying to SSH into CISCO virtual router, which covers broader authentication contexts.

Automating the Setup on Boot

To ensure Auto-SSH starts automatically when your machine boots, you can add the script to your crontab. Edit your crontab with:
crontab -e
Add the following line at the end of the file to run the script at startup:
@reboot /home/username/ssh-autoreconnect.sh
Replace /home/username/ with your actual home directory path. This ensures that even after a reboot, your persistent connection strategy is restored immediately. Note that if you use key-based authentication, ensure your private keys are accessible and not password-protected, as automated scripts cannot interactively enter passwords.

Troubleshooting Common Issues

If Auto-SSH fails to reconnect, check the system logs using journalctl -u ssh or review the output of your script. Ensure that the firewall on the server allows inbound SSH traffic on port 22. Additionally, verify that your local machine has outbound access to the server. If you encounter key exchange errors, refer to our article on Troubleshooting kex_exchange_identification Error in Linux SSH Connection to resolve protocol mismatches. Screen sessions can also accumulate if not cleaned up. Use screen -ls to list active sessions. To remove a detached session that is no longer needed, use screen -X -S [session_id] quit. This prevents clutter and potential confusion when reattaching later.

Frequently Asked Questions

Can I use tmux instead of Screen?

Yes, tmux is a modern alternative to screen with better copy-and-paste capabilities and window splitting features. However, screen is pre-installed on many minimal Ubuntu servers, making it a zero-dependency choice for quick setups.

Does Auto-SSH consume significant bandwidth?

No, Auto-SSH only sends small keep-alive packets at intervals defined by ServerAliveInterval. These packets are negligible in size and typically occur every 30 seconds, adding almost no overhead to your connection.

What happens if my server reboots unexpectedly?

If the server reboots, the SSH service will restart, and Auto-SSH will detect the disconnection and reconnect once the network is available. Your screen sessions will be lost unless they were configured to survive across reboots, which requires additional systemd service configuration.

Is it safe to run Auto-SSH over public Wi-Fi?

Yes, provided you use strong encryption and key-based authentication. Auto-SSH does not change the security of the SSH protocol itself; it merely manages the connection lifecycle. Always ensure your SSH server is hardened against brute-force attacks.

How do I stop a runaway process in Screen?

Reattach to the screen session using screen -r, locate the process causing issues, and terminate it using standard Linux commands like kill or Ctrl+C. If the process ignores signals, you may need to kill it by its PID from a separate SSH session.

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