MongoDB Plugin Design: Command pipe

 

UniServer 6-Carbo
MongoDB plugin design.

Command pipe

Some Mongo commands are specific to the client and need to be directly entered. To automate this requires use of a command pipe. A file is first created containing list of commands to be executes and this is piped to the client.

This page looks at commands requiring this technique they only apply to an authentication server.

Create a database and assign a user

Creating a database in Monogo is simple select the database (this prepares it for creation) write something to it (assign a user) it really is that easy.

Define a new constant in file mongo_db_inc.php path to temporary command file.

define("CMD_DUMMY_TXT",      "$mongo_base_f/usr/local/mongo_tutorial/bin/cmd_dummy.txt");

Top

Create a new batch file z_create_db_auth.bat with the following content:

TITLE UNIFORM SERVER - Create DB Auth
COLOR B0
@echo off
cls
cd ..\..\php
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\z_create_db_auth.php
pause
EXIT

Create a new test script z_create_db_auth.php with the following content:

<?php
chdir(dirname(__FILE__)); // Change wd to this files location
include_once "mongo_db_inc.php";

create_db_auth("mpg777","fredAAA","fred123");

//=== CREATE DB Auth ==========================================================
// Create DB and assign user

function create_db_auth($db_name,$user_name,$user_password){
  $port = get_mongo_port_auth();       // Get port from config
  $a_pwd_array = get_name_pwd_array(); // Get Admin name and password from file
  $name = $a_pwd_array[0];             // Set name 
  $password =  $a_pwd_array[1];        // Set password

  $return_wd = getcwd();               // Save current wd 
  chdir(MONGO_BIN);                    // Change wd to Mongo Bin

  // Create content for cmd_dummy.txt
  $cmd_dummy[] = "use $db_name\n";
  $cmd_dummy[] = "db.addUser(\"$user_name\", \"$user_password\")\n";
  $str = implode($cmd_dummy);                 // Convert array to string
  file_put_contents(CMD_DUMMY_TXT,$str);      // Save to file

   // Build command line
  $cmd1 = "mongo.exe ";
  $cmd2 = "--port $port ";
  $cmd3 = "--username $name ";
  $cmd4 = "--password $password ";
  $cmd5 = ' admin < '.CMD_DUMMY_TXT;  // pipe file

  $cmd=$cmd1.$cmd2.$cmd3.$cmd4.$cmd5;
  //print $cmd; // Test code

  exec($cmd,$dummy,$return);    // Run command 

  chdir($return_wd);            // Restore original wd
}
//===================================================== END CREATE DB Auth ====
?>

Initial:

  • Function reads validation information from configuration files.
  • Saves current working directory.
  • Changes current working directory to Mongo bin

Command file:

  • Dummy file array is created containing:
  • Selects database to create – Preparation
  • Assigns user to this database – Creates the database
  • Array is converted to a string and saved to file.

Authentication:

  • Command string is created
  • String contains authentication parameters
  • $cmd5 pipes “<” dummy file to Mongo client

Final:

  • Command is executed.
  • Original working directory restored

Top

Test

  1. Run Run_mongo_auth.bat
  2. Run z_create_db_auth.bat
  3. Run z_list_dbs.bat
  4. Change function parameters create_db_auth()
  5. Repeat steps 2 and 3 confirm new database created.

Cut and copy above function save to file mongo_db_inc.php

Top

Get user assigned to database

An admin may wish to check or delete a user assigned to a database. Generally a single user is assigned to a database however it is possible to have more users hence this function returns an array of users.

db.system.users.find()

Output from db.system.users.find() looks similar to this:

