How to kill a specific active SSH session after a defined time interval – version 2
There are a few different ways you can kill an active SSH session after a defined time interval:
1. Use the timeout
command:
You can use the timeout
command to run a command with a time limit. For example, you can use the following command to kill an active SSH session after 60 seconds:
timeout 60 ssh username@hostname
2. Use the at
command:
The at
command allows you to schedule a command to be executed at a specified time in the future. For example, you can use the following command to kill an active SSH session after 60 seconds
echo "pkill ssh" | at now + 1 minute
3. Use a script:
You can also write a script that checks the duration of an active SSH session and kills it if it exceeds a certain time limit. Here’s an example of a Bash script that does this:
#!/bin/bash
# Set the time limit (in seconds)
time_limit=3600
# Get the PID of the SSH session
pid=$(pgrep ssh)
# Get the start time of the SSH session
start_time=$(ps -o etime= -p $pid)
# Calculate the elapsed time
elapsed_time=$(($(date +%s) - $(date -d "$start_time" +%s)))
# Check if the elapsed time is greater than the time limit
if [ $elapsed_time -gt $time_limit ]; then
# Kill the SSH session
kill $pid
fi
You can then set up a cron job to run this script periodically (e.g., every minute) to check for and kill any active SSH sessions that have exceeded the time limit.
I hope this helps!