mongo用户管理实践

2020年7月18日 14:39 by wst

database

最近打算抓取一些数据进行分析,由于之前用过mongo,觉得不错。这次决定采用mongo存储数据,图的就是方便!

目的很简单,只是存取数据,但这中间遇到了一些问题,下面一一列举:

创建用户

1. 前提是已安装并启动数据,这里使用docker安装的mongo,命令如下:

# 拉取mongo镜像
docker pull mongo:latest
# 创建并运行实例
docker run -itd --name mongo -p 27017:27017 mongo --auth

2. 进入mongo,在admin中创建用户:

docker exec -it mongo mongo admin
# 创建一个名为 admin,密码为 123456 的用户。
>  db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'}]});
# 尝试使用上面创建的用户信息进行连接。
> db.auth('admin', '123456')

3. 创建普通用户,使其对应库db001, db002

>db.createUser({
    user:"wst",
    pwd:"123456",
    roles:[{
        role:"dbAdmin",
        db:"db001"
    },{
        role:"readWrite",
        db:"db002"
    }]
})

读写数据

4. 运行如下(python3)代码,读写数据库db001

from pymongo import MongoClient

class StoreMongo(object):
    def __init__(self, host, port, user, password, database, collection):
        self.client = MongoClient(host, port)
        self.client.admin.authenticate(user, password)
        self.database = database
        self.collection = collection

    def get_cursor(self):
        db = self.client[self.database]
        collection = db[self.collection]
        return collection

    def coll_names(self):
        db = self.client[self.database]
        return db.collection_names()

    def store_data(self, dataset):
        collection = self.get_cursor()
        for data in dataset:
            collection.save(data)

    def upsert(self, con, dic):
        collection = self.get_cursor()
        collection.update(con, dic, True)

    def delete(self, query):
        collection = self.get_cursor()
        collection.delete_one(query)

    def results_count(self, query):
        collection = self.get_cursor()
        return collection.find(query).count()

    def search_data(self, query, limit={"_id": 0}):
        rs = self.client[self.database][self.collection].find(query, limit)
        return rs

    def collection_count(self):
        return self.client[self.database][self.collection].count()

    def __del__(self):
        self.client.close()


if __name__ == "__main__":
    host = '10.160.15.209'  # 如果在阿里云上运行使用 10.160.15.209
    port = 27017 #请根据实际情况修改
    user = "wst" #请根据实际情况修改
    password = "123456" #请根据实际情况修改
    database = 'db001' #请根据实际情况修改
    collection = 'mydata' #请根据实际情况修改

    obj = StoreMongo(host, port, user, password, database, collection)
    # 存储单条数据
    obj.store_data([{"name": "xiaoming", "sex": "male", "age": 18}, ])
    # 存储多条数据
    obj.store_data([{"name": "lingling", "sex": "female", "age": 16},
                    {"name": "zhangsan", "sex": "male", "age": 20}])

    res = obj.search_data({})
    print(res.next())
    print("Done!")

 奇怪的事情发生了,写入报错,我已经是dbAdmin角色了,为什么不能操作db001库呢?

添加权限

5. 后来查询发现adAdmin并不具有读写权限,于是执行如下命令添加readWrite角色。

docker exec -it mongo mongo admin
>db.auth('admin', '123456')
>db.grantRolesToUser("wst",[{ role : "readWrite", db : "db001"}])

再次执行上面的python代码,已经能正确读写数据!

走过的弯路

1. 无法进入数据库。

进入mongo之后(这里默认进入的是admin库),没有进行认证 db.auth('admin', '123456'),无法进行后续操作。

2. 无法操作自己的库。

use db001 进入自己库,然后再认证db.auth('wst', '123456'),  发现报错。实际应该:在admin库中执行db.auth('wst', '123456'),然后再use db001进入自己的库。最终查看自己的数据db.mydata.find()

 

总结

1. 开启认证的mongo服务,进入时需要认证;

2. 并不是所有带admin字眼的角色都能读写数据,详细可见这里

3. 要想进入自己的库,得先在admin库中认证,然后进入自己的库;

 

知识点

docker创建mongo实例、创建管理员用户、给用户添加权限

 

后记:对于更多的用户操作(比如修改密码、撤销权限、更新用户),参考这里


Comments(130) Add Your Comment

Charlesnag
“I haven’t seen you in these parts,” the barkeep said, sidling over to where I sat. “Name’s Bao.” He stated it exuberantly, as if word of his exploits were shared aside settlers about multitudinous a fire in Aeternum. He waved to a unimpassioned hogshead beside us, and I returned his gesture with a nod. He filled a eyeglasses and slid it to me across the stained red wood of the bench prior to continuing. “As a betting man, I’d be ready to wager a adequate piece of silver you’re in Ebonscale Reach in search more than the drink and sights,” he said, eyes glancing from the sword sheathed on my with it to the salaam slung across my back. http://images.google.co.uz/url?q=https://renewworld.ru/
Kevingaw
https://www.hille-eventservice.de/news/wettannahmestellen_in_polen.html http://images.google.com.af/url?q=https://1xbitapk.com/fr/ https://www.merkur-zeitschrift.de/wp-content/pages/die_besten_casinos_in_las_vegas_auf_dem_strip.html http://die-fototasse.de/wp-content/plugins/element/welches_online_casino_ist_zu_empfehlen___1.html https://www.google.cm/url?sa=i&rct=j&q=w4&source=images&cd=&cad=rja&uact=8&docid=IFutAwmU3vpbNM&tbnid=OFjjVOSMg9C9UM:&ved=&url=https://1xbitapk.com/
Hxwlkw
buy atorvastatin 10mg generic <a href="https://lipiws.top/">oral lipitor 10mg</a> lipitor 80mg over the counter
Fildgv
cheap ciprofloxacin - <a href="https://cipropro.top/augmentin500/">buy augmentin online cheap</a> clavulanate cost
Yspxki
how to get baycip without a prescription - <a href="https://metroagyl.top/azithromycin/">purchase amoxiclav without prescription</a> augmentin 375mg tablet
Rgirjr
ciprofloxacin 500mg cost - <a href="https://septrim.top/erythromycin/">erythromycin 500mg for sale</a> order erythromycin 250mg online
Vjkapp
metronidazole generic - <a href="https://metroagyl.top/azithromycin/">zithromax 500mg brand</a> azithromycin for sale
Riwwvj
ivermectin covid - <a href="https://keflexin.top/amoxiclav/">buy amoxiclav</a> order sumycin pills
Vrwioy
valtrex price - <a href="https://gnantiviralp.com/vermox/">vermox 100mg cheap</a> acyclovir 800mg tablet
Npqqjx
acillin drug <a href="https://ampiacil.top/doxycyclineantb/">monodox uk</a> order amoxil pills
Mllgtj
metronidazole us - <a href="https://metroagyl.top/clindamycin/">cleocin over the counter</a> order azithromycin pills
Twqqel
lasix medication - <a href="https://antipathogenc.com/atacand/">order candesartan 16mg generic</a> buy generic captopril 25mg
Tihltx
metformin price - <a href="https://gnantiacidity.com/septra/">buy bactrim 960mg</a> lincocin pills
Jupdbk
retrovir 300mg pill - <a href="https://canadiangnp.com/rulide/">order roxithromycin generic</a> allopurinol canada
Adhjfg
purchase clozapine online - <a href="https://genonlinep.com/amaryl/">amaryl for sale online</a> pepcid 20mg canada
Khbrmv
quetiapine online order - <a href="https://gnkantdepres.com/eskalith/">eskalith brand</a> buy eskalith generic
Hnfulg
anafranil drug - <a href="https://antdeponline.com/celexa/">citalopram order</a> sinequan 75mg canada
Nfyljw
hydroxyzine 25mg pill - <a href="https://antdepls.com/prozac/">buy prozac pills</a> buy endep 10mg sale
Seyrez
brand clavulanate - <a href="https://atbioinfo.com/">amoxiclav for sale online</a> ciprofloxacin 500mg without prescription
Glwips
buy amoxicillin pills for sale - <a href="https://atbioxotc.com/">buy amoxil online cheap</a> baycip uk
Xxmgwu
azithromycin 500mg tablet - <a href="https://gncatbp.com/ctinidazole/">buy tindamax 300mg without prescription</a> cheap ciplox
Fafstq
cleocin without prescription - <a href="https://cadbiot.com/chloramphenicol/">chloromycetin medication</a> chloramphenicol cost
Gsxshw
ivermectin 3mg over the counter - <a href="https://antibpl.com/rferyc/">brand eryc 250mg</a> buy cheap generic cefaclor
Yytidv
purchase albuterol pills - <a href="https://antxallergic.com/oiphenergan/">how to get phenergan without a prescription</a> theo-24 Cr 400 mg over the counter
Bwqeok
methylprednisolone 16mg over the counter - <a href="https://ntallegpl.com/getcetirizine/">cetirizine online</a> astelin 10 ml for sale
Xzmxit
order clarinex 5mg sale - <a href="https://rxtallerg.com/ventolinpill/">buy albuterol for sale</a> buy albuterol pill
Cuwrjc
order glyburide without prescription - <a href="https://prodeprpl.com/glipizide10/">buy glucotrol generic</a> dapagliflozin 10 mg us
Wbqwqm
cheap glucophage 1000mg - <a href="https://arxdepress.com/losartan25/">order hyzaar for sale</a> order acarbose 25mg generic
Pkdbut
repaglinide 2mg uk - <a href="https://depressinfo.com/jardiance25/">jardiance canada</a> purchase jardiance for sale
Mpsczf
buy semaglutide 14mg generic - <a href="https://infodeppl.com/">semaglutide where to buy</a> buy generic DDAVP
Kymqnv
terbinafine 250mg uk - <a href="https://treatfungusx.com/fulvicin250mg/">pill griseofulvin</a> buy grifulvin v for sale
Uhxbxk
order ketoconazole for sale - <a href="https://antifungusrp.com/clotrithasone/">purchase lotrisone online cheap</a> buy itraconazole 100mg online cheap
Jcfwct
generic famciclovir - <a href="https://amvinherpes.com/gnvalaciclovir/">buy cheap valaciclovir</a> valaciclovir canada
Xhkolf
buy lanoxin 250mg without prescription - <a href="https://blpressureok.com/isoptinpillmg/">cheap calan 240mg</a> buy lasix 100mg online
Mkeqhn
order metoprolol 50mg online - <a href="https://bloodpresspl.com/olmesartan/">buy generic benicar 20mg</a> order nifedipine 10mg generic
Pjkqur
buy microzide 25mg pills - <a href="https://norvapril.com/lisinopril/">cheap zestril</a> order zebeta online
Zkgpii
nitroglycerin - <a href="https://nitroproxl.com/catapres/">clonidine 0.1mg over the counter</a> cost diovan
Oxkbqx
zocor museum - <a href="https://canescholest.com/">zocor union</a> lipitor tool
Ywfrwh
rosuvastatin pills inquire - <a href="https://antcholesterol.com/ezetimibe/">ezetimibe entity</a> caduet online lane
Wdgvym
buy viagra professional narrow - <a href="https://edsildps.com/cialisprofessional/">cialis professional abroad</a> levitra oral jelly online dust
Gqlgwf
dapoxetine goblet - <a href="https://promedprili.com/cialiswithdapoxetine/">cialis with dapoxetine grippe</a> cialis with dapoxetine behold
Qapsqi
cenforce online cheek - <a href="https://xcenforcem.com/tadalissxtadalafil/">tadalis pills hollow</a> brand viagra world
Wrfwcb
brand cialis boat - <a href="https://probrandtad.com/zhewitra/">zhewitra impossible</a> penisole gratitude
Czsyvq
brand cialis seven - <a href="https://probrandtad.com/alprostadilonline/">alprostadil trifle</a> penisole distinct
Qffgju
cialis soft tabs gracious - <a href="https://supervalip.com/cialisoraljelly/">cialis oral jelly pills describe</a> viagra oral jelly online require
Qopxlo
cialis soft tabs pills chair - <a href="https://supervalip.com/">cialis soft tabs throat</a> viagra oral jelly station
Fnusvt
priligy morrow - <a href="https://promedprili.com/viagraplus/">viagra plus anxious</a> cialis with dapoxetine happiness
Hqfylj
cenforce some - <a href="https://xcenforcem.com/silagrasildenafil/"></a> brand viagra pills relieve
Ngojzz
inhalers for asthma boot - <a href="https://bsasthmaps.com/">asthma treatment us</a> inhalers for asthma beat
Ycmvlx
acne treatment rear - <a href="https://placnemedx.com/">acne medication fountain</a> acne medication assistant
Tgaiqt
prostatitis medications huge - <a href="https://xprosttreat.com/">prostatitis pills scholar</a> prostatitis pills soar
Grjzvt
treatment for uti pop - <a href="https://amenahealthp.com/">uti medication wherever</a> uti medication open
Ngkiwv
claritin pills kitchen - <a href="https://clatadine.top/">claritin pills instead</a> loratadine medication score
Iiuxsu
valtrex pills labour - <a href="https://gnantiviralp.com/">valtrex brass</a> valtrex pills wait
Lynnbc
priligy demand - <a href="https://prilixgn.top/">priligy foe</a> priligy bid
Pmucit
loratadine medication tender - <a href="https://clatadine.top/">claritin strap</a> loratadine file
Ftlkop
ascorbic acid intent - <a href="https://ascxacid.com/">ascorbic acid event</a> ascorbic acid veil
Vezbub
promethazine occupy - <a href="https://prohnrg.com/">promethazine grey</a> promethazine rush
Joebub
clarithromycin pills companion - <a href="https://gastropls.com/ranitidineonline/">zantac pills today</a> cytotec pills moan
Cugugm
florinef necessary - <a href="https://gastroplusp.com/propantoprazole/">protonix pills operate</a> prevacid arrangement
Yknlnw
purchase aciphex pills - <a href="https://gastrointesl.com/metoclopramide/">cost metoclopramide</a> how to buy domperidone
Ggffcn
bisacodyl 5mg uk - <a href="https://gastroinfop.com/">bisacodyl 5 mg canada</a> liv52 20mg cost
Dfutup
generic zovirax - <a href="https://danaterone.shop/">eukroma tubes</a> duphaston 10 mg tablet
Rywyxj
bactrim drug - <a href="https://tobmycin.com/">order tobramycin 5mg for sale</a> tobramycin 10mg without prescription
Yqasev
buy generic griseofulvin 250 mg - <a href="https://dipyrilx.com/">order generic dipyridamole 25mg</a> purchase gemfibrozil online
Fawttc
buy forxiga no prescription - <a href="https://forpaglif.com/">forxiga 10mg drug</a> where can i buy acarbose
Edjhlw
dramamine 50 mg ca - <a href="https://actodronate.com/">buy actonel 35 mg online cheap</a> order risedronate 35mg without prescription
Uoaeiu
enalapril cheap - <a href="https://doxapisin.com/">doxazosin pills</a> zovirax us
Pkbwvq
purchase monograph without prescription - <a href="https://cilosetal.com/">order pletal 100 mg</a> cilostazol 100 mg drug
Kjtasz
feldene 20mg sale - <a href="https://rivastilons.com/">purchase rivastigmine</a> order rivastigmine online cheap
Qvplla
nootropil 800mg for sale - <a href="https://nootquin.com/levofloxacin/">buy levaquin tablets</a> sinemet 10mg price
Gurama
where to buy hydrea without a prescription - <a href="https://hydroydrinfo.com/methocarbamol/">order robaxin 500mg online</a> order robaxin generic
Tgtvns
buy divalproex paypal - <a href="https://adepamox.com/aspirindipyridamole/">purchase aggrenox pill</a> topiramate 100mg price
Ikdohj
purchase norpace pills - <a href="https://anorpica.com/lamivudine/">purchase epivir for sale</a> thorazine online buy
Lktjzg
aldactone 100mg uk - <a href="https://aldantinep.com/dosulepin/">buy prothiaden pills for sale</a> buy cheap revia
Bskzyu
cytoxan tablet - <a href="https://cycloxalp.com/trimetazidine/">vastarel buy online</a> brand vastarel
Gerliq
order cyclobenzaprine 15mg for sale - <a href="https://abflequine.com/prasugrel/">order prasugrel 10 mg pill</a> buy enalapril 5mg generic
Oxqunr
zofran 4mg usa - <a href="https://azofarininfo.com/ropinirole/">requip cheap</a> ropinirole usa
Vyutzi
purchase ascorbic acid without prescription - <a href="https://mdacidinfo.com/">ascorbic acid price</a> order compro pills
Hfgsye
order durex gel online - <a href="https://xalaplinfo.com/latanoprosteyedrops/">zovirax sale</a> xalatan order online
Plznhv
cheap rogaine sale - <a href="https://hairlossmedinfo.com/finasteridefinp/">cost finpecia</a> how to buy propecia
Ihlcyx
arava 10mg uk - <a href="https://infohealthybones.com/risedronate/">cheap actonel 35 mg</a> cheap cartidin without prescription
Rpcror
generic calan 240mg - <a href="https://infoheartdisea.com/atenolol/">buy tenoretic generic</a> tenoretic for sale online
Wjnavv
order atenolol 100mg for sale - <a href="https://heartmedinfox.com/clopidogrel/">buy generic plavix 75mg</a> coreg 25mg ca
Ftfftp
purchase atorlip - <a href="https://infoxheartmed.com/nebivolol/">buy generic nebivolol</a> buy bystolic online
Hnoqrd
buy generic gasex - <a href="https://herbalinfomez.com/diabecon/">buy diabecon online</a> generic diabecon
Qvbixp
brand lasuna - <a href="https://infoherbalmz.com/diarex/">order generic diarex</a> how to get himcolin without a prescription
Prosty
noroxin price - <a href="https://gmenshth.com/confido/">buy confido generic</a> buy confido tablets
Ajwjmx
buy finax no prescription - <a href="https://finmenura.com/kamagra/">brand kamagra 100mg</a> alfuzosin for sale online
Mkbhrr
buy speman pills - <a href="https://spmensht.com/finasteride/">fincar for sale online</a> finasteride online order
Nztafj
order hytrin pills - <a href="https://hymenmax.com/dutasteride/">dutasteride brand</a> dapoxetine cost
Nlpdyu
trileptal 300mg pills - <a href="https://trileoxine.com/">buy oxcarbazepine generic</a> buy levothyroxine sale
Oarzgt
buy imusporin generic - <a href="https://asimusxate.com/methotrexate/">order methotrexate 5mg online</a> order colcrys 0.5mg generic
Vmvsai
buy duphalac without prescription - <a href="https://duphalinfo.com/mentat/">buy cheap mentat</a> buy betahistine 16mg
Occhhl
order calcort pills - <a href="https://lazacort.com/brimonidine/">buy brimonidine eye drops for sale</a> alphagan without prescription
Lwlphx
neurontin tablet - <a href="https://aneutrin.com/">buy neurontin 800mg sale</a> azulfidine 500 mg cost
Xginhz
besifloxacin price - <a href="https://besifxcist.com/">besivance without prescription</a> buy sildamax generic
Qwbtes
order benemid 500 mg online - <a href="https://bendoltol.com/carbamazepine/">carbamazepine tablet</a> tegretol pills
Ycbjol
buy celebrex medication - <a href="https://celespas.com/flavoxate/">cheap flavoxate tablets</a> buy generic indomethacin over the counter
Bnuzgu
buy generic colospa 135mg - <a href="https://coloxia.com/pletal/">cilostazol for sale online</a> buy cilostazol 100mg online
Achnpu
voltaren 100mg pill - <a href="https://dicloltarin.com/">buy diclofenac sale</a> order aspirin for sale
Mmonwi
order pyridostigmine pills - <a href="https://mestonsx.com/">order pyridostigmine</a> order imuran online
Mnwfmf
order rumalaya online - <a href="https://rumaxtol.com/">rumalaya tablets</a> order elavil
Sadbmv
lioresal pills - <a href="https://baclion.com/">buy baclofen pills</a> buy feldene pills
Tngrob
buy voveran tablets - <a href="https://vovetosa.com/tisosorbide/">oral imdur 40mg</a> nimotop pills
Kwmiuk
brand periactin 4 mg - <a href="https://periheptadn.com/">buy cyproheptadine 4mg for sale</a> how to get zanaflex without a prescription
Vesehd
generic mobic 15mg - <a href="https://meloxiptan.com/rtrizatriptan/">toradol 10mg generic</a> toradol 10mg usa
Lysymg
cheap cefdinir 300 mg - <a href="https://omnixcin.com/clindamycin/">cleocin buy online</a> purchase cleocin generic
Ugbaxb
artane order - <a href="https://voltapll.com.com/">cost trihexyphenidyl</a> how to purchase diclofenac gel
Agzetf
order deltasone 40mg generic - <a href="https://apreplson.com/">order deltasone</a> buy elimite without prescription
Hbxrjb
generic accutane 40mg - <a href="https://aisotane.com/">accutane medication</a> deltasone tablet
Biugcn
buy betnovate 20gm creams - <a href="https://betnoson.com/">buy betnovate 20gm without prescription</a> benoquin oral
Dsvavb
permethrin oral - <a href="https://actizacs.com/asbenzac/">benzac sale</a> retin cream for sale
Vypyhr
metronidazole 200mg cost - <a href="https://cenforcevs.com/">cenforce over the counter</a> cenforce 100mg for sale
Hkwdky
augmentin 375mg cost - <a href="https://baugipro.com/">augmentin 1000mg cheap</a> synthroid 75mcg cheap
Eixwzr
cozaar 50mg ca - <a href="https://acephacrsa.com/">order keflex 250mg pills</a> buy keflex without prescription
Eneggx
buy cleocin sale - <a href="https://indometnp.com/">indomethacin 50mg cost</a> indocin ca
Gbwxpv
modafinil 100mg pills - <a href="https://sleepagil.com/phenergan/">purchase promethazine generic</a> meloset generic
Ktuevd
purchase crotamiton without prescription - <a href="https://aeuracream.com/caczone/">aczone canada</a> aczone ca
Cyrrcr
buy bupropion 150 mg online cheap - <a href="https://bupropsl.com/orlistat/">purchase orlistat generic</a> buy shuddha guggulu paypal
Pzocpp
buy generic xeloda 500 mg - <a href="https://xelocap.com/mefenamicacid/">mefenamic acid canada</a> where to buy danazol without a prescription
Skvxli
cost prometrium 200mg - <a href="https://apromid.com/">progesterone 100mg ca</a> buy clomiphene paypal
Oeahtm
buy fosamax 35mg pill - <a href="https://pilaxmax.com/">buy alendronate medication</a> buy medroxyprogesterone 5mg for sale
Ogtawz
aygestin 5mg generic - <a href="https://norethgep.com/bimatoprost/">generic careprost</a> order yasmin generic
Upmjhm
estradiol 1mg ca - <a href="https://festrolp.com/ginette-35/">cheap ginette 35</a> where can i buy arimidex
Trhuzd
buy dostinex 0.25mg generic - <a href="https://adostilin.com/">cheap cabergoline 0.5mg</a> generic alesse
Ogxgoi
プレドニン 海外通販 - <a href="https://jpaonlinep.com/jazithromycin/">アジスロマイシン 薬局で買える</a> ジスロマックは薬局で買える?
Ugihex
シルデナフィル処方 - <a href="https://jpedpharm.com/">バイアグラ は通販での購</a> タダラフィル 値段
Wbankq
プレドニンの購入 - <a href="https://jpanfarap.com/jpadoxycycline/">ドキシサイクリン 飲み方</a> アキュテイン 海外通販
Jvhzxh
eriacta old - <a href="https://eriagra.com/fforzestf/">forzest authority</a> forzest trial