Category Archives: Bash

Bash to add many users (linux+MySQL) at one time.

I had a list of username and database to create and could not afford creating them manually. Well, I thought it was a good idea to do some bash scripting and let the machine do the dirty work xd xd.

First, I needed to read arguments from a file/list, then I had some trouble with mysql and all the crop of escaping special character and interpreting variables within single quotes. But I managed to get my users and databases added as intended.

Genrating UNIX accounts:

#!/bin/bash -xv
LIST="~/list"    #list of users

#add users
touch ulogin # file to hold passwords for newly created users
while read line # Loop and read from the list
account=`echo $line | cut -d":" -f1`
uaccount=`echo $line | cut -d":" -f2`
upass=`generate some pass with your preferred function`

useradd -m -g users -u $uaccount $account
echo "$account:$upass" | chpasswd
echo -e "Login FTP:$account \t Password:$upass" >>ulogin

done <$LIST

Genrating MySQL databases and users with privileges granted:

#!/bin/bash -xv
touch dblogin
while read dbname
ddbname=`echo $dbname | sed -e 's/[ \t]*//'` #delete any space or tab
pas=`generate your password with your preferred function ` # I use pwgen
pass=" '$pas' "
dbname=" '$ddbname' "
mysql -uroot -p`cat /root/.hiddenpass` -e "CREATE DATABASE \`$ddbname\`;"
mysql -uroot -p`cat /root/.hiddenpass` -e "CREATE USER $dbname@'%' IDENTIFIED BY $pass;"
mysql -uroot -p`cat /root/.hiddenpass` -e "GRANT ALL PRIVILEGES ON  \`$ddbname\`.* TO $dbname@'%' IDENTIFIED BY $pass; FLUSH PRIVILEGES;"
echo -e "Login/BDD:$ddbname \t Password:$pass" >> dblogin
done <$DB