MongoDB User management shell script
#!/bin/bash
## Copy this script to your mongo /bin folder #################################
PWP_HOME=/opt/pwp/3.0
MONGO_HOME=/apps/bin
SCRIPTS=/apps/UMG_Menu/Scripts
HOME=/apps/UMG_Menu/UMG_PWP
LOGS=/apps/UMG_Menu/ScriptLogs
TIMESTAMP=`date +%d-%m-%y_%H:%M:%S`
DATE=`date +%d-%m-%y`
db=admin
local_host=`hostname`
ID=`id -u -n`
echo
echo " User_Management.sh script is executed by user : $ID"
echo
echo " Date and Time of Execution : `date`"
echo
read -p "Enter Hostname : " host
read -p "Enter Port : " port
var=`grep $host $SCRIPTS/mongodb.ini | grep $port`
if [ -z "$var" ]
then
echo "$host is not in mongodb.ini file - Please provide a valid hostname." >> $LOGS/UserManagement-$DATE-$TIMESTAMP.log
echo "$host is not in mongodb.ini file - $TIMESTAMP \n" >> $LOGS/UserManagement-$DATE-$TIMESTAMP.log
exit
else
echo "$host is mongodb.ini file - $TIMESTAMP \n" >> $LOGS/UserManagement-$DATE-$TIMESTAMP.log
fi
echo
echo "Hostname and Port number are valid." >> $LOGS/UserManagement-$DATE-$TIMESTAMP.log
echo
sleep 1
PASWD=`$PWP_HOME/bin/pwpl -a $HOME/access.cf -f $HOME/password.cf $SCRIPTS/GetPw.sh uisabg2 $local_host`
while :
do
clear
echo -e "===============================================================================
------------------ M A I N - M E N U ----------------------------------
1) List Of DB Wise Existing Users & Their Roles
2) User Creation
3) Change Password Of A User
4) Lock/Unlock A User
5) Remove A User
6) To Change Roles of A User
7) Exit
===============================================================================\n"
echo -n "Please choose your option from the above list of User Management activities [1-7] :"
read option
case $option in
1) dbs=`$MONGO_HOME/mongo $host:$port/admin -u menu -p $PASWD --eval "printjson(db.adminCommand('listDatabases'))" | grep "name" | cut -d: -f2 | sed 's/ "//g;s/",//g'`;
echo -e "\nActive Users & their Roles in respective databases ...
================================================================================\n"
for i in $dbs ;
do
echo -e "Database Name : $i
----------------------------"
$MONGO_HOME/mongo $host:$port/$i --authenticationDatabase admin -u menu -p $PASWD --eval "db.system.users.find({},{\"user\":1,\"roles\":1,\"_id\":0}).forEach(function(a){print(a.user ,' -------> ', a.roles)})" | grep -v "MongoDB" | grep -v "connecting" ;
echo -e "\n"
done;
echo -e "\nAll Locked Users & their Roles in respective databases ...
================================================================================\n"
for i in $dbs ;
do
echo -e "Database Name : $i
----------------------------"
$MONGO_HOME/mongo $host:$port/$i --authenticationDatabase admin -u menu -p $PASWD --eval "db.lockedUsers.find({},{\"user\":1,\"roles\":1,\"_id\":0}).forEach(function(a){print(a.user ,' -------> ', a.roles)})" | grep -v "MongoDB" | grep -v "connecting" ;
echo -e "\n"
done;
echo -e "\nPress [enter] key to continue to ISA Main Menu :";
read enterKey;;
2) read -p "Enter Database Name : " db ;
echo -e "\nAvailable User roles in MongoDB are ...\n";
echo -e "===================
read
readAnyDatabase
readWrite
readWriteAnyDatabase
dbAdmin
dbAdminAnyDatabase
userAdmin
userAdminAnyDatabase
clusterAdmin
====================\n";
read -p "Enter Role (for multiple roles - use \",\" as a delimeter) : " role;
sleep 1;
echo
read -p "Enter User ID : " un ;
sleep 1;
echo
echo -e "****** Pls Note: Password should be at least 6 Characters along with 1 Digit and 1 Upper case Alphabet ******\n";
read -s -p " Enter password : " s ;
sleep 1;
if [[ ${#s} -ge 6 && "$s" == *[A-Z]* && "$s" == *[a-z]* && "$s" == *[0-9]* ]];then
$MONGO_HOME/mongo $host:$port/$db --authenticationDatabase admin -u menu -p $PASWD --eval "db.addUser({user:\"$un\",pwd:\"$s\",roles:[\"$role\"]})" > /dev/null 2>&1 &
mypid=$!
wait $mypid
op=$?
if [ $op -eq 0 ]; then
echo -e "\nSUCCESS : User has been created with the following details \n
Username : $un
User role : $role
Database : $db
Port : $port
Hostname : $host \n"
else
echo "ERROR : User creation failed, please check & try again."
fi
else
echo -e "\nPassword criteria: Password should be at least 6 Characters along with 1 Digit & 1 Upper case Alphabet";
echo -e "\nPassword does not Match the criteria, exiting... try again";
exit;
fi
echo -e "\nPress [enter] key to continue to Main Menu. . .";
read enterKey;;
3)
read -p "Enter Database Name : " db
sleep 1;
echo -e "\nUser & their Roles under Database : $db are ...
------------------------------"
$MONGO_HOME/mongo $host:$port/$db --authenticationDatabase admin -u menu -p $PASWD --eval "db.system.users.find({},{\"user\":1,\"roles\":1,\"_id\":0}).forEach(function(a){print(a.user ,' -------> ', a.roles)})" | grep -v "MongoDB" | grep -v "connecting" ;
echo -e "\n"
read -p "Enter User ID : " un ;
if [ $un == "menu" ]; then
echo "No operation allowed on $un user .. exiting"
exit
fi
echo -e "\n****** Pls Note: Password should be at least 6 Characters along with 1 Digit and 1 Upper case Alphabet ******\n";
read -s -p "Enter the new password : " s ;
sleep 1;
if [[ ${#s} -ge 6 && "$s" == *[A-Z]* && "$s" == *[a-z]* && "$s" == *[0-9]* ]];then
$MONGO_HOME/mongo $host:$port/$db --authenticationDatabase admin -u menu -p $PASWD --eval "db.changeUserPassword(\"$un\",\"$s\")"
op=$?
if [ $op -eq 0 ]; then
echo -e "\nSUCCESS : User password has been changed with the following details \n
Username : $un
Database : $db
Port : $port
Hostname : $host \n"
else
echo "ERROR : Password change failed, please check & try again."
fi
else
echo -e "\nPassword criteria: Password should be at least 6 Characters along with 1 Digit & 1 Upper case Alphabet";
echo -e "\nPassword does not Match the criteria, exiting... try again";
exit;
fi
echo -e "\nPress [enter] key to continue to ISA Main Menu :";
read enterKey;;
4)
read -p "Enter Database Name : " dbs;
echo -e "\nAll Users & their Roles under Database : $dbs are ...
------------------------------"
$MONGO_HOME/mongo $host:$port/$dbs --authenticationDatabase admin -u menu -p $PASWD --eval "db.system.users.find({},{\"user\":1,\"roles\":1,\"_id\":0}).forEach(function(a){print(a.user ,' -------> ', a.roles)})" | grep -v "MongoDB" | grep -v "connecting" ;
echo -e "\nAll Locked Users & their Roles under Database : $dbs are ... \n
------------------------------"
$MONGO_HOME/mongo $host:$port/$dbs --authenticationDatabase admin -u menu -p $PASWD --eval "db.lockedUsers.find({},{\"user\":1,\"roles\":1,\"_id\":0}).forEach(function(a){print(a.user ,' -------> ', a.roles)})" | grep -v "MongoDB" | grep -v "connecting" ;
read -p "Enter Username :" user;
read -p "To lock user enter l, To unlock user enter u : (l:lock / u:unlock) : " lug;
if [ $lug == "l" ]; then
if [ $user == "menu" ]; then
echo "No operation allowed on $un user .. exiting"
exit
fi
$MONGO_HOME/mongo $host:$port/$dbs --authenticationDatabase admin -u menu -p $PASWD --eval "var toLock = db.system.users.find({ \"user\": \"$user\" });if (toLock.size() != 1) { print(\"Error! found \" + toLock.size() + \" matching users\");} else {db.lockedUsers.insert(toLock[0]);db.system.users.remove({\"user\": \"$user\"});}";
op=$?
if [ $op -eq 0 ]; then
echo -e "\nSUCCEESS : User has been locked with the following details \n
Username : $user
Database : $dbs
Port : $port
Hostname : $host \n"
else
echo "ERROR : Lock User operation failed, please check & try again."
fi
fi
if [ $lug == "u" ]; then
$MONGO_HOME/mongo $host:$port/$dbs --authenticationDatabase admin -u menu -p $PASWD --eval "var toUnlock = db.lockedUsers.find( {\"user\":\"$user\"} );if (toUnlock.size() != 1) { print(\"Error! found \" + toUnlock.size() + \" matching users\"); return;} else {db.system.users.insert(toUnlock[0]);db.lockedUsers.remove({\"user\":\"$user\"});}";
op=$?
if [ $op -eq 0 ]; then
echo -e "\nSUCCESS : User has been unlocked with the following details \n
Username : $user
Database : $db
Port : $port
Hostname : $host \n"
else
echo "ERROR : Unlock user operation failed, please check & try again."
fi
fi
if [ $lug != "l" -a $lug != "u" ]; then
echo -e "\nERROR : Invalid option $lug, please try again. ";
fi
echo -e "\nPress [enter] key to continue to Main Menu. . .";
read enterKey;;
5)
read -p "Enter Database Name : " db
echo -e "\nAll Users & their Roles under Database : $db are ... \n
------------------------------"
$MONGO_HOME/mongo $host:$port/$db --authenticationDatabase admin -u menu -p $PASWD --eval "db.system.users.find({},{\"user\":1,\"roles\":1,\"_id\":0}).forEach(function(a){print(a.user ,' -------> ', a.roles)})" | grep -v "MongoDB" | grep -v "connecting" ;
read -p "Enter User ID to remove : " un
if [ $un == "menu" ]; then
echo "No operation allowed on $un user .. exiting"
exit
fi
$MONGO_HOME/mongo $host:$port/$db --authenticationDatabase admin -u menu -p $PASWD --eval "db.removeUser(\"$un\")"
op=$?
if [ $op -eq 0 ]; then
echo -e "\nSUCCESS : User has been removed with the following details \n
Username : $un
Database : $db
Port : $port
Hostname : $host \n"
else
echo "ERROR : User remove operation failed, please check & try again."
fi
echo -e "\nPress [enter] key to continue to Main Menu. . .";
read enterKey;;
6) read -p "Enter Database Name : " db
echo -e "\nAll User & their Roles under Database : $db are ... \n
------------------------------"
$MONGO_HOME/mongo $host:$port/$db --authenticationDatabase admin -u menu -p $PASWD --eval "db.system.users.find({},{\"user\":1,\"roles\":1,\"_id\":0}).forEach(function(a){print(a.user ,' -------> ', a.roles)})" | grep -v "MongoDB" | grep -v "connecting" ;
echo -e "\n"
read -p "Enter User ID to change User roles : " un
if [ $un == "menu" ]; then
echo "No operation allowed on $un user .. exiting"
exit
fi
echo -e "\nAvailable User roles in MongoDB are ..
===========================================
read
readAnyDatabase
readWrite
readWriteAnyDatabase
dbAdmin
dbAdminAnyDatabase
userAdmin
userAdminAnyDatabase
clusterAdmin
============================================\n";
read -p "Enter Role (for multiple roles - use \",\" as a delimeter) : " role
$MONGO_HOME/mongo $host:$port/$db --authenticationDatabase admin -u menu -p $PASWD --eval "db.system.users.update({\"user\":\"$un\"},{\$set:{\"roles\":[\"$role\"]}})" >> $LOGS/UsrMgt-$DATE.log 2>> $LOGS/UsrMgt-$DATE.log
op=$?
if [ $op -eq 0 ]; then
echo -e "\nSUCCESS : Role(s) successfully granted with following details \n"
echo "Username : $un"
echo "User Role : $role"
echo "Database : $db"
echo "Port : $port"
echo -e "Hostname : $host \n"
else
echo "ERROR : Granting role has failed, please check & try again."
fi
echo -e "\nPress [enter] key to continue to Main Menu. . .";
read enterKey;;
7) echo "Bye $USER";
exit 1;;
*) echo -e "\n $option is an invaild option, please select option between 1-7 only"
echo -e "\n Press Enter key to continue to Main Menu"
read enterKey;;
esac
done
Ask Question