Last active
April 26, 2024 20:12
-
-
Save crkrenn/55651ceb8a2843a8cc6e3f0520508742 to your computer and use it in GitHub Desktop.
auto-shutdown-for-server-with-bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# update history after every command | |
cat << 'EOF' >> ~/.bashrc | |
# If PROMPT_COMMAND already has commands | |
if [[ ! -z "$PROMPT_COMMAND" ]]; then | |
PROMPT_COMMAND="$PROMPT_COMMAND; history -a" | |
else | |
PROMPT_COMMAND="history -a" | |
fi | |
EOF | |
mkdir ~/bin | |
# Write shutdown Bash script to a file | |
SHUTDOWN_SCRIPT_NAME=${HOME}/bin/idle_shutdown_script.sh | |
cat <<EOF > ${SHUTDOWN_SCRIPT_NAME} | |
#!/bin/bash | |
# Set the idle time limit (30 minutes in seconds) | |
# IDLE_LIMIT=1800 | |
IDLE_LIMIT=600 | |
# Get the current time in seconds since the epoch | |
current_time=\$(date +%s) | |
# Function to get the last modification time of a file in seconds | |
get_modification_time() { | |
local file_path="\$1" | |
# Get the last modification time in seconds since the epoch | |
stat -c %Y "\$file_path" | |
} | |
# List of home directories (assuming /home for user directories) | |
cd /home | |
home_dirs=\$(ls) | |
# Assume all sessions are idle initially | |
all_idle=true | |
# Loop through home directories and check the last modification time of .bash_history | |
for home_dir in \$home_dirs; do | |
history_file="\$home_dir/.bash_history" | |
if [[ -f \$history_file ]]; then | |
last_modification=\$(get_modification_time "\$history_file") | |
# Calculate idle time | |
idle_time=\$((current_time - last_modification)) | |
if ((idle_time < IDLE_LIMIT)); then | |
all_idle=false # If any session is active within 30 minutes, set to false | |
fi | |
else | |
all_idle=false # If there's no .bash_history, assume not idle | |
fi | |
done | |
# If all sessions are idle for 30 minutes or more, shut down | |
if \$all_idle; then | |
sudo /usr/sbin/shutdown -h now | |
fi | |
EOF | |
chmod ugo+x $SHUTDOWN_SCRIPT_NAME | |
# Define the cron job to be added | |
NEW_CRON_JOB="* * * * * $SHUTDOWN_SCRIPT_NAME" | |
# Get the current crontab | |
CURRENT_CRONTAB=$(crontab -l 2>/dev/null) | |
# Check if the new cron job already exists in the current crontab | |
if echo "$CURRENT_CRONTAB" | grep -qF "$NEW_CRON_JOB"; then | |
echo "Cron job already exists." | |
else | |
# Append the new cron job to the current crontab | |
(echo "$CURRENT_CRONTAB"; echo "$NEW_CRON_JOB") | crontab - | |
echo "Cron job added to crontab." | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment