{"role": "dbOwner", "db": db_name}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @mail    : lshan523@163.com
# @Time    : 2024/12/19 17:16
# @Author  : Sea
# @File    : BatchAddUserForDbs.py# @Purpose :
# @history : 
# ****************************
import pymongo
from pymongo.errors import OperationFailure
# 连接到 MongoDB
client = pymongo.MongoClient("mongodb://root:root@192.168.118.59:27017/")
# 获取所有数据库名称
db_names = client.list_database_names()
# 要创建的用户信息
username = "myUser"  # 用户名
password = "yourPsd"  # 密码

# 循环遍历所有数据库并创建用户
for db_name in db_names:
    # 选择当前数据库
    db = client[db_name]

    # 定义角色数组,包括所有权限
    roles = [
        {"role": "readWrite", "db": db_name},
        {"role": "dbAdmin", "db": db_name},
        {"role": "userAdmin", "db": db_name},
        {"role": "dbOwner", "db": db_name},   # 数据库拥有者权限  
        {"role": "clusterAdmin", "db": "admin"},  # 如果需要更高的权限
    ]
    try:
        # 创建用户
        db.command("createUser", username, pwd=password, roles=roles)
        print(f"用户 '{username}' 在数据库 '{db_name}' 创建成功。")
    except OperationFailure as e:
        print(f"创建用户 '{username}' 在数据库 '{db_name}' 时发生错误: {e}")
    except Exception as e:
        print(f"在数据库 '{db_name}' 创建用户时发生未知错误: {e}")
    # 关闭连接
client.close()

 

 

posted on 2024-12-19 17:41  lshan  阅读(3)  评论(0编辑  收藏  举报