url: admin
connecting to: 127.0.0.1:27017/admin
type "exit" to exit
type "help" for help
> switched to db admin
> { "_id" : ObjectId("4c3dc5877a3d000000002f42"), "user" : "root", "readOnly" : false, "pwd" : "2a8025f0885adad5a8ce0044
070032b3" }
{ "_id" : ObjectId("4c3f3c85c36e0000000059a5"), "user" : "root123", "readOnly" : false, "pwd" : "bedd87b3d27bc223dd224e7
dd842192f" }
{ "_id" : ObjectId("4c41c18ba95a000000007ec9"), "user" : "fred", "readOnly" : false, "pwd" : "b61fbaa42c4d6ed46fea2b0d27

We want to target the following user/name pairs "user" : "root", extracting only the name.

The following regx \"user\"[ ]*:[ ]*\"(.*)\"[ ]*, can be used,

  • \"user\" Targets "user" must be exact match
  • [ ]* Target zero or more spaces
  • : Target colon must be exact match
  • [ ]*\" Targets one or more spaces and quote
  • (.*) Brackets save what is matched .* zero or more characters
  • \"[ ]*, Targets quote one or more spaces and a comma

New batch file:

Create a new batch file z_get_user_auth.bat with the following content:

:mode con:cols=65 lines=20
TITLE UNIFORM SERVER - Mongo Auth
COLOR B0
@echo off
cls
cd ..\..\php
php.exe -c php-cli.ini ..\mongo\a_test\z_get_user_auth.php
pause
EXIT

Create a new test script z_get_user_auth.php with the following content:

<?php
chdir(dirname(__FILE__)); // Change wd to this files location
include_once "mongo_db_inc.php";

$new_array = get_user_auth("mpg777");
print_r($new_array);

$new_array2 = get_user_auth("admin");
print_r($new_array2);

//=== GET USER Auth ===========================================================
// Select a db and obtain user/s asigned to it

function get_user_auth($db_name){
  $port = get_mongo_port_auth();       // Get port from config
  $a_pwd_array = get_name_pwd_array(); // Get Admin name and password from file
  $name = $a_pwd_array[0];             // Set name 
  $password =  $a_pwd_array[1];        // Set password

  $return_wd = getcwd();               // Save current wd 
  chdir(MONGO_BIN);                    // Change wd to Mongo Bin

  // Create content for cmd_dummy.txt
  $cmd_dummy[] = "use $db_name\n";
  $cmd_dummy[] = "db.system.users.find()\n"; // List of users
  $str = implode($cmd_dummy);                // Convert array to string
  file_put_contents(CMD_DUMMY_TXT,$str);     // Save to file

   // Build command line
  $cmd1 = "mongo.exe ";
  $cmd2 = "--port $port ";
  $cmd3 = "--username $name ";
  $cmd4 = "--password $password ";
  $cmd5 = ' admin < '.CMD_DUMMY_TXT;       // pipe file

  $cmd=$cmd1.$cmd2.$cmd3.$cmd4.$cmd5;
  //print $cmd; // Test code

  exec($cmd,$dummy,$return);               // Run command 
                                           // $dummy array returned all output 
  foreach($dummy as $text){                // Scan $dummy array 
   // print "$text\n"; // Test code

   // test each line for match 
   if(preg_match("/\"user\"[ ]*:[ ]*\"(.*)\"[ ]*,/", $text,$match)){ 
     $new_array[] = $match[1];    // match found assign to array
   }
  }                               // repeate for next line

  chdir($return_wd);              // Restore original wd
  return $new_array;              // Return array of users
}
//======================================================= END GET USER Auth ===
?>

Initial:

  • Function reads validation information from configuration files.
  • Saves current working directory.
  • Changes current working directory to Mongo bin

Command file:

  • Dummy file array is created containing:
  • Selects database to use
  • List user/s assigned to selected database
  • Array is converted to a string and saved to file.

Authentication:

  • Command string is created
  • String contains authentication parameters
  • $cmd5 pipes “<” dummy file to Mongo client

Final:

  • Command is executed
  • All output is assigned to array $dummy
  • This array is scanned line-by-line
  • Each line is tested with regx for a match
  • On finding a match that user is assigned to new_array
  • Working directory is restored
  • User array is returned

Top

Test

  1. Run Run_mongo_auth.bat
  2. Run z_get_user_auth.bat
  3. Change function parameters get_user_auth("admin")
  4. Repeat steps 2 and 3 confirm users assigned to database is displayed

Cut and copy above function save to file mongo_db_inc.php Top

Delete User

To delete a user from currently selected database run the following command:

db.system.users.remove({user: "fred123"}) 

Top New batch file:

Create a new batch file z_delete_user_auth.bat with the following content:

TITLE UNIFORM SERVER - Delete a User Auth
COLOR B0
@echo off
cls
cd ..\..\php
php.exe -c mongo_tutorial_cli.ini ..\mongo_tutorial\a_test\z_delete_user_auth.php
pause
EXIT

Create a new test script z_delete_user_auth..php with the following content:

<?php
chdir(dirname(__FILE__)); // Change wd to this files location
include_once "mongo_db_inc.php";

delete_user_auth("admin","fred");


//=== DELETE USER Auth ========================================================
// Select database and delete user

function delete_user_auth($db_name,$user_name){
  $port = get_mongo_port_auth();       // Get port from config
  $a_pwd_array = get_name_pwd_array(); // Get Admin name and password from file
  $name = $a_pwd_array[0];             // Set name 
  $password =  $a_pwd_array[1];        // Set password

  $return_wd = getcwd();               // Save current wd 
  chdir(MONGO_BIN);                    // Change wd to Mongo Bin

  // Create content for cmd_dummy.txt
  $cmd_dummy[] = "use $db_name\n";            // Select database
  $cmd_dummy[] = "db.system.users.remove({user: \"$user_name\"}) \n";
  $str = implode($cmd_dummy);                 // Convert array to string
  file_put_contents(CMD_DUMMY_TXT,$str);      // Save to file

   // Build command line
  $cmd1 = "mongo.exe ";
  $cmd2 = "--port $port ";
  $cmd3 = "--username $name ";
  $cmd4 = "--password $password ";
  $cmd5 = ' admin < '.CMD_DUMMY_TXT;  // pipe file

  $cmd=$cmd1.$cmd2.$cmd3.$cmd4.$cmd5;
  //print $cmd; // Test code

  exec($cmd,$dummy,$return);    // Run command 

  chdir($return_wd);            // Restore original wd
}
//=================================================== END DELETE USER Auth ====
?>

Initial:

  • Function reads validation information from configuration files.
  • Saves current working directory.
  • Changes current working directory to Mongo bin

Command file:

  • Dummy file array is created containing:
  • Selects database to use
  • Command to delete a user
  • Array is converted to a string and saved to file.

Authentication:

  • Command string is created
  • String contains authentication parameters
  • $cmd5 pipes “<” dummy file to Mongo client

Final:

  • Command is executed.
  • Original working directory restored

Top

Test

  1. Run Run_mongo_auth.bat
  2. Run z_delete_user_auth.bat
  3. Run z_get_user_auth.bat
  4. Confirm user is deleted

Cut and copy above function save to file mongo_db_inc.php

Top

Summary

I apologise for such a long tutorial detail provided was for users new to PHP CLI scripting.

Currently we have a file mongo_db_inc.php containing a set of functions that can be applied to running MongoDB either with or without authentication.

These functions are run-able using a batch file and PHP script each specific task such as start and stop servers require a separate batch file and corresponding script.

Advantages you can avoid creating short cuts or opening a command prompt and navigating to the bin folder.


Top