How to Keep an SSH Connection Alive Without Changing Config Files?

0
9
Asked By CuriousCoder99 On

I'm running a Bash script that needs to wait for a user to finish a task in the GUI before proceeding. However, sometimes the user takes too long, and the SSH connection drops. I'm looking for a way to modify the script so that it pings the server or sends a command like "cat file" every 20 seconds to keep the connection active while waiting for user input with "read -r answer". Any suggestions on how to implement this?

4 Answers

Answered By TmuxEnthusiast On

If you often run into this issue, I highly recommend using tmux. It's like having another layer of bash. Start a tmux session with:
```
tmux new -t sessionname
```
If you get disconnected, you can reconnect to the server and reattach the tmux session with:
```
tmux attach -t sessionname
```
It's really stable and offers a lot of other features!

Answered By RemoteExpert34 On

Have you checked out mosh? It's designed for mobile SSH connections and can handle intermittent network connections better than standard SSH, which could be really useful in your case.

Answered By CodeWhisperer77 On

A neat trick is to start a background loop that sends a non-printing character every 20 seconds to keep the connection open. You can implement it like this:
```
while true; do sleep 20; echo -ne ""; done & HEARTBEAT_PID=$!
read -r answer
kill $HEARTBEAT_PID
```
This way, the connection should stay alive while waiting for the user's input.

Answered By HelpfulTechie22 On

You can use the SSH command with options to keep your connection alive without modifying any configuration files. Try this command:
```
ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=60 user@hostname
```
This sends an empty packet to the server every 60 seconds, which effectively keeps your connection alive for up to an hour. Adjust the timing as needed based on your server's specific requirements.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.