Linux环境下无人连接时自动关闭Minecraft服务器及主机的脚本实现求助
Hey there! Let's tackle this auto-shutdown logic for your Minecraft servers step by step. Since you already know bash basics, rcon, and Wake-on-LAN, we'll focus on building the core monitoring, timing, and trigger system you need.
1. Core Logic Overview
The key idea is straightforward:
- Monitor all your Minecraft server ports for active TCP connections
- Track the last time any connection was detected
- When no connections are found for 30 minutes straight:
- Gracefully shut down all Minecraft servers via rcon
- Power off the host machine
2. Script Setup & Configuration
First, create a bash script (e.g., mc-auto-shutdown.sh) with configurable variables for your servers. This makes it easy to add/remove servers later.
#!/bin/bash set -euo pipefail # Enable strict error handling to catch bugs early # -------------------------- CONFIGURATION AREA -------------------------- # Define your Minecraft servers: format is "PORT:RCON_SHUTDOWN_COMMAND" # Replace with your actual rcon command (adjust based on your rcon tool, e.g., mcrcon) MC_SERVERS=( "25565:mcrcon -H localhost -P 25565 -p your-rcon-password-1 stop" "25566:mcrcon -H localhost -P 25566 -p your-rcon-password-2 stop" ) INACTIVE_THRESHOLD=1800 # 30 minutes in seconds (1800) CHECK_INTERVAL=60 # Check connections every 60 seconds (adjust as needed) # ----------------------------------------------------------------------- # Initialize timestamp of last detected active connection LAST_ACTIVE_TIMESTAMP=$(date +%s)
3. Connection Detection Function
This function checks all your configured server ports for established TCP connections (using the lsof command you already know). It returns 0 (success) if any active connection is found, 1 otherwise.
check_active_connections() { local has_active=1 # Default to no active connections for server in "${MC_SERVERS[@]}"; do # Extract the port from the server config local port=$(echo "$server" | cut -d: -f1) # Check if the port has any established TCP connections if lsof -iTCP:"$port" -sTCP:ESTABLISHED -t > /dev/null; then has_active=0 # Found active connection break # No need to check other servers fi done return $has_active }
4. Main Monitoring Loop
This is the heart of the script: it runs continuously, checks for connections, updates the last active timestamp, and triggers shutdown when the threshold is hit.
echo "$(date): Starting Minecraft auto-shutdown monitor..." while true; do if check_active_connections; then # Active connection detected: reset the last active timestamp LAST_ACTIVE_TIMESTAMP=$(date +%s) echo "$(date): Active connection detected - resetting inactivity timer" else # No active connections: calculate time since last activity CURRENT_TIMESTAMP=$(date +%s) TIME_SINCE_LAST=$((CURRENT_TIMESTAMP - LAST_ACTIVE_TIMESTAMP)) echo "$(date): No active connections - elapsed time: $TIME_SINCE_LAST seconds" # Check if we've exceeded the inactivity threshold if [ "$TIME_SINCE_LAST" -ge "$INACTIVE_THRESHOLD" ]; then echo "$(date): Inactivity threshold reached! Starting shutdown process..." # Step 1: Gracefully shut down all Minecraft servers via rcon for server in "${MC_SERVERS[@]}"; do local port=$(echo "$server" | cut -d: -f1) local rcon_cmd=$(echo "$server" | cut -d: -f2-) echo "$(date): Shutting down server on port $port..." $rcon_cmd # Wait 30 seconds for the server to save and exit (adjust as needed) sleep 30 done # Step 2: Power off the host machine echo "$(date): All servers shut down. Powering off host..." shutdown -h now exit 0 # Exit script after shutdown fi fi # Wait before next check sleep "$CHECK_INTERVAL" done
5. Make the Script Run in Background & On Boot
To ensure the script runs continuously (even after reboot), set up a systemd service:
Save the script and make it executable:
chmod +x /path/to/mc-auto-shutdown.shCreate a systemd service file (e.g.,
/etc/systemd/system/mc-auto-shutdown.service):[Unit] Description=Minecraft Auto Shutdown Monitor After=network.target [Service] User=your-minecraft-user # Replace with the user running your MC servers ExecStart=/path/to/mc-auto-shutdown.sh Restart=always # Restart the script if it crashes RestartSec=5 [Install] WantedBy=multi-user.targetEnable and start the service:
sudo systemctl daemon-reload sudo systemctl enable mc-auto-shutdown.service sudo systemctl start mc-auto-shutdown.service
6. Optional Enhancements
- Add player warnings: Before shutting down, send a message to all players via rcon (e.g.,
say Server will shut down in 5 minutes due to inactivity!) and wait 5 minutes. - Test with shorter thresholds: Set
INACTIVE_THRESHOLD=60(1 minute) to test the script without waiting 30 minutes. - Log to a file: Redirect script output to a log file for debugging (add
>> /var/log/mc-auto-shutdown.log 2>&1to theExecStartline in the systemd service).
内容的提问来源于stack exchange,提问作者BloxBoss6




