Skip to content

Instantly share code, notes, and snippets.

@vedantiitkgp
Created November 8, 2024 22:51
Show Gist options
  • Save vedantiitkgp/30e81a2737c8717c730675b724163298 to your computer and use it in GitHub Desktop.
Save vedantiitkgp/30e81a2737c8717c730675b724163298 to your computer and use it in GitHub Desktop.
Resetting the MySQL Passwords
#!/bin/bash
# Define the system password for sudo (only needed if not logged in as root)
PASSWORD="your_password"
# Define the new MySQL root password
SQL_PASSWORD="vedant123"
# Check if the script is run as root
if [ "$(whoami)" == "root" ]; then
IS_ROOT=true
else
IS_ROOT=false
fi
# Check if the MySQL socket directory exists, if not, create it
if [ ! -d /var/run/mysqld ]; then
if [ "$IS_ROOT" = true ]; then
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
else
echo "$PASSWORD" | sudo -S mkdir -p /var/run/mysqld
echo "$PASSWORD" | sudo -S chown mysql:mysql /var/run/mysqld
fi
echo "Created /var/run/mysqld directory and set permissions."
else
echo "/var/run/mysqld directory already exists."
fi
# Stop the MySQL service
if [ "$IS_ROOT" = true ]; then
systemctl stop mysql
else
echo "$PASSWORD" | sudo -S systemctl stop mysql
fi
# Run MySQL in safe mode (skip-grant-tables)
if [ "$IS_ROOT" = true ]; then
mysqld_safe --skip-grant-tables &
else
echo "$PASSWORD" | sudo -S mysqld_safe --skip-grant-tables &
fi
# Wait for MySQL to start in safe mode
sleep 10 # Adjust this time as needed to ensure MySQL is ready
# Log into MySQL (now running without grant tables) and reset the password
mysql -u root <<EOF
USE mysql;
UPDATE mysql.user SET authentication_string='$SQL_PASSWORD' WHERE User='root' AND Host='localhost';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$SQL_PASSWORD';
FLUSH PRIVILEGES;
EOF
# Stop mysqld_safe process manually (as it's not a service)
if [ "$IS_ROOT" = true ]; then
pkill -f mysqld_safe
else
echo "$PASSWORD" | sudo -S pkill -f mysqld_safe
fi
# Start MySQL service again
if [ "$IS_ROOT" = true ]; then
systemctl start mysql
else
echo "$PASSWORD" | sudo -S systemctl start mysql
fi
echo "Password reset completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment