This is not a simple task, but it can be done. There are many web sites that have several solutions – and some actually work. However, this one is guaranteed to work on Ubuntu 12.04 and later.
The problem is that the AppArmor product does an exceptionally good job of not letting a script make changes to the MySQL environment. As such, we need to get it out of our way and then proceed with the resetting of the MySQL root
password.
Note that the password of abcd1234mysql is hard-coded into the script. You can use and editor like gedit
to change this.
Become the superuser (sudo -s
) and you can use the following procedure to simplify your life:
wget https://programmingby.design/project-data/mysql-chpw chmod u+x mysql-chpw ./mysql-chpw
For those interested in how it works, the source code is included below.
[bash] #!/bin/bash#
# Change this to your desired password
#
pw="abcd1234mysql"
clear
cat >/tmp/myreset.sql <<EOF
update mysql.user set password=password(‘$pw’) where user=’root’;
flush privileges;
EOF
echo -e "\nTearing down AppArmor – it gets in the way"
service apparmor teardown
echo -e "\nStopping mysqld."
service mysql stop
echo -e "\nStarting mysqld with init file."
/usr/bin/mysqld_safe –init-file=/tmp/myreset.sql &
while [ ! -f /var/run/mysqld/mysqld.pid ]
do
sleep 1
done
cat /var/run/mysqld/mysqld.pid
pid=$(cat /var/run/mysqld/mysqld.pid)
echo -e "\nStopping mysqld and restoring normal service."
kill -15 $pid
p=$(ps -ef | grep " $pid " | grep -v grep | wc -l)
while [ $p -gt 0 ]
do
p=$(ps -ef | grep " $pid " | grep -v grep | wc -l)
done
service mysql start
echo "Starting AppArmor"
service apparmor start
echo -e "\n\nIT IS STRONGLY ADVISED YOU REBOOT SINCE APPARMOR IS NOT ENFORCING.\n\n"
rm -f /tmp/myreset.sql
[/bash]