Here are some ways to keep an SSH connection active:
- Configuring SSH Client:
You can configure your SSH client to keep the connection alive. This can be done by modifying the ~/.ssh/config file on your local machine. Here's an example:
Host*
TCPKeepAlive yes
ServerAliveInterval 30
ServerAliveCountMax 3
In this example, TCPKeepAlive yes enables TCP keepalive, ServerAliveInterval 30 sets the time (in seconds) between keepalive messages, and ServerAliveCountMax 3 sets the number of failed keepalive messages before giving up.
- Using Screen or Tmux:
Screen and Tmux are terminal multiplexers that allow you to create, manage, and switch between multiple terminal sessions. They can help keep your SSH sessions alive even when you disconnect from the server.
- Using
screen -d -mortmux new -s sessionname:
When you start a screen or tmux session, it runs in the background and keeps your SSH session active even if you disconnect from the server.
- Using
screen -rortmux attach:
To reattach to your screen or tmux session, use the screen -r or tmux attach command.
- Using
nohupcommand:
The nohup command allows you to run a command in the background and keep it running even after you disconnect from the server. However, this won't work for interactive shells.
nohup ssh user@server "command" &
Replace user@server with your username and server address, and command with the command you want to run.
Remember, these methods are for keeping your SSH session active, not for executing long-running tasks. For that, you should consider using a job scheduler or a task queue.
References: