[SCM] Samba Shared Repository - branch master updated

Alexander Bokovoy ab at samba.org
Wed Jul 5 15:54:02 UTC 2017


The branch, master has been updated
       via  e3707c1 Add code to run the tests for 'samba-tool user edit'
       via  3c03ac7 Add test for 'samba-tool user edit'
       via  2ab239b Easily edit a users object in AD, as if using ldbedit.
      from  79faf30 auth/spnego: pass spnego_in to gensec_spnego_parse_negTokenInit()

https://git.samba.org/?p=samba.git;a=shortlog;h=master


- Log -----------------------------------------------------------------
commit e3707c1b19a27d431722e1b355dc39a39f7f8f1c
Author: Rowland Penny <rpenny at samba.org>
Date:   Tue Jul 4 15:07:53 2017 +0100

    Add code to run the tests for 'samba-tool user edit'
    
    Signed-off-by: Rowland Penny <rpenny at samba.org>
    Reviewed-by: Alexander Bokovoy <ab at samba.org>
    
    Autobuild-User(master): Alexander Bokovoy <ab at samba.org>
    Autobuild-Date(master): Wed Jul  5 17:53:24 CEST 2017 on sn-devel-144

commit 3c03ac750f4dea00da21f21302beeaf5b12a35b8
Author: Rowland Penny <rpenny at samba.org>
Date:   Tue Jul 4 15:04:36 2017 +0100

    Add test for 'samba-tool user edit'
    
    Signed-off-by: Rowland Penny <rpenny at samba.org>
    Reviewed-by: Alexander Bokovoy <ab at samba.org>

commit 2ab239be0d69389b451816ec72d548d1156e495b
Author: Rowland Penny <rpenny at samba.org>
Date:   Tue Jul 4 15:00:58 2017 +0100

    Easily edit a users object in AD, as if using ldbedit.
    
    Signed-off-by: Rowland Penny <rpenny at samba.org>
    Reviewed-by: Alexander Bokovoy <ab at samba.org>

-----------------------------------------------------------------------

Summary of changes:
 python/samba/netcmd/user.py           | 139 +++++++++++++++++++++++++++++++++-
 python/samba/tests/samba_tool/edit.sh |  72 ++++++++++++++++++
 source4/selftest/tests.py             |   4 +
 3 files changed, 214 insertions(+), 1 deletion(-)
 create mode 100755 python/samba/tests/samba_tool/edit.sh


Changeset truncated at 500 lines:

diff --git a/python/samba/netcmd/user.py b/python/samba/netcmd/user.py
index 53ac39f..3b744a3 100644
--- a/python/samba/netcmd/user.py
+++ b/python/samba/netcmd/user.py
@@ -21,6 +21,9 @@ import samba.getopt as options
 import ldb
 import pwd
 import os
+import re
+import tempfile
+import difflib
 import sys
 import fcntl
 import signal
@@ -28,7 +31,7 @@ import errno
 import time
 import base64
 import binascii
-from subprocess import Popen, PIPE, STDOUT
+from subprocess import Popen, PIPE, STDOUT, check_call, CalledProcessError
 from getpass import getpass
 from samba.auth import system_session
 from samba.samdb import SamDB
@@ -2283,6 +2286,139 @@ samba-tool user syncpasswords --terminate \\
         update_pid(None)
         return
 
+class cmd_user_edit(Command):
+    """Modify User AD object.
+
+This command will allow editing of a user account in the Active Directory
+domain. You will then be able to add or change attributes and their values.
+
+The username specified on the command is the sAMAccountName.
+
+The command may be run from the root userid or another authorized userid.
+
+The -H or --URL= option can be used to execute the command against a remote
+server.
+
+Example1:
+samba-tool user edit User1 -H ldap://samba.samdom.example.com \
+-U administrator --password=passw1rd
+
+Example1 shows how to edit a users attributes in the domain against a remote
+LDAP server.
+
+The -H parameter is used to specify the remote target server.
+
+Example2:
+samba-tool user edit User2
+
+Example2 shows how to edit a users attributes in the domain against a local
+LDAP server.
+
+Example3:
+samba-tool user edit User3 --editor=nano
+
+Example3 shows how to edit a users attributes in the domain against a local
+LDAP server using the 'nano' editor.
+
+"""
+    synopsis = "%prog <username> [options]"
+
+    takes_options = [
+        Option("-H", "--URL", help="LDB URL for database or target server",
+               type=str, metavar="URL", dest="H"),
+        Option("--editor", help="Editor to use instead of the system default,"
+               " or 'vi' if no system default is set.", type=str),
+    ]
+
+    takes_args = ["username"]
+    takes_optiongroups = {
+        "sambaopts": options.SambaOptions,
+        "credopts": options.CredentialsOptions,
+        "versionopts": options.VersionOptions,
+        }
+
+    def run(self, username, credopts=None, sambaopts=None, versionopts=None,
+            H=None, editor=None):
+
+        lp = sambaopts.get_loadparm()
+        creds = credopts.get_credentials(lp, fallback_machine=True)
+        samdb = SamDB(url=H, session_info=system_session(),
+                      credentials=creds, lp=lp)
+
+        filter = ("(&(sAMAccountType=%d)(sAMAccountName=%s))" %
+                  (dsdb.ATYPE_NORMAL_ACCOUNT, ldb.binary_encode(username)))
+
+        domaindn = samdb.domain_dn()
+
+        try:
+            res = samdb.search(base=domaindn,
+                               expression=filter,
+                               scope=ldb.SCOPE_SUBTREE)
+            user_dn = res[0].dn
+        except IndexError:
+            raise CommandError('Unable to find user "%s"' % (username))
+
+        for msg in res:
+            r_ldif = samdb.write_ldif(msg, 1)
+            # remove 'changetype' line
+            result_ldif = re.sub('changetype: add\n', '', r_ldif)
+
+            if editor is None:
+                editor = os.environ.get('EDITOR')
+                if editor is None:
+                    editor = 'vi'
+
+            with tempfile.NamedTemporaryFile(suffix=".tmp") as t_file:
+                t_file.write(result_ldif)
+                t_file.flush()
+                try:
+                    check_call([editor, t_file.name])
+                except CalledProcessError as e:
+                    raise CalledProcessError("ERROR: ", e)
+                with open(t_file.name) as edited_file:
+                    edited_message = edited_file.read()
+
+        if result_ldif != edited_message:
+            diff = difflib.ndiff(result_ldif.splitlines(),
+                                 edited_message.splitlines())
+            minus_lines = []
+            plus_lines = []
+            for line in diff:
+                if line.startswith('-'):
+                    line = line[2:]
+                    minus_lines.append(line)
+                elif line.startswith('+'):
+                    line = line[2:]
+                    plus_lines.append(line)
+
+            user_ldif="dn: %s\n" % user_dn
+            user_ldif += "changetype: modify\n"
+
+            for line in minus_lines:
+                attr, val = line.split(':', 1)
+                search_attr="%s:" % attr
+                if not re.search(r'^' + search_attr, str(plus_lines)):
+                    user_ldif += "delete: %s\n" % attr
+                    user_ldif += "%s: %s\n" % (attr, val)
+
+            for line in plus_lines:
+                attr, val = line.split(':', 1)
+                search_attr="%s:" % attr
+                if re.search(r'^' + search_attr, str(minus_lines)):
+                    user_ldif += "replace: %s\n" % attr
+                    user_ldif += "%s: %s\n" % (attr, val)
+                if not re.search(r'^' + search_attr, str(minus_lines)):
+                    user_ldif += "add: %s\n" % attr
+                    user_ldif += "%s: %s\n" % (attr, val)
+
+            try:
+                samdb.modify_ldif(user_ldif)
+            except Exception as e:
+                raise CommandError("Failed to modify user '%s': " %
+                                   username, e)
+
+            self.outf.write("Modified User '%s' successfully\n" % username)
+
 class cmd_user(SuperCommand):
     """User management."""
 
@@ -2298,3 +2434,4 @@ class cmd_user(SuperCommand):
     subcommands["setpassword"] = cmd_user_setpassword()
     subcommands["getpassword"] = cmd_user_getpassword()
     subcommands["syncpasswords"] = cmd_user_syncpasswords()
+    subcommands["edit"] = cmd_user_edit()
diff --git a/python/samba/tests/samba_tool/edit.sh b/python/samba/tests/samba_tool/edit.sh
new file mode 100755
index 0000000..c1ecfde
--- /dev/null
+++ b/python/samba/tests/samba_tool/edit.sh
@@ -0,0 +1,72 @@
+#!/bin/sh
+#
+# Test for 'samba-tool user edit'
+
+if [ $# -lt 3 ]; then
+cat <<EOF
+Usage: edit.sh SERVER USERNAME PASSWORD
+EOF
+exit 1;
+fi
+
+SERVER="$1"
+USERNAME="$2"
+PASSWORD="$3"
+
+STpath=$(pwd)
+. $STpath/testprogs/blackbox/subunit.sh
+
+# create editor.sh
+# this has to be hard linked to /tmp or 'samba-tool user edit' cannot find it
+tmpeditor=$(mktemp --suffix .sh -p $STpath/bin samba-tool-editor-XXXXXXXX)
+
+cat >$tmpeditor <<-'EOF'
+#!/usr/bin/env bash
+user_ldif="$1"
+SED=$(which sed)
+$SED -i -e 's/userAccountControl: 512/userAccountControl: 514/' $user_ldif
+EOF
+
+chmod +x $tmpeditor
+
+failed=0
+
+# Create a test user
+subunit_start_test "Create_User"
+output=$(${STpath}/source4/scripting/bin/samba-tool user create sambatool1 --random-password \
+-H "ldap://$SERVER" "-U$USERNAME" "--password=$PASSWORD")
+status=$?
+if [ "x$status" = "x0" ]; then
+    subunit_pass_test "Create_User"
+else
+    echo "$output" | subunit_fail_test "Create_User"
+    failed=$((failed + 1))
+fi
+
+# Edit test user
+subunit_start_test "Edit_User"
+output=$(${STpath}/source4/scripting/bin/samba-tool user edit sambatool1 --editor=$tmpeditor \
+-H "ldap://$SERVER" "-U$USERNAME" "--password=$PASSWORD")
+status=$?
+if [ "x$status" = "x0" ]; then
+    subunit_pass_test "Edit_User"
+else
+    echo "$output" | subunit_fail_test "Edit_User"
+    failed=$((failed + 1))
+fi
+
+# Delete test user
+subunit_start_test "Delete_User"
+output=$(${STpath}/source4/scripting/bin/samba-tool user delete sambatool1 \
+-H "ldap://$SERVER" "-U$USERNAME" "--password=$PASSWORD")
+status=$?
+if [ "x$status" = "x0" ]; then
+    subunit_pass_test "Delete_User"
+else
+    echo "$output" | subunit_fail_test "Delete_User"
+    failed=$((failed + 1))
+fi
+
+rm -f $tmpeditor
+
+exit $failed
diff --git a/source4/selftest/tests.py b/source4/selftest/tests.py
index 4e0642f..15037a2 100755
--- a/source4/selftest/tests.py
+++ b/source4/selftest/tests.py
@@ -586,6 +586,10 @@ planpythontestsuite("ad_dc_ntvfs:local", "samba.tests.samba_tool.join")
 for env in ["ad_dc_ntvfs", "fl2000dc", "fl2003dc", "fl2008r2dc"]:
     planpythontestsuite(env + ":local", "samba.tests.samba_tool.fsmo")
 
+# test user.edit
+for env in ["ad_dc:local", "ad_dc_ntvfs:local", "fl2000dc:local", "fl2003dc:local", "fl2008r2dc:local"]:
+    plantestsuite("samba.tests.samba_tool.edit", env, [os.path.join(srcdir(), "python/samba/tests/samba_tool/edit.sh"), '$SERVER', '$USERNAME', '$PASSWORD'])
+
 # We run this test against both AD DC implemetnations because it is
 # the only test we have of GPO get/set behaviour, and this involves
 # the file server as well as the LDAP server.


-- 
Samba Shared Repository



More information about the samba-cvs mailing list