Files
mysql-ubuntu/mysqlinstall

130 lines
3.0 KiB
Bash
Executable File

#!/usr/bin/env bash
# Author : Allan Christensen
# First Created : 08072021 (DD-MM-YYYY)
# Description : Installs MySQL on Ubuntu 24.04 using PASSWORD authentication
# License : MIT License (see LICENSE file for details)
#
# Are we root
#
if [[ $(id -u) -ne 0 ]]; then echo "" && echo "Must be root or use sudo" && echo "" ; exit 1 ; fi
#
# Check if services are already running
#
for svc in mysql; do if systemctl is-active --quiet "$svc"; then printf "\n%s is already running, cannot continue...\n\n" "${svc^}" ; exit 1 ; fi ; done
#
# Define variables
#
mysqlconfig="/etc/mysql/mysql.conf.d/mysqld.cnf"
#
# Function usage
#
usage () {
printf -- "\nmysqlinstall\n\n"
printf -- "Installs and configures MySQL on Ubuntu 24.04\n"
printf -- "Note: Must be run as root or using sudo\n\n"
printf -- "Root authentication uses PASSWORD (no socket auth)\n\n"
printf -- "Usage:\n"
printf -- " sudo ./mysqlinstall -p <rootpassword>\n"
printf -- " sudo ./mysqlinstall -h (help)\n\n"
printf -- "Example:\n"
printf -- " sudo ./mysqlinstall -p SuperSecret123\n\n"
}
clear
#
# Argument check
#
if [[ $# -eq 0 ]]; then usage ; printf "ERROR: -p REQUIRED!\n\n" ; exit 1 ; fi
while [[ $# -gt 0 ]]; do
case "$1" in
-p)
shift
[[ -z "$1" ]] && usage && printf "ERROR: ROOT PASSWORD REQUIRED!\n\n" && exit 1
rootpwd="$1"
shift
;;
-h)
usage ; exit 0 ;;
*)
usage ; printf "\nType: sudo %s -h for help\n\n" "$0" ; exit 1 ;;
esac
done
#
# Final sanity check
#
if [[ -z "$rootpwd" ]]; then usage ; printf "\nERROR: Missing -p <rootpassword>\n\n" ; exit 1 ; fi
#
# Password disallow spaces and backslashes
#
if [[ "$rootpwd" =~ [[:space:]] ]]; then
printf "\nERROR: Password cannot contain spaces.\n\n"
exit 1
fi
if [[ "$rootpwd" =~ [\\] ]]; then
printf "\nERROR: Password cannot contain backslashes (\\).\n\n"
exit 1
fi
#
# Install MySQL
#
apt install -y mysql-server mysql-client
#
# Configure MySQL authentication (native password, no socket auth)
#
mysql --execute="ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${rootpwd}'; FLUSH PRIVILEGES;"
#
# Harden MySQL installation
#
mysql -u root -p"${rootpwd}" <<'EOF'
-- Remove anonymous users
DELETE FROM mysql.user WHERE User='';
-- Remove remote root access
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
-- Drop test database
DROP DATABASE IF EXISTS test;
-- Remove test DB privileges
DELETE FROM mysql.db WHERE Db='test' OR Db LIKE 'test_%';
-- Apply changes
FLUSH PRIVILEGES;
EOF
#
# Create /root/.my.cnf
#
cat > /root/.my.cnf <<EOF
[client]
user=root
password=${rootpwd}
EOF
chmod 400 /root/.my.cnf
#
# All done
#
printf "\nAll Done...\n\n"
printf -- "--------------------------------------------\n"
printf " Root Password : %s\n" "$rootpwd"
printf -- "--------------------------------------------\n\n"
printf ".my.cnf has been created for passwordless login.\n\n"
#
# End of script
#