Skip to content

Instantly share code, notes, and snippets.

@nateflink
Last active November 10, 2024 05:08
Show Gist options
  • Save nateflink/5785237 to your computer and use it in GitHub Desktop.
Save nateflink/5785237 to your computer and use it in GitHub Desktop.
A bash script that adds a mysql user, and creates a database with the same name as the user and echos the generated password
#!/bin/bash
# Adds a mysql user, and creates a database with the same name as the user and echos the generated password
# usage:
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
echo "usage: ./$0 [mysql db username] [mysql user password] [new identifier]"
exit
fi
DB_USER=$3
DB_PASSWORD=</dev/urandom LC_CTYPE=C tr -dc A-Za-z0-9_\!\@\#\%\^\&\*\(\)-+ | head -c 24
#sql for creating a user and a database
CMD=$(cat <<EOF
CREATE USER '$DB_USER'@'%' IDENTIFIED BY '$DB_PASSWORD';
GRANT USAGE ON * . * TO '$DB_USER'@'%' IDENTIFIED BY '$DB_PASSWORD' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
CREATE DATABASE IF NOT EXISTS \`$DB_USER\`;
GRANT ALL PRIVILEGES ON \`$DB_USER\` . * TO '$DB_USER'@'%';
EOF
)
#echo "$CMD" > "$TMP_FILE"
mysql -u "$1" -p"$2" -e "$CMD"
echo "$DB_PASSWORD"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment