Files
Kelx/privileged/jobs/mysql-skip-grant.sh
T
2026-11-30 16:32:37 +00:00

96 lines
2.3 KiB
Bash

#!/usr/bin/env bash
# ADPanel privileged job: MySQL/MariaDB admin reset via skip-grant-tables.
# Invoked via adpanel-priv: adpanel-priv job mysql-skip-grant
# stdin: SQL statements to execute as root once the server is in
# skip-grant-tables mode.
set -u
SQL="$(cat)"
[ -n "$SQL" ] || { echo "mysql-skip-grant: no SQL on stdin" >&2; exit 2; }
SOCK_DIR="/var/run/mysqld"
SOCK_PATH="$SOCK_DIR/mysqld.sock"
# Detect service name (mariadb, mysql or mysqld)
SVC=""
for s in mariadb mysql mysqld; do
if systemctl list-unit-files "$s.service" >/dev/null 2>&1; then
SVC="$s"
break
fi
done
if [ -z "$SVC" ]; then
echo "ERROR: Could not detect MySQL/MariaDB service name" >&2
exit 1
fi
# Detect the server binary (mariadbd or mysqld)
SERVER_BIN=""
for bin in mariadbd mysqld; do
if command -v "$bin" >/dev/null 2>&1; then
SERVER_BIN="$bin"
break
fi
for p in /usr/sbin /usr/bin /usr/libexec; do
if [ -x "$p/$bin" ]; then
SERVER_BIN="$p/$bin"
break 2
fi
done
done
if [ -z "$SERVER_BIN" ]; then
echo "ERROR: Could not find mariadbd or mysqld binary" >&2
exit 1
fi
systemctl stop "$SVC" 2>/dev/null || true
pkill -9 -x mariadbd 2>/dev/null || true
pkill -9 -x mysqld 2>/dev/null || true
sleep 2
mkdir -p "$SOCK_DIR"
chown mysql:mysql "$SOCK_DIR" 2>/dev/null || true
chmod 755 "$SOCK_DIR"
rm -f "$SOCK_PATH" 2>/dev/null || true
"$SERVER_BIN" --skip-grant-tables --skip-networking --user=mysql --socket="$SOCK_PATH" &
SAFE_PID=$!
READY=0
for i in $(seq 1 40); do
if [ -S "$SOCK_PATH" ]; then
if mysql --socket="$SOCK_PATH" -u root -e "SELECT 1" >/dev/null 2>&1; then
READY=1
break
fi
fi
sleep 0.5
done
if [ "$READY" -ne 1 ]; then
echo "ERROR: skip-grant-tables server did not become ready" >&2
kill "$SAFE_PID" 2>/dev/null || true
pkill -9 -x mariadbd 2>/dev/null || true
pkill -9 -x mysqld 2>/dev/null || true
systemctl start "$SVC" 2>/dev/null || true
exit 1
fi
{ echo "FLUSH PRIVILEGES;"; printf '%s\n' "$SQL"; } | mysql --socket="$SOCK_PATH" -u root
SQL_EXIT=$?
kill "$SAFE_PID" 2>/dev/null || true
pkill -9 -x mariadbd 2>/dev/null || true
pkill -9 -x mysqld 2>/dev/null || true
sleep 2
systemctl start "$SVC" 2>/dev/null || true
for i in $(seq 1 30); do
if systemctl is-active "$SVC" >/dev/null 2>&1; then
break
fi
sleep 0.5
done
exit "$SQL_EXIT"