如何使用Powershell创建mongoDB用户?

时间:2017-06-07 15:44:44

标签: mongodb powershell mongodb-.net-driver

我正在尝试编写一个脚本,在mongoDB 3.0副本集的admin数据库中创建用户。

经过大量阅读和许多尝试使用不同版本的c-sharp MongoDB驱动程序后,我终于能够将以下代码组合在一起,该代码能够成功记录到副本集中,访问admin数据库,写出system集合的全名:

try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.Core.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Bson.dll'

    $connectionString = "mongodb://username:password@primary:27017,secondary:27017,arbiter:27017/admin?replicaSet=name&authSource=admin"
    $dbName =  "admin"
    $collectionName =  "System"

    function Get-MongoDBDatabase ($connectionString, $db) {
        $mongoClient = New-Object MongoDB.Driver.MongoClient($connectionString)
        $mongoServer = $mongoClient.GetServer()
        $mongoServer.GetDatabase($db)
    }

    [MongoDB.Driver.MongoDatabase] $mongoDatabase = Get-MongoDBDatabase $connectionString $dbName
    [MongoDB.Driver.MongoCollection] $mongoCollection = $mongoDatabase.GetCollection($collectionName)

    Write-Output "Test accessing collection: $($mongoCollection.FullName)"
}
catch {
    Write-Output "Error: $($_.Exception.Message)" 
}

此时我不清楚在admin数据库中创建新用户的方向,并为该用户分配一些角色。

db.createUser( 
   { 
     user: "testUser", 
     pwd: "abc123", 
     roles: [  
        {role:"read", db:"admin"},  
        {role:"readWrite", db:"databaseOne"}, 
        {role:"readWrite", db:"databaseTwo"}, 
        {role:"readWrite", db:"databaseThree"}, 
        {role:"readWrite", db:"databaseFour"}, 
        {role:"read", db:"config"}] 
   } 
)

以上是我希望能够在admin数据库上执行的命令/查询,但我需要您的帮助以了解如何使用MongoDB C-Sharp驱动程序v.2.0将其转换为Powershell 0.2

1 个答案:

答案 0 :(得分:0)

好的,我找到了一种方法来完成这项工作,不仅仅是在Powershell中。

按照@PeteGarafano的建议,我决定在一个简单的Visual Studio类库中使用最新最好的驱动程序(版本2.4.3.23,通过NuGet下载)。

由于这只是一个测试,目前代码非常粗糙并且充满了硬编码的东西(例如分配给用户的角色)

以下是类库的代码:

using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBUtilities
{
    public class Connectivity
    {
        public bool DoesUserExist(string connectionString, string databaseName, string username)
        {
            try
            {
                var command = @" { usersInfo: { user: '" + username + @"', db: 'admin' } } ";

                var result = runCommand(connectionString, databaseName, command);
                var users = result["users"];
                if(users != null) 
                {
                    var usersArray = users.AsBsonArray;
                    if(usersArray.Count > 0) {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public string CreateUser(string connectionString, string databaseName, string username, string password)
        {
            try
            {
                var command = @"{ 
                      createUser: '" + username + @"',
                      pwd: '" + password + @"',
                      roles: [
                          { role: 'read', db: 'admin'},  
                          { role: 'read', db: 'someDB'},  
                          { role: 'read', db: 'someOtherDB'}] 
                    }";

                var result = runCommand(connectionString, databaseName, command);
                return result.ToJson().ToString();
            }
            catch (Exception ex) {
                return unfoldException(ex);
            }
        }

        private BsonDocument runCommand(string connectionString, string databaseName, string command)
        {
            var database = getDatabase(connectionString, databaseName);
            var task = database.RunCommandAsync<BsonDocument>(command);
            var result = task.Result;
            return result;
        }

        private IMongoDatabase getDatabase(string connectionString, string databaseName) {
            IMongoClient client;
            client = new MongoClient(connectionString);
            return client.GetDatabase(databaseName);
        }

        private string unfoldException(Exception ex) {
            string message = ex.Message + Environment.NewLine;
            Exception currentException = ex;
            while (currentException.InnerException != null)
            {
                currentException = currentException.InnerException;
                message += currentException.Message + Environment.NewLine;
            }
            return message;
        }
    }
}

真的没什么好看的,但重点是如何使用 MongoDB官方参考文档中描述的任何命令的JSON形式(例如:{ {3}})。

注意还有另一种方法可以构建 BsonDocument 对象,但我发现它不太直观,因为引用使用了所有JSON语法。

接下来,我在我的PS脚本中使用了这个库。这是一个例子:

try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB\MongoDBUtilities.dll'

    $connectionString = "mongodb://username:password@primaryServerName:27017,secondaryServerName:27017,arbiterServerName:27017/admin?replicaSet=replicaSetName&authSource=admin"
    $conn = New-Object -TypeName MongoDBUtilities.Connectivity
    if($conn.DoesUserExist($connectionString, "admin", "testUser")) {
        Write-Output "User already exists, no need to create again"
    }
    else {
        Write-Output "Creating user...";
        $result = $conn.CreateUser($connectionString, "admin", "testUser", "test")
        Write-Output $result;
    }
}
catch {
    Write-Output "Error: $($_.Exception.Message)" 
}

此示例首先检查用户是否已经在admin数据库中,如果用户已经在那里,则会创建它。

我希望这对于尝试在C#或Powershell中做任何类似事情的人都有用。