Prerequisites
- Basic understanding of Bash scripting
- Knowledge of
ssh
command - Familiarity with terminal commands
- Access to a Linux-based system
- Ensure OpenSSH is installed (if working with SSH sessions)
DID YOU KNOW?
SSH connections can be automatically terminated by the server after a defined period of inactivity. The Keep Alive script can extend these sessions significantly.
The Script
This Bash script will ping the server at regular intervals to keep the session alive. It uses the while
loop to execute the ping
command consistently.
#!/bin/bash
HOST="your.server.com"
INTERVAL=30 # seconds
while true; do
ping -c 1 $HOST >/dev/null 2>&1
sleep $INTERVAL
done
Step-by-Step Explanation
NOTE!
Make sure to replace your.server.com
with the actual address of the server you wish to keep alive.
Let’s look at how the provided script works step by step:
- Defining Variables: The script starts by defining the
HOST
variable to hold the server’s address and theINTERVAL
variable for sleep duration. - Loop Execution: The
while true
statement creates an infinite loop, which continuously executes the commands inside. - Ping Command: The
ping
command sends a single packet to the definedHOST
. Output is silenced by redirecting it to/dev/null
. - Sleep Command: The
sleep
command pauses the loop for the duration set inINTERVAL
, avoiding overloading the server with requests.
How to Run the Script
To execute the Keep Alive Bash script, you’ll need to follow these steps:
- Create a new script file using a text editor, e.g.,
nano keep_alive.sh
. - Copy and paste the provided script into the new file.
- Make the script executable by running
chmod +x keep_alive.sh
. - Run the script with
./keep_alive.sh
.
Conclusion
The Keep Alive Bash script is a simple yet effective way to maintain your SSH connection active. With the ability to customize the timeout interval, you can adjust the script according to your network environment and personal needs.
FAQ
-
What happens if I stop the script?
The connection will no longer be kept alive, and you may be disconnected if there is no activity.
-
Can I change the ping command?
Yes, you can use other commands, but ensure they maintain the connection with the server.
-
Is it safe to run this script continuously?
Yes, but be mindful of the load it may cause on the server, especially if there are many active users.
-
What if the script doesn’t seem to work?
Check the server address and ensure that the server is reachable.
Troubleshooting
If you encounter issues running the Keep Alive script, consider the following common problems:
- Network Reachability: Ensure the server is online and reachable.
- Permissions Error: Verify that the script has the right permissions set (use
chmod +x
). - No Output or Response: Check if your firewall settings allow
ping
traffic.