Skip to content

Instantly share code, notes, and snippets.

@kennwhite
Last active February 14, 2021 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennwhite/3b0361aa841a49f4f1ce38f1aad3567f to your computer and use it in GitHub Desktop.
Save kennwhite/3b0361aa841a49f4f1ce38f1aad3567f to your computer and use it in GitHub Desktop.
Enable Authentication for new install of MongoDB
#!/bin/bash
sudo sed -i-`date -u|tr ' ' '_'`.bak 's/^#security:*/security:\n authorization: enabled/' /etc/mongod.conf
_mpwd=$(head -c 32 /dev/urandom 2>&1 | sha1sum | head -c 14 )
echo "db.dropUser('dba')"|mongo "mongodb://localhost/admin"
echo "db.createUser({user:'dba',pwd:'$_mpwd',roles:['root']})"|mongo "mongodb://localhost/admin"
sudo service mongod restart && sleep 5
echo show dbs | mongo "mongodb://dba:$_mpwd@localhost/?authSource=admin"
echo -e "\nTo login as user 'dba': mongo 'mongodb://dba:$_mpwd@localhost/?authSource=admin' (or YourIpAddress:27107)\n\n"
@kennwhite
Copy link
Author

kennwhite commented Sep 14, 2018

Expanded version:

#!/bin/bash

# Enable auth by default, save date-stamped backup conf file
echo -e "\nTesting connection to mongod server WITHOUT auth..."
if echo show dbs | mongo admin 2>&1 | grep -q config; then echo Confirmed connection WITHOUT auth.; fi

echo -e "\nEnabling authentication..."

sudo sed -i-`date -u|tr ' ' '_'`.bak 's/^#security:*/security:\n  authorization: enabled/' /etc/mongod.conf

_mpwd=$(head -c 32 /dev/urandom 2>&1 | sha1sum | head -c 14 )
echo "db.dropUser('dba')"|mongo "mongodb://localhost/admin" 
echo "db.createUser({user:'dba',pwd:'$_mpwd',roles:['root']})"|mongo "mongodb://localhost/admin" 

echo -e "\nRestarting MongoDB to enforce authentication in 5 seconds..."
sudo service mongod restart && sleep 5

echo -e "\nTesting connection to mongod server WITHOUT auth (should fail)..."
if ! echo show dbs | mongo admin 2>&1 | grep -q config; then echo "Confirmed connection (correctly) failed without auth."; fi

echo -e "\nTesting connection to mongod server WITH auth (should show DBs)...\n"
echo show dbs | mongo "mongodb://dba:$_mpwd@localhost/?authSource=admin"

echo -e "\nTo login as user 'dba': mongo "mongodb://dba:$_mpwd@localhost/?authSource=admin" (or YourIpAddress:27107)\n\n"


@kennwhite
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment