Files
server-scripts/delete_user.sh
2026-01-05 22:18:06 +01:00

82 lines
1.6 KiB
Bash
Executable File

#!/usr/bin/env bash
set -e
FORCE=0
USERNAME=""
usage() {
echo "Usage: $0 [--force] <username>"
echo
echo "Options:"
echo " --force Skip graceful shutdown, force kill processes and delete user"
exit 1
}
# Parse args
while [[ $# -gt 0 ]]; do
case "$1" in
--force)
FORCE=1
shift
;;
-*)
usage
;;
*)
USERNAME="$1"
shift
;;
esac
done
if [ -z "$USERNAME" ]; then
usage
fi
# Safety checks
if [ "$USERNAME" = "root" ]; then
echo "❌ Refusing to delete root"
exit 1
fi
if [ "$USERNAME" = "$(whoami)" ]; then
echo "❌ Refusing to delete the currently logged-in user"
exit 1
fi
if ! id "$USERNAME" >/dev/null 2>&1; then
echo "❌ User '$USERNAME' does not exist"
exit 1
fi
echo "🧨 Preparing to delete user: $USERNAME"
echo "Force mode: $FORCE"
echo
if [ "$FORCE" -eq 0 ]; then
echo "🔍 Processes owned by $USERNAME:"
ps -u "$USERNAME" -o pid,ppid,cmd || true
echo "🛑 Terminating systemd session for $USERNAME (if any)..."
loginctl list-users | grep -w "$USERNAME" && loginctl terminate-user "$USERNAME" || true
echo "🧹 Sending SIGTERM to remaining processes..."
pkill -u "$USERNAME" || true
sleep 1
fi
echo "🔥 Sending SIGKILL to remaining processes..."
pkill -9 -u "$USERNAME" || true
sleep 1
# Optional linger cleanup (rootless docker users)
if [ -f "/var/lib/systemd/linger/$USERNAME" ]; then
echo "🧼 Removing linger file for $USERNAME"
rm -f "/var/lib/systemd/linger/$USERNAME"
fi
echo "🗑️ Deleting user and home directory..."
userdel -r "$USERNAME"
echo "✅ User '$USERNAME' deleted successfully."