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.