MongoDB enables user authentication and uses PyMongo to connect

Source: Internet
Author: User
Tags auth mongoclient mongodb


Log on to MongoDB shell and switch to the admin database

Mongo
Use admin

Create administrator user

Db. createUser (
  {
User: "yourusername ",
Pwd: "password ",
Roles: [{role: "userAdminAnyDatabase", db: "admin"}]
  }
)

Modify/etc/init. d/mongod and restart MongoDB.


OPTIONS = "-f $ CONFIGFILE"
Change
OPTIONS = "-- auth-f $ CONFIGFILE"
 
/Etc/init. d/mongod restart

Log on and perform user authentication

Mongo
Use admin
Db. auth ("yourusername", "password ")

You can also log on

Mongo -- port 27017-u yourusername-p password -- authenticationDatabase admin

After the authentication is successful, create a common user and use this user to log on to the specified database.

Db. createUser (
  {
User: "123 ",
Pwd: "123123 ",
Roles :[
{Role: "readWrite", db: "firstdb"}, # read/write permission granted to the firstdb database
{Role: "read", db: "products"}, # read permission for the products database
   ]
  }
)

Use PyMongo to connect to a user-authenticated mongodb instance

From pymongo import MongoClient
Dedicated client ('mongodb: // user: '+ 'password' +' @ 127.0.0.1 ')

If the password contains symbols such as %, \,/, you must use urllib for escape.

Import urllib
From pymongo import MongoClient
Password = urllib. quote_plus ('pass/word % &\/')
MongoClient ('mongodb: // user: '+ password +' @ 127.0.0.1 ')

Change the password of a specified user

Use admin
Db. changeUserPassword ("username", "newpassword ")

Delete a specified user

Use admin
Db. db. system. users. remove ({user: "username "})

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.