Skip to content

Instantly share code, notes, and snippets.

@BaksiLi
Created November 25, 2024 15:34
Show Gist options
  • Save BaksiLi/b844a84e35b679c15e83c21a3dfac1e7 to your computer and use it in GitHub Desktop.
Save BaksiLi/b844a84e35b679c15e83c21a3dfac1e7 to your computer and use it in GitHub Desktop.
User-aware process control monitor (SIGSTOP/SIGCONT)
#!/bin/bash
set -euo pipefail
# Configuration
SCRIPT_NAME="./evil-process"
LOG_FILE="./process_monitor.log"
CHECK_INTERVAL=5
# Target users to monitor
TARGET_USERS=("root" "admin")
# Log
log() {
local message="$1"
# Standard logging
echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | tee -a "$LOG_FILE"
}
# Redirect stdout and stderr to log file while maintaining console output
exec 1> >(tee -a "$LOG_FILE") 2>&1
# Find process
PROCESS_PID=$(pgrep -f "$SCRIPT_NAME") || {
log "Process $SCRIPT_NAME not found"
exit 1
}
# Signal handling
cleanup() {
log "Stopping monitor..." true
kill -CONT $PROCESS_PID 2>/dev/null || true
exit 0
}
trap cleanup SIGTERM SIGINT
# Process health check
check_process() {
if ! kill -0 "$PROCESS_PID" 2>/dev/null; then
log "Target process no longer exists"
exit 1
fi
}
# Create lock file
LOCK_FILE="/tmp/process_monitor.lock"
if [ -e "$LOCK_FILE" ]; then
log "Another instance is running. Exiting..."
exit 1
fi
touch "$LOCK_FILE"
trap 'rm -f "$LOCK_FILE"' EXIT
previous_state="resumed"
log "Starting monitor for PID $PROCESS_PID"
while true; do
check_process
# Check if any target user is logged in
for user in "${TARGET_USERS[@]}"; do
if who | grep "^${user}" | grep -q "pts/"; then
if [ "$previous_state" != "paused" ]; then
log "Target user ${user} detected - suspending process"
kill -STOP $PROCESS_PID
previous_state="paused"
break
fi
fi
done
# Resume if no target users are logged in
if [ "$previous_state" = "paused" ]; then
if ! who | grep -E "^($(IFS="|"; echo "${TARGET_USERS[*]}"))" | grep -q "pts/"; then
log "No target users - resuming process"
kill -CONT $PROCESS_PID
previous_state="resumed"
fi
fi
sleep "$CHECK_INTERVAL"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment