From dbda2c2db5a3c0c39134fde1ae58ceadf473a87f Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Fri, 18 Dec 2009 14:45:58 +1100 Subject: s4-provision: added a note about where invocationIDs come from Pair-Programmed-With: Andrew Bartlett --- source4/scripting/python/samba/provision.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/provision.py b/source4/scripting/python/samba/provision.py index 3e4e90a746..d7d0a790ca 100644 --- a/source4/scripting/python/samba/provision.py +++ b/source4/scripting/python/samba/provision.py @@ -894,6 +894,8 @@ def setup_samdb(path, setup_path, session_info, provision_backend, lp, samdb.set_domain_sid(str(domainsid)) if serverrole == "domain controller": samdb.set_invocation_id(invocationid) + # NOTE: the invocationid for standalone and member server + # cases is setup in the sambd_dsdb module init function message("Adding DomainDN: %s" % names.domaindn) -- cgit From c064549e2e29b1a7e100300fa7d851451a90a6a7 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 01:04:33 +0100 Subject: net: Support implementing subcommands in python. --- source4/scripting/python/samba/netcmd/__init__.py | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 source4/scripting/python/samba/netcmd/__init__.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py new file mode 100644 index 0000000000..54f3134d2f --- /dev/null +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -0,0 +1,33 @@ +#!/usr/bin/python + +# Unix SMB/CIFS implementation. +# Copyright (C) Jelmer Vernooij 2009 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +class Command(object): + """A net command.""" + + def _get_description(self): + return self.__doc__ + + description = property(_get_description) + + def run(self): + """Run the command. This should be overriden by all subclasses.""" + raise NotImplementedError(self.run) + + +commands = {} -- cgit From 9b1a21031187e83de61d999b70a6d1cda7b68444 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 01:21:27 +0100 Subject: net: Support usage/help of subcommands implemented in Python. --- source4/scripting/python/samba/netcmd/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 54f3134d2f..f644febba6 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -23,6 +23,9 @@ class Command(object): def _get_description(self): return self.__doc__ + def usage(self): + raise NotImplementedError + description = property(_get_description) def run(self): @@ -31,3 +34,4 @@ class Command(object): commands = {} +commands["foo"] = Command() -- cgit From 9e603dfb95f61a7daf2acc80c9c3120ae9ecf98e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 13:53:18 +0100 Subject: s4/net: Support parsing arguments in Python commands. --- source4/scripting/python/samba/netcmd/__init__.py | 64 +++++++++++++++++++++-- 1 file changed, 61 insertions(+), 3 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index f644febba6..16f19f8b24 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -17,21 +17,79 @@ # along with this program. If not, see . # +import optparse +from samba import getopt as options, Ldb + + +class Option(optparse.Option): + pass + + class Command(object): """A net command.""" def _get_description(self): - return self.__doc__ + return self.__doc__.splitlines()[-1].rstrip("\n") + + def _get_name(self): + name = self.__class__.__name__ + if name.startswith("cmd_"): + return name[4:] + return name + + name = property(_get_name) def usage(self): - raise NotImplementedError + self.parser.print_usage() description = property(_get_description) + takes_args = [] + takes_options = [] + + def __init__(self): + synopsis = self.name + if self.takes_args: + synopsis += " " + " ".join(self.takes_args) + self.parser = optparse.OptionParser(synopsis) + self.parser.add_options(self.takes_options) + + def _run(self, *argv): + opts, args = self.parser.parse_args(list(argv)) + return self.run(*args, **opts.__dict__) + def run(self): """Run the command. This should be overriden by all subclasses.""" raise NotImplementedError(self.run) +class SuperCommand(Command): + """A command with subcommands.""" + + subcommands = {} + + def run(self, subcommand, *args, **kwargs): + if not subcommand in subcommands: + print >>sys.stderr, "No such subcommand '%s'" % subcommand + return subcommands[subcommand].run(*args, **kwargs) + + def usage(self, subcommand=None, *args, **kwargs): + if subcommand is None: + print "Available subcommands" + for subcommand in subcommands: + print "\t%s" % subcommand + return 0 + else: + if not subcommand in subcommands: + print >>sys.stderr, "No such subcommand '%s'" % subcommand + return subcommands[subcommand].usage(*args, **kwargs) + + +class FooCommand(Command): + + def run(self, bar): + print "LALALA" + bar + return 0 + commands = {} -commands["foo"] = Command() +commands["foo"] = FooCommand() -- cgit From 8c19cd2dea470b5f4a981bfbd4b9e33c11bfde39 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 14:17:25 +0100 Subject: netcmd: Add some basic tests. --- source4/scripting/python/samba/tests/netcmd.py | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 source4/scripting/python/samba/tests/netcmd.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/tests/netcmd.py b/source4/scripting/python/samba/tests/netcmd.py new file mode 100644 index 0000000000..ecd8dc439e --- /dev/null +++ b/source4/scripting/python/samba/tests/netcmd.py @@ -0,0 +1,34 @@ +#!/usr/bin/python + +# Unix SMB/CIFS implementation. +# Copyright (C) Jelmer Vernooij 2009 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +import unittest + +from samba.netcmd import Command + +class CommandTests(unittest.TestCase): + + def test_name(self): + class cmd_foo(Command): + pass + self.assertEquals("foo", cmd_foo().name) + + def test_description(self): + class cmd_foo(Command): + """Mydescription""" + self.assertEquals("Mydescription", cmd_foo().description) -- cgit From eaf4a9afb24f2cc3cd1a268dda4ad37637821f9d Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 16:04:19 +0100 Subject: s4/net: Make pwsettings a net subcommand. --- .../scripting/python/samba/netcmd/pwsettings.py | 187 +++++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100755 source4/scripting/python/samba/netcmd/pwsettings.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/pwsettings.py b/source4/scripting/python/samba/netcmd/pwsettings.py new file mode 100755 index 0000000000..724c28e5f9 --- /dev/null +++ b/source4/scripting/python/samba/netcmd/pwsettings.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# +# Sets password settings. +# (Password complexity, history length, minimum password length, the minimum +# and maximum password age) on a Samba4 server +# +# Copyright Matthias Dieter Wallnoefer 2009 +# Copyright Andrew Kroeger 2009 +# Copyright Jelmer Vernooij 2009 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +import sys + +import samba.getopt as options +import optparse +import ldb + +from samba.auth import system_session +from samba.samdb import SamDB +from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX +from samba.netcmd import Command, CommandError, Option + +class cmd_pwsettings(Command): + """Sets password settings. + + Password complexity, history length, minimum password length, the minimum + and maximum password age) on a Samba4 server. + """ + + synopsis = "(show | set )" + + takes_optiongroups = [ + options.SambaOptions, + options.VersionOptions, + options.CredentialsOptions, + ] + + takes_options = [ + Option("-H", help="LDB URL for database or target server", type=str), + Option("--quiet", help="Be quiet", action="store_true"), + Option("--complexity", type="choice", choices=["on","off","default"], + help="The password complexity (on | off | default). Default is 'on'"), + Option("--history-length", + help="The password history length ( | default). Default is 24.", type=str), + Option("--min-pwd-length", + help="The minimum password length ( | default). Default is 7.", type=str), + Option("--min-pwd-age", + help="The minimum password age ( | default). Default is 0.", type=str), + Option("--max-pwd-age", + help="The maximum password age ( | default). Default is 43.", type=str), + ] + + def run(self, H=None, min_pwd_age=None, max_pwd_age=None, quiet=False, + complexity=None, history_length=None, min_pwd_length=None, + username=None, simple_bind_dn=None, no_pass=None, workgroup=None, + kerberos=None, configfile=None, password=None): + lp = sambaopts.get_loadparm() + creds = credopts.get_credentials(lp) + + if H is not None: + url = H + else: + url = lp.get("sam database") + + samdb = SamDB(url=url, session_info=system_session(), credentials=creds, lp=lp) + + domain_dn = SamDB.domain_dn(samdb) + res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE, + attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength", "minPwdAge", + "maxPwdAge"]) + assert(len(res) == 1) + try: + pwd_props = int(res[0]["pwdProperties"][0]) + pwd_hist_len = int(res[0]["pwdHistoryLength"][0]) + min_pwd_len = int(res[0]["minPwdLength"][0]) + # ticks -> days + min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24)) + max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24)) + except KeyError: + raise CommandError("Could not retrieve password properties!") + + if args[0] == "show": + self.message("Password informations for domain '%s'" % domain_dn) + self.message("") + if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0: + self.message("Password complexity: on") + else: + self.message("Password complexity: off") + self.message("Password history length: %d" % pwd_hist_len) + self.message("Minimum password length: %d" % min_pwd_len) + self.message("Minimum password age (days): %d" % min_pwd_age) + self.message("Maximum password age (days): %d" % max_pwd_age) + elif args[0] == "set": + msgs = [] + m = ldb.Message() + m.dn = ldb.Dn(samdb, domain_dn) + + if complexity is not None: + if complexity == "on" or complexity == "default": + pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX + msgs.append("Password complexity activated!") + elif complexity == "off": + pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX) + msgs.append("Password complexity deactivated!") + + m["pwdProperties"] = ldb.MessageElement(str(pwd_props), + ldb.FLAG_MOD_REPLACE, "pwdProperties") + + if history_length is not None: + if history_length == "default": + pwd_hist_len = 24 + else: + pwd_hist_len = int(history_length) + + if pwd_hist_len < 0 or pwd_hist_len > 24: + raise CommandError("Password history length must be in the range of 0 to 24!") + + m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len), + ldb.FLAG_MOD_REPLACE, "pwdHistoryLength") + msgs.append("Password history length changed!") + + if min_pwd_length is not None: + if min_pwd_length == "default": + min_pwd_len = 7 + else: + min_pwd_len = int(min_pwd_length) + + if min_pwd_len < 0 or min_pwd_len > 14: + raise CommandError("Minimum password length must be in the range of 0 to 14!") + + m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len), + ldb.FLAG_MOD_REPLACE, "minPwdLength") + msgs.append("Minimum password length changed!") + + if min_pwd_age is not None: + if min_pwd_age == "default": + min_pwd_age = 0 + else: + min_pwd_age = int(min_pwd_age) + + if min_pwd_age < 0 or min_pwd_age > 998: + raise CommandError("Minimum password age must be in the range of 0 to 998!") + + # days -> ticks + min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7)) + + m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks), + ldb.FLAG_MOD_REPLACE, "minPwdAge") + msgs.append("Minimum password age changed!") + + if max_pwd_age is not None: + if max_pwd_age == "default": + max_pwd_age = 43 + else: + max_pwd_age = int(max_pwd_age) + + if max_pwd_age < 0 or max_pwd_age > 999: + raise CommandError("Maximum password age must be in the range of 0 to 999!") + + # days -> ticks + max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7)) + + m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks), + ldb.FLAG_MOD_REPLACE, "maxPwdAge") + msgs.append("Maximum password age changed!") + + if max_pwd_age > 0 and min_pwd_age >= max_pwd_age: + raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age)) + + samdb.modify(m) + msgs.append("All changes applied successfully!") + self.message("\n".join(msgs)) + else: + raise CommandError("Wrong argument '" + args[0] + "'!") -- cgit From 732a7630e9db2578c3a46d0836aaf602e1d5c604 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 16:05:04 +0100 Subject: Use CommandError exception to deal with problems during net commands. --- source4/scripting/python/samba/getopt.py | 14 ++++---- source4/scripting/python/samba/netcmd/__init__.py | 40 +++++++++++++++-------- 2 files changed, 34 insertions(+), 20 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/getopt.py b/source4/scripting/python/samba/getopt.py index 8b756b2d6f..48d48dc260 100644 --- a/source4/scripting/python/samba/getopt.py +++ b/source4/scripting/python/samba/getopt.py @@ -2,17 +2,17 @@ # Samba-specific bits for optparse # Copyright (C) Jelmer Vernooij 2007 -# +# # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . # @@ -30,7 +30,7 @@ class SambaOptions(optparse.OptionGroup): def __init__(self, parser): optparse.OptionGroup.__init__(self, parser, "Samba Common Options") self.add_option("-s", "--configfile", action="callback", - type=str, metavar="FILE", help="Configuration file", + type=str, metavar="FILE", help="Configuration file", callback=self._load_configfile) self._configfile = None @@ -73,15 +73,15 @@ class CredentialsOptions(optparse.OptionGroup): help="DN to use for a simple bind") self.add_option("--password", metavar="PASSWORD", action="callback", help="Password", type=str, callback=self._set_password) - self.add_option("-U", "--username", metavar="USERNAME", + self.add_option("-U", "--username", metavar="USERNAME", action="callback", type=str, help="Username", callback=self._parse_username) - self.add_option("-W", "--workgroup", metavar="WORKGROUP", + self.add_option("-W", "--workgroup", metavar="WORKGROUP", action="callback", type=str, help="Workgroup", callback=self._parse_workgroup) self.add_option("-N", "--no-pass", action="store_true", help="Don't ask for a password") - self.add_option("-k", "--kerberos", metavar="KERBEROS", + self.add_option("-k", "--kerberos", metavar="KERBEROS", action="callback", type=str, help="Use Kerberos", callback=self._set_kerberos) self.creds = Credentials() diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 16f19f8b24..4be8977b45 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -29,7 +29,7 @@ class Command(object): """A net command.""" def _get_description(self): - return self.__doc__.splitlines()[-1].rstrip("\n") + return self.__doc__.splitlines()[0].rstrip("\n") def _get_name(self): name = self.__class__.__name__ @@ -44,15 +44,26 @@ class Command(object): description = property(_get_description) + def _get_synopsis(self): + ret = self.name + if self.takes_args: + ret += " " + " ".join(self.takes_args) + return ret + + synopsis = property(_get_synopsis) + takes_args = [] takes_options = [] + takes_optiongroups = [] def __init__(self): - synopsis = self.name - if self.takes_args: - synopsis += " " + " ".join(self.takes_args) - self.parser = optparse.OptionParser(synopsis) + self.parser = optparse.OptionParser(self.synopsis) self.parser.add_options(self.takes_options) + for optiongroup in self.takes_optiongroups: + self.parser.add_option_group(optiongroup(self.parser)) + + def message(self, text): + print text def _run(self, *argv): opts, args = self.parser.parse_args(list(argv)) @@ -70,8 +81,12 @@ class SuperCommand(Command): def run(self, subcommand, *args, **kwargs): if not subcommand in subcommands: - print >>sys.stderr, "No such subcommand '%s'" % subcommand - return subcommands[subcommand].run(*args, **kwargs) + print >>sys.stderr, "ERROR: No such subcommand '%s'" % subcommand + try: + return subcommands[subcommand].run(*args, **kwargs) + except CommandError, e: + print >>sys.stderr, "ERROR: %s" % e.message + return -1 def usage(self, subcommand=None, *args, **kwargs): if subcommand is None: @@ -81,15 +96,14 @@ class SuperCommand(Command): return 0 else: if not subcommand in subcommands: - print >>sys.stderr, "No such subcommand '%s'" % subcommand + print >>sys.stderr, "ERROR: No such subcommand '%s'" % subcommand return subcommands[subcommand].usage(*args, **kwargs) -class FooCommand(Command): +class CommandError(Exception): + pass - def run(self, bar): - print "LALALA" + bar - return 0 commands = {} -commands["foo"] = FooCommand() +from samba.netcmd.pwsettings import cmd_pwsettings +commands["pwsettings"] = cmd_pwsettings() -- cgit From e60a40e287a1febdab98cc6cf81a80a8cb6bcfb2 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 16:48:07 +0100 Subject: s4/net: Add domainlevel subcommand. --- source4/scripting/python/samba/netcmd/__init__.py | 39 +++- .../scripting/python/samba/netcmd/domainlevel.py | 229 +++++++++++++++++++++ .../scripting/python/samba/netcmd/pwsettings.py | 33 +-- 3 files changed, 275 insertions(+), 26 deletions(-) create mode 100644 source4/scripting/python/samba/netcmd/domainlevel.py mode change 100755 => 100644 source4/scripting/python/samba/netcmd/pwsettings.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 4be8977b45..5c18d29fc3 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -39,8 +39,9 @@ class Command(object): name = property(_get_name) - def usage(self): - self.parser.print_usage() + def usage(self, args): + parser, _ = self._create_parser() + parser.print_usage() description = property(_get_description) @@ -54,20 +55,34 @@ class Command(object): takes_args = [] takes_options = [] - takes_optiongroups = [] - - def __init__(self): - self.parser = optparse.OptionParser(self.synopsis) - self.parser.add_options(self.takes_options) - for optiongroup in self.takes_optiongroups: - self.parser.add_option_group(optiongroup(self.parser)) + takes_optiongroups = {} + + def _create_parser(self): + parser = optparse.OptionParser(self.synopsis) + parser.prog = "net" + parser.add_options(self.takes_options) + optiongroups = {} + for name, optiongroup in self.takes_optiongroups.iteritems(): + optiongroups[name] = optiongroup(parser) + parser.add_option_group(optiongroups[name]) + return parser, optiongroups def message(self, text): print text def _run(self, *argv): - opts, args = self.parser.parse_args(list(argv)) - return self.run(*args, **opts.__dict__) + parser, optiongroups = self._create_parser() + opts, args = parser.parse_args(list(argv)) + # Filter out options from option groups + kwargs = dict(opts.__dict__) + for option_group in parser.option_groups: + for option in option_group.option_list: + del kwargs[option.dest] + kwargs.update(optiongroups) + if len(args) < len(self.takes_args): + self.usage(args) + return -1 + return self.run(*args, **kwargs) def run(self): """Run the command. This should be overriden by all subclasses.""" @@ -107,3 +122,5 @@ class CommandError(Exception): commands = {} from samba.netcmd.pwsettings import cmd_pwsettings commands["pwsettings"] = cmd_pwsettings() +from samba.netcmd.domainlevel import cmd_domainlevel +commands["domainlevel"] = cmd_domainlevel() diff --git a/source4/scripting/python/samba/netcmd/domainlevel.py b/source4/scripting/python/samba/netcmd/domainlevel.py new file mode 100644 index 0000000000..1c12bde0c6 --- /dev/null +++ b/source4/scripting/python/samba/netcmd/domainlevel.py @@ -0,0 +1,229 @@ +#!/usr/bin/python +# +# Raises domain and forest function levels +# +# Copyright Matthias Dieter Wallnoefer 2009 +# Copyright Jelmer Vernooij 2009 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +# Notice: At the moment we have some more checks to do here on the special +# attributes (consider attribute "msDS-Behavior-Version). This is due to the +# fact that we on s4 LDB don't implement their change policy (only certain +# values, only increments possible...) yet. + +import samba.getopt as options +import ldb + +from samba.auth import system_session +from samba.netcmd import ( + Command, + CommandError, + Option, + ) +from samba.samdb import SamDB +from samba import ( + DS_DOMAIN_FUNCTION_2000, + DS_DOMAIN_FUNCTION_2003, + DS_DOMAIN_FUNCTION_2003_MIXED, + DS_DOMAIN_FUNCTION_2008, + DS_DOMAIN_FUNCTION_2008_R2, + DS_DC_FUNCTION_2000, + DS_DC_FUNCTION_2003, + DS_DC_FUNCTION_2008, + DS_DC_FUNCTION_2008_R2, + ) + +class cmd_domainlevel(Command): + """Raises domain and forest function levels.""" + + synopsis = "(show | raise )" + + takes_optiongroups = { + "sambaopts": options.SambaOptions, + "credopts": options.CredentialsOptions, + "versionopts": options.VersionOptions, + } + + takes_options = [ + Option("-H", help="LDB URL for database or target server", type=str), + Option("--quiet", help="Be quiet", action="store_true"), + Option("--forest", type="choice", choices=["2003", "2008", "2008_R2"], + help="The forest function level (2003 | 2008 | 2008_R2)"), + Option("--domain", type="choice", choices=["2003", "2008", "2008_R2"], + help="The domain function level (2003 | 2008 | 2008_R2)"), + ] + + takes_args = ["subcommand"] + + def run(self, subcommand, H=None, forest=None, domain=None, quiet=False, + credopts=None, sambaopts=None, versionopts=None): + lp = sambaopts.get_loadparm() + creds = credopts.get_credentials(lp) + + if H is not None: + url = H + else: + url = lp.get("sam database") + + samdb = SamDB(url=url, session_info=system_session(), + credentials=creds, lp=lp) + + domain_dn = SamDB.domain_dn(samdb) + + res_forest = samdb.search("CN=Partitions,CN=Configuration," + domain_dn, + scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"]) + assert(len(res_forest) == 1) + + res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE, + attrs=["msDS-Behavior-Version", "nTMixedDomain"]) + assert(len(res_domain) == 1) + + res_dc_s = samdb.search("CN=Sites,CN=Configuration," + domain_dn, + scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)", + attrs=["msDS-Behavior-Version"]) + assert(len(res_dc_s) >= 1) + + try: + level_forest = int(res_forest[0]["msDS-Behavior-Version"][0]) + level_domain = int(res_domain[0]["msDS-Behavior-Version"][0]) + level_domain_mixed = int(res_domain[0]["nTMixedDomain"][0]) + + min_level_dc = int(res_dc_s[0]["msDS-Behavior-Version"][0]) # Init value + for msg in res_dc_s: + if int(msg["msDS-Behavior-Version"][0]) < min_level_dc: + min_level_dc = int(msg["msDS-Behavior-Version"][0]) + + if level_forest < 0 or level_domain < 0: + raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!") + if min_level_dc < 0: + raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!") + if level_forest > level_domain: + raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!") + if level_domain > min_level_dc: + raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!") + + except KeyError: + raise CommandError("Could not retrieve the actual domain, forest level and/or lowest DC function level!") + + if subcommand == "show": + self.message("Domain and forest function level for domain '" + domain_dn + "'") + if level_forest < DS_DOMAIN_FUNCTION_2003: + self.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2003 (Native). This isn't supported! Please raise!") + if level_domain < DS_DOMAIN_FUNCTION_2003: + self.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2003 (Native). This isn't supported! Please raise!") + if min_level_dc < DS_DC_FUNCTION_2003: + self.message("\nATTENTION: You run SAMBA 4 on a lowest function level of a DC lower than Windows 2003. This isn't supported! Please step-up or upgrade the concerning DC(s)!") + + self.message("") + + if level_forest == DS_DOMAIN_FUNCTION_2000: + outstr = "2000" + elif level_forest == DS_DOMAIN_FUNCTION_2003_MIXED: + outstr = "2003 with mixed domains/interim (NT4 DC support)" + elif level_forest == DS_DOMAIN_FUNCTION_2003: + outstr = "2003" + elif level_forest == DS_DOMAIN_FUNCTION_2008: + outstr = "2008" + elif level_forest == DS_DOMAIN_FUNCTION_2008_R2: + outstr = "2008 R2" + else: + outstr = "higher than 2008 R2" + self.message("Forest function level: (Windows) " + outstr) + + if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0: + outstr = "2000 mixed (NT4 DC support)" + elif level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed == 0: + outstr = "2000" + elif level_domain == DS_DOMAIN_FUNCTION_2003_MIXED: + outstr = "2003 with mixed domains/interim (NT4 DC support)" + elif level_domain == DS_DOMAIN_FUNCTION_2003: + outstr = "2003" + elif level_domain == DS_DOMAIN_FUNCTION_2008: + outstr = "2008" + elif level_domain == DS_DOMAIN_FUNCTION_2008_R2: + outstr = "2008 R2" + else: + outstr = "higher than 2008 R2" + self.message("Domain function level: (Windows) " + outstr) + + if min_level_dc == DS_DC_FUNCTION_2000: + outstr = "2000" + elif min_level_dc == DS_DC_FUNCTION_2003: + outstr = "2003" + elif min_level_dc == DS_DC_FUNCTION_2008: + outstr = "2008" + elif min_level_dc == DS_DC_FUNCTION_2008_R2: + outstr = "2008 R2" + else: + outstr = "higher than 2008 R2" + self.message("Lowest function level of a DC: (Windows) " + outstr) + + elif subcommand == "raise": + msgs = [] + + if domain is not None: + if domain == "2003": + new_level_domain = DS_DOMAIN_FUNCTION_2003 + elif domain == "2008": + new_level_domain = DS_DOMAIN_FUNCTION_2008 + elif domain == "2008_R2": + new_level_domain = DS_DOMAIN_FUNCTION_2008_R2 + + if new_level_domain <= level_domain and level_domain_mixed == 0: + raise CommandError("Domain function level can't be smaller equal to the actual one!") + + if new_level_domain > min_level_dc: + raise CommandError("Domain function level can't be higher than the lowest function level of a DC!") + + # Deactivate mixed/interim domain support + if level_domain_mixed != 0: + m = ldb.Message() + m.dn = ldb.Dn(samdb, domain_dn) + m["nTMixedDomain"] = ldb.MessageElement("0", + ldb.FLAG_MOD_REPLACE, "nTMixedDomain") + samdb.modify(m) + m = ldb.Message() + m.dn = ldb.Dn(samdb, domain_dn) + m["msDS-Behavior-Version"]= ldb.MessageElement( + str(new_level_domain), ldb.FLAG_MOD_REPLACE, + "msDS-Behavior-Version") + samdb.modify(m) + level_domain = new_level_domain + msgs.append("Domain function level changed!") + + if forest is not None: + if forest == "2003": + new_level_forest = DS_DOMAIN_FUNCTION_2003 + elif forest == "2008": + new_level_forest = DS_DOMAIN_FUNCTION_2008 + elif forest == "2008_R2": + new_level_forest = DS_DOMAIN_FUNCTION_2008_R2 + if new_level_forest <= level_forest: + raise CommandError("Forest function level can't be smaller equal to the actual one!") + if new_level_forest > level_domain: + raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!") + m = ldb.Message() + m.dn = ldb.Dn(samdb, "CN=Partitions,CN=Configuration," + + domain_dn) + m["msDS-Behavior-Version"]= ldb.MessageElement( + str(new_level_forest), ldb.FLAG_MOD_REPLACE, + "msDS-Behavior-Version") + samdb.modify(m) + msgs.append("Forest function level changed!") + msgs.append("All changes applied successfully!") + self.message("\n".join(msgs)) + else: + raise CommandError("Wrong argument '%s'!" % subcommand) diff --git a/source4/scripting/python/samba/netcmd/pwsettings.py b/source4/scripting/python/samba/netcmd/pwsettings.py old mode 100755 new mode 100644 index 724c28e5f9..0568ea78e6 --- a/source4/scripting/python/samba/netcmd/pwsettings.py +++ b/source4/scripting/python/samba/netcmd/pwsettings.py @@ -42,11 +42,11 @@ class cmd_pwsettings(Command): synopsis = "(show | set )" - takes_optiongroups = [ - options.SambaOptions, - options.VersionOptions, - options.CredentialsOptions, - ] + takes_optiongroups = { + "sambaopts": options.SambaOptions, + "versionopts": options.VersionOptions, + "credopts": options.CredentialsOptions, + } takes_options = [ Option("-H", help="LDB URL for database or target server", type=str), @@ -63,10 +63,12 @@ class cmd_pwsettings(Command): help="The maximum password age ( | default). Default is 43.", type=str), ] - def run(self, H=None, min_pwd_age=None, max_pwd_age=None, quiet=False, - complexity=None, history_length=None, min_pwd_length=None, - username=None, simple_bind_dn=None, no_pass=None, workgroup=None, - kerberos=None, configfile=None, password=None): + takes_args = ["subcommand"] + + def run(self, subcommand, H=None, min_pwd_age=None, max_pwd_age=None, + quiet=False, complexity=None, history_length=None, + min_pwd_length=None, credopts=None, sambaopts=None, + versionopts=None): lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) @@ -75,12 +77,13 @@ class cmd_pwsettings(Command): else: url = lp.get("sam database") - samdb = SamDB(url=url, session_info=system_session(), credentials=creds, lp=lp) + samdb = SamDB(url=url, session_info=system_session(), + credentials=creds, lp=lp) domain_dn = SamDB.domain_dn(samdb) res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE, - attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength", "minPwdAge", - "maxPwdAge"]) + attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength", + "minPwdAge", "maxPwdAge"]) assert(len(res) == 1) try: pwd_props = int(res[0]["pwdProperties"][0]) @@ -92,7 +95,7 @@ class cmd_pwsettings(Command): except KeyError: raise CommandError("Could not retrieve password properties!") - if args[0] == "show": + if subcommand == "show": self.message("Password informations for domain '%s'" % domain_dn) self.message("") if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0: @@ -103,7 +106,7 @@ class cmd_pwsettings(Command): self.message("Minimum password length: %d" % min_pwd_len) self.message("Minimum password age (days): %d" % min_pwd_age) self.message("Maximum password age (days): %d" % max_pwd_age) - elif args[0] == "set": + elif subcommand == "set": msgs = [] m = ldb.Message() m.dn = ldb.Dn(samdb, domain_dn) @@ -184,4 +187,4 @@ class cmd_pwsettings(Command): msgs.append("All changes applied successfully!") self.message("\n".join(msgs)) else: - raise CommandError("Wrong argument '" + args[0] + "'!") + raise CommandError("Wrong argument '%s'!" % subcommand) -- cgit From 433f58f5a7490ba470dddc55e37325bb73cdba5c Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 20:37:48 +0100 Subject: s4/net: Pass all arguments through to the Python commands. --- source4/scripting/python/samba/netcmd/__init__.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 5c18d29fc3..cb8fa01fe1 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -19,6 +19,7 @@ import optparse from samba import getopt as options, Ldb +import sys class Option(optparse.Option): @@ -82,7 +83,11 @@ class Command(object): if len(args) < len(self.takes_args): self.usage(args) return -1 - return self.run(*args, **kwargs) + try: + return self.run(*args, **kwargs) + except CommandError, e: + print >>sys.stderr, "ERROR: %s" % e + return -1 def run(self): """Run the command. This should be overriden by all subclasses.""" @@ -97,11 +102,7 @@ class SuperCommand(Command): def run(self, subcommand, *args, **kwargs): if not subcommand in subcommands: print >>sys.stderr, "ERROR: No such subcommand '%s'" % subcommand - try: return subcommands[subcommand].run(*args, **kwargs) - except CommandError, e: - print >>sys.stderr, "ERROR: %s" % e.message - return -1 def usage(self, subcommand=None, *args, **kwargs): if subcommand is None: -- cgit From e2c4d8281d726716a00cfe2e3e0352777fc8b66f Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Mon, 28 Dec 2009 21:07:25 +0100 Subject: s4/net: Allow options before arguments for Python commands. --- source4/scripting/python/samba/netcmd/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index cb8fa01fe1..1a04210f95 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -75,12 +75,13 @@ class Command(object): parser, optiongroups = self._create_parser() opts, args = parser.parse_args(list(argv)) # Filter out options from option groups + args = args[1:] kwargs = dict(opts.__dict__) for option_group in parser.option_groups: for option in option_group.option_list: del kwargs[option.dest] kwargs.update(optiongroups) - if len(args) < len(self.takes_args): + if len(args) != len(self.takes_args): self.usage(args) return -1 try: -- cgit From 588b3e61812978f73d2708ec37da30726ac8026e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Tue, 29 Dec 2009 16:07:54 +0100 Subject: python: When updating sys.path to include the Samba python path, avoid throwing away the changes made by site.py. --- source4/scripting/python/modules.c | 43 +++++++++++++++++++++++++++++++++++--- source4/scripting/python/modules.h | 2 +- 2 files changed, 41 insertions(+), 4 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/modules.c b/source4/scripting/python/modules.c index 5365c5007d..198b3ccf12 100644 --- a/source4/scripting/python/modules.c +++ b/source4/scripting/python/modules.c @@ -61,10 +61,47 @@ void py_load_samba_modules(void) } } -void py_update_path(const char *bindir) +static bool PySys_PathPrepend(PyObject *list, const char *path) +{ + PyObject *py_path = PyString_FromString(path); + if (py_path == NULL) + return false; + + return (PyList_Insert(list, 0, py_path) == 0); +} + +bool py_update_path(const char *bindir) { char *newpath; - asprintf(&newpath, "%s/python:%s/../scripting/python:%s", bindir, bindir, Py_GetPath()); - PySys_SetPath(newpath); + PyObject *mod_sys, *py_path; + + mod_sys = PyImport_ImportModule("sys"); + if (mod_sys == NULL) { + return false; + } + + py_path = PyObject_GetAttrString(mod_sys, "path"); + if (py_path == NULL) { + return false; + } + + if (!PyList_Check(py_path)) { + return false; + } + + asprintf(&newpath, "%s/../scripting/python", bindir); + if (!PySys_PathPrepend(py_path, newpath)) { + free(newpath); + return false; + } free(newpath); + + asprintf(&newpath, "%s/python", bindir); + if (!PySys_PathPrepend(py_path, newpath)) { + free(newpath); + return false; + } + free(newpath); + + return true; } diff --git a/source4/scripting/python/modules.h b/source4/scripting/python/modules.h index 6b242ee257..4d1067cdd4 100644 --- a/source4/scripting/python/modules.h +++ b/source4/scripting/python/modules.h @@ -21,7 +21,7 @@ #define __SAMBA_PYTHON_MODULES_H__ void py_load_samba_modules(void); -void py_update_path(const char *bindir); +bool py_update_path(const char *bindir); #define py_iconv_convenience(mem_ctx) smb_iconv_convenience_init(mem_ctx, "ASCII", PyUnicode_GetDefaultEncoding(), true) -- cgit From b531696a5b878beef9d0177eeb4939160d1a602e Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 30 Dec 2009 19:53:05 +0100 Subject: net: Move 'setpassword' to 'net setpassword'. Signed-off-by: Andrew Tridgell --- source4/scripting/python/samba/netcmd/__init__.py | 9 ++- .../scripting/python/samba/netcmd/pwsettings.py | 2 +- .../scripting/python/samba/netcmd/setpassword.py | 77 ++++++++++++++++++++++ 3 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 source4/scripting/python/samba/netcmd/setpassword.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 1a04210f95..0086fa6f70 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -81,7 +81,12 @@ class Command(object): for option in option_group.option_list: del kwargs[option.dest] kwargs.update(optiongroups) - if len(args) != len(self.takes_args): + for i, arg in enumerate(self.takes_args): + if arg[-1] != "?": + if len(args) < i: + self.usage(args) + return -1 + if len(args) > len(self.takes_args): self.usage(args) return -1 try: @@ -126,3 +131,5 @@ from samba.netcmd.pwsettings import cmd_pwsettings commands["pwsettings"] = cmd_pwsettings() from samba.netcmd.domainlevel import cmd_domainlevel commands["domainlevel"] = cmd_domainlevel() +from samba.netcmd.setpassword import cmd_setpassword +commands["setpassword"] = cmd_setpassword() diff --git a/source4/scripting/python/samba/netcmd/pwsettings.py b/source4/scripting/python/samba/netcmd/pwsettings.py index 0568ea78e6..eb3bb65790 100644 --- a/source4/scripting/python/samba/netcmd/pwsettings.py +++ b/source4/scripting/python/samba/netcmd/pwsettings.py @@ -1,7 +1,7 @@ #!/usr/bin/python # # Sets password settings. -# (Password complexity, history length, minimum password length, the minimum +# (Password complexity, history length, minimum password length, the minimum # and maximum password age) on a Samba4 server # # Copyright Matthias Dieter Wallnoefer 2009 diff --git a/source4/scripting/python/samba/netcmd/setpassword.py b/source4/scripting/python/samba/netcmd/setpassword.py new file mode 100644 index 0000000000..6393e47414 --- /dev/null +++ b/source4/scripting/python/samba/netcmd/setpassword.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Sets a user password on a Samba4 server +# Copyright Jelmer Vernooij 2008 +# +# Based on the original in EJS: +# Copyright Andrew Tridgell 2005 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +import samba.getopt as options +from samba.netcmd import Command, CommandError, Option + +from getpass import getpass +from samba.auth import system_session +from samba.samdb import SamDB + +class cmd_setpassword(Command): + """Change the password of a user.""" + + synopsis = "setpassword [username] [options]" + + takes_optiongroups = { + "sambaopts": options.SambaOptions, + "versionopts": options.VersionOptions, + "credopts": options.CredentialsOptions, + } + + takes_options = [ + Option("-H", help="LDB URL for database or target server", type=str), + Option("--filter", help="LDAP Filter to set password on", type=str), + Option("--newpassword", help="Set password", type=str), + Option("--must-change-at-next-login", + help="Force password to be changed on next login", + action="store_true"), + ] + + takes_args = ["username?"] + + def run(self, username=None, filter=None, credopts=None, sambaopts=None, + versionopts=None, H=None, newpassword=None, + must_change_at_next_login=None): + if filter is None and username is None: + raise CommandError("Either the username or '--filter' must be specified!") + + password = newpassword + if password is None: + password = getpass("New Password: ") + + if filter is None: + filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username) + + lp = sambaopts.get_loadparm() + creds = credopts.get_credentials(lp) + + if H is not None: + url = H + else: + url = lp.get("sam database") + + samdb = SamDB(url=url, session_info=system_session(), + credentials=creds, lp=lp) + + samdb.setpassword(filter, password, + force_password_change_at_next_login_req=must_change_at_next_login) -- cgit From 345b25d059db27f96b00143f7617919233a78ba4 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 30 Dec 2009 20:00:12 +0100 Subject: net: Move setexpiry to 'net setexpiry' Signed-off-by: Andrew Tridgell --- source4/scripting/python/samba/netcmd/__init__.py | 2 + source4/scripting/python/samba/netcmd/setexpiry.py | 71 ++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 source4/scripting/python/samba/netcmd/setexpiry.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 0086fa6f70..ca5a8ddf24 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -133,3 +133,5 @@ from samba.netcmd.domainlevel import cmd_domainlevel commands["domainlevel"] = cmd_domainlevel() from samba.netcmd.setpassword import cmd_setpassword commands["setpassword"] = cmd_setpassword() +from samba.netcmd.setexpiry import cmd_setexpiry +commands["setexpiry"] = cmd_setexpiry() diff --git a/source4/scripting/python/samba/netcmd/setexpiry.py b/source4/scripting/python/samba/netcmd/setexpiry.py new file mode 100644 index 0000000000..51cf4c8c1a --- /dev/null +++ b/source4/scripting/python/samba/netcmd/setexpiry.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Sets the user password expiry on a Samba4 server +# Copyright Jelmer Vernooij 2008 +# +# Based on the original in EJS: +# Copyright Andrew Tridgell 2005 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +from samba.netcmd import Command, CommandError, Option + +import samba.getopt as options + +from samba.auth import system_session +from samba.samdb import SamDB + +class cmd_setexpiry(Command): + + synopsis = "setexpiry [username] [options]" + + takes_optiongroups = { + "sambaopts": options.SambaOptions, + "versionopts": options.VersionOptions, + "credopts": options.CredentialsOptions, + } + + takes_options = [ + Option("-H", help="LDB URL for database or target server", type=str), + Option("--filter", help="LDAP Filter to set password on", type=str), + Option("--days", help="Days to expiry", type=int), + Option("--noexpiry", help="Password does never expire", action="store_true"), + ] + + takes_args = ["username?"] + + def run(self, username=None, sambaopts=None, credopts=None, + versionopts=None, H=None, filter=None, days=None, noexpiry=None): + if username is None and filter is None: + raise CommandError("Either the username or '--filter' must be specified!") + + if filter is None: + filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username) + + lp = sambaopts.get_loadparm() + creds = credopts.get_credentials(lp) + + if days is None: + days = 0 + + if H is not None: + url = H + else: + url = lp.get("sam database") + + samdb = SamDB(url=url, session_info=system_session(), + credentials=creds, lp=lp) + + samdb.setexpiry(filter, days*24*3600, no_expiry_req=noexpiry) -- cgit From 73594c248f35a6ebbe391cc46b717aff14d393be Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 30 Dec 2009 20:10:34 +0100 Subject: net: Fix tests and documentation of setexpiry. Signed-off-by: Andrew Tridgell --- source4/scripting/python/samba/netcmd/__init__.py | 2 + .../scripting/python/samba/netcmd/enableaccount.py | 65 ++++++++++++++++++++++ source4/scripting/python/samba/netcmd/setexpiry.py | 1 + 3 files changed, 68 insertions(+) create mode 100755 source4/scripting/python/samba/netcmd/enableaccount.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index ca5a8ddf24..3213dd71b3 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -135,3 +135,5 @@ from samba.netcmd.setpassword import cmd_setpassword commands["setpassword"] = cmd_setpassword() from samba.netcmd.setexpiry import cmd_setexpiry commands["setexpiry"] = cmd_setexpiry() +from samba.netcmd.enableaccount import cmd_enableaccount +commands["enableaccount"] = cmd_enableaccount() diff --git a/source4/scripting/python/samba/netcmd/enableaccount.py b/source4/scripting/python/samba/netcmd/enableaccount.py new file mode 100755 index 0000000000..d4af0a84f1 --- /dev/null +++ b/source4/scripting/python/samba/netcmd/enableaccount.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Enables an user account on a Samba4 server +# Copyright Jelmer Vernooij 2008 +# +# Based on the original in EJS: +# Copyright Andrew Tridgell 2005 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +import samba.getopt as options + +from samba.auth import system_session +from samba.netcmd import Command, CommandError, Option +from samba.samdb import SamDB + +class cmd_enableaccount(Command): + """Enable an account.""" + + synopsis = "enableaccount [username] [options]" + + takes_optiongroups = { + "sambaopts": options.SambaOptions, + "versionopts": options.VersionOptions, + "credopts": options.CredentialsOptions, + } + + takes_options = [ + Option("-H", help="LDB URL for database or target server", type=str), + Option("--filter", help="LDAP Filter to set password on", type=str), + ] + + takes_args = ["username?"] + + def run(self, username=None, sambaopts=None, credopts=None, + versionopts=None, filter=None, H=None): + if username is None and filter is None: + raise CommandError("Either the username or '--filter' must be specified!") + + if filter is None: + filter = "(&(objectClass=user)(sAMAccountName=%s))" % (username) + + lp = sambaopts.get_loadparm() + creds = credopts.get_credentials(lp) + + if H is not None: + url = H + else: + url = lp.get("sam database") + + samdb = SamDB(url=url, session_info=system_session(), + credentials=creds, lp=lp) + samdb.enable_account(filter) diff --git a/source4/scripting/python/samba/netcmd/setexpiry.py b/source4/scripting/python/samba/netcmd/setexpiry.py index 51cf4c8c1a..0c5dc5afff 100644 --- a/source4/scripting/python/samba/netcmd/setexpiry.py +++ b/source4/scripting/python/samba/netcmd/setexpiry.py @@ -28,6 +28,7 @@ from samba.auth import system_session from samba.samdb import SamDB class cmd_setexpiry(Command): + """Set the expiration of a user account.""" synopsis = "setexpiry [username] [options]" -- cgit From 9e5ef916d41ee5f27616d18e431a9943310d3db6 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 30 Dec 2009 20:40:11 +0100 Subject: net: Move 'newuser' to 'net newuser' Signed-off-by: Andrew Tridgell --- source4/scripting/python/samba/netcmd/__init__.py | 15 +++-- source4/scripting/python/samba/netcmd/newuser.py | 70 +++++++++++++++++++++++ 2 files changed, 80 insertions(+), 5 deletions(-) create mode 100755 source4/scripting/python/samba/netcmd/newuser.py (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 3213dd71b3..9798f3529b 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -81,12 +81,15 @@ class Command(object): for option in option_group.option_list: del kwargs[option.dest] kwargs.update(optiongroups) + min_args = 0 + max_args = 0 for i, arg in enumerate(self.takes_args): - if arg[-1] != "?": - if len(args) < i: - self.usage(args) - return -1 - if len(args) > len(self.takes_args): + if arg[-1] not in ("?", "*"): + min_args += 1 + max_args += 1 + if arg[-1] == "*": + max_args = -1 + if len(args) < min_args or (max_args != -1 and len(args) > max_args): self.usage(args) return -1 try: @@ -137,3 +140,5 @@ from samba.netcmd.setexpiry import cmd_setexpiry commands["setexpiry"] = cmd_setexpiry() from samba.netcmd.enableaccount import cmd_enableaccount commands["enableaccount"] = cmd_enableaccount() +from samba.netcmd.newuser import cmd_newuser +commands["newuser"] = cmd_newuser() diff --git a/source4/scripting/python/samba/netcmd/newuser.py b/source4/scripting/python/samba/netcmd/newuser.py new file mode 100755 index 0000000000..651313a345 --- /dev/null +++ b/source4/scripting/python/samba/netcmd/newuser.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Adds a new user to a Samba4 server +# Copyright Jelmer Vernooij 2008 +# +# Based on the original in EJS: +# Copyright Andrew Tridgell 2005 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import samba.getopt as options +from samba.netcmd import Command, CommandError, Option + +from getpass import getpass +from samba.auth import system_session +from samba.samdb import SamDB + +class cmd_newuser(Command): + """Create a new user.""" + + synopsis = "newuser [options] []" + + takes_optiongroups = { + "sambaopts": options.SambaOptions, + "versionopts": options.VersionOptions, + "credopts": options.CredentialsOptions, + } + + takes_options = [ + Option("-H", help="LDB URL for database or target server", type=str), + Option("--unixname", help="Unix Username", type=str), + Option("--must-change-at-next-login", + help="Force password to be changed on next login", + action="store_true"), + ] + + takes_args = ["username", "password?"] + + def run(self, username, password=None, credopts=None, sambaopts=None, + versionopts=None, H=None, unixname=None, + must_change_at_next_login=None): + if password is None: + password = getpass("New Password: ") + + if unixname is None: + unixname = username + + lp = sambaopts.get_loadparm() + creds = credopts.get_credentials(lp) + + if H is not None: + url = H + else: + url = lp.get("sam database") + + samdb = SamDB(url=url, session_info=system_session(), credentials=creds, + lp=lp) + samdb.newuser(username, unixname, password, + force_password_change_at_next_login_req=must_change_at_next_login) -- cgit From 7effe2d2e30191c067ae1290224d388d96701b53 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 30 Dec 2009 21:06:21 +0100 Subject: net: Support 'super' commands implemented in Python. Signed-off-by: Andrew Tridgell --- source4/scripting/python/samba/netcmd/__init__.py | 29 ++++++++++++----------- 1 file changed, 15 insertions(+), 14 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/__init__.py b/source4/scripting/python/samba/netcmd/__init__.py index 9798f3529b..a204ab897b 100644 --- a/source4/scripting/python/samba/netcmd/__init__.py +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -40,7 +40,7 @@ class Command(object): name = property(_get_name) - def usage(self, args): + def usage(self, *args): parser, _ = self._create_parser() parser.print_usage() @@ -49,7 +49,7 @@ class Command(object): def _get_synopsis(self): ret = self.name if self.takes_args: - ret += " " + " ".join(self.takes_args) + ret += " " + " ".join([x.upper() for x in self.takes_args]) return ret synopsis = property(_get_synopsis) @@ -90,7 +90,7 @@ class Command(object): if arg[-1] == "*": max_args = -1 if len(args) < min_args or (max_args != -1 and len(args) > max_args): - self.usage(args) + self.usage(*args) return -1 try: return self.run(*args, **kwargs) @@ -108,21 +108,22 @@ class SuperCommand(Command): subcommands = {} - def run(self, subcommand, *args, **kwargs): - if not subcommand in subcommands: - print >>sys.stderr, "ERROR: No such subcommand '%s'" % subcommand - return subcommands[subcommand].run(*args, **kwargs) - - def usage(self, subcommand=None, *args, **kwargs): + def _run(self, myname, subcommand=None, *args): if subcommand is None: - print "Available subcommands" - for subcommand in subcommands: + print "Available subcommands:" + for subcommand in self.subcommands: print "\t%s" % subcommand return 0 + if not subcommand in self.subcommands: + raise CommandError("No such subcommand '%s'" % subcommand) + return self.subcommands[subcommand]._run(subcommand, *args) + + def usage(self, myname, subcommand=None, *args): + if subcommand is None or not subcommand in self.subcommands: + print "Usage: %s (%s) [options]" % (myname, + " | ".join(self.subcommands.keys())) else: - if not subcommand in subcommands: - print >>sys.stderr, "ERROR: No such subcommand '%s'" % subcommand - return subcommands[subcommand].usage(*args, **kwargs) + return self.subcommands[subcommand].usage(*args) class CommandError(Exception): -- cgit From ea5af6e30ca91df3325581f67daab96d688d58fc Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 30 Dec 2009 21:46:32 +0100 Subject: pyldb: Add dom_sid.split in favor of less powerful dom_sid_to_rid(). Signed-off-by: Andrew Tridgell --- source4/scripting/python/pyglue.c | 23 ----------------------- source4/scripting/python/samba/__init__.py | 9 --------- 2 files changed, 32 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/pyglue.c b/source4/scripting/python/pyglue.c index 9f01102316..3d33e605db 100644 --- a/source4/scripting/python/pyglue.c +++ b/source4/scripting/python/pyglue.c @@ -442,27 +442,6 @@ static PyObject *py_dsdb_make_schema_global(PyObject *self, PyObject *args) Py_RETURN_NONE; } -static PyObject *py_dom_sid_to_rid(PyLdbObject *self, PyObject *args) -{ - PyObject *py_sid; - struct dom_sid *sid; - uint32_t rid; - NTSTATUS status; - - if(!PyArg_ParseTuple(args, "O", &py_sid)) - return NULL; - - sid = dom_sid_parse_talloc(NULL, PyString_AsString(py_sid)); - - status = dom_sid_split_rid(NULL, sid, NULL, &rid); - if (!NT_STATUS_IS_OK(status)) { - PyErr_SetString(PyExc_RuntimeError, "dom_sid_split_rid failed"); - return NULL; - } - - return PyInt_FromLong(rid); -} - static PyMethodDef py_misc_methods[] = { { "generate_random_str", (PyCFunction)py_generate_random_str, METH_VARARGS, "random_password(len) -> string\n" @@ -506,8 +485,6 @@ static PyMethodDef py_misc_methods[] = { NULL }, { "dsdb_make_schema_global", (PyCFunction)py_dsdb_make_schema_global, METH_VARARGS, NULL }, - { "dom_sid_to_rid", (PyCFunction)py_dom_sid_to_rid, METH_VARARGS, - NULL }, { "set_debug_level", (PyCFunction)py_set_debug_level, METH_VARARGS, "set debug level" }, { NULL } diff --git a/source4/scripting/python/samba/__init__.py b/source4/scripting/python/samba/__init__.py index f74304c01c..d501fd7b88 100644 --- a/source4/scripting/python/samba/__init__.py +++ b/source4/scripting/python/samba/__init__.py @@ -370,15 +370,6 @@ def valid_netbios_name(name): return True -def dom_sid_to_rid(sid_str): - """Converts a domain SID to the relative RID. - - :param sid_str: The domain SID formatted as string - """ - - return glue.dom_sid_to_rid(sid_str) - - version = glue.version # "userAccountControl" flags -- cgit From 66f81d18ce08cfb1ed6c347a753b436d3de8ced7 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Wed, 30 Dec 2009 21:48:42 +0100 Subject: samba: Fix whitespace, remove pointless 'pass' statement. Signed-off-by: Andrew Tridgell --- source4/scripting/python/samba/__init__.py | 53 +++++++++++++++--------------- 1 file changed, 26 insertions(+), 27 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/__init__.py b/source4/scripting/python/samba/__init__.py index d501fd7b88..5d61c1bd8c 100644 --- a/source4/scripting/python/samba/__init__.py +++ b/source4/scripting/python/samba/__init__.py @@ -2,20 +2,20 @@ # Unix SMB/CIFS implementation. # Copyright (C) Jelmer Vernooij 2007-2008 -# +# # Based on the original in EJS: # Copyright (C) Andrew Tridgell 2005 -# +# # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program. If not, see . # @@ -45,11 +45,11 @@ import ldb import glue class Ldb(ldb.Ldb): - """Simple Samba-specific LDB subclass that takes care + """Simple Samba-specific LDB subclass that takes care of setting up the modules dir, credentials pointers, etc. - - Please note that this is intended to be for all Samba LDB files, - not necessarily the Sam database. For Sam-specific helper + + Please note that this is intended to be for all Samba LDB files, + not necessarily the Sam database. For Sam-specific helper functions see samdb.py. """ def __init__(self, url=None, lp=None, modules_dir=None, session_info=None, @@ -65,7 +65,7 @@ class Ldb(ldb.Ldb): :param options: Additional options (optional) This is different from a regular Ldb file in that the Samba-specific - modules-dir is used by default and that credentials and session_info + modules-dir is used by default and that credentials and session_info can be passed through (required by some modules). """ @@ -122,10 +122,10 @@ class Ldb(ldb.Ldb): # need one public, we will have to change this here super(Ldb, self).set_create_perms(perms) - def searchone(self, attribute, basedn=None, expression=None, + def searchone(self, attribute, basedn=None, expression=None, scope=ldb.SCOPE_BASE): """Search for one attribute as a string. - + :param basedn: BaseDN for the search. :param attribute: Name of the attribute :param expression: Optional search expression. @@ -166,7 +166,7 @@ class Ldb(ldb.Ldb): self.erase_users_computers(basedn) # Delete the 'visible' records, and the invisble 'deleted' records (if this DB supports it) - for msg in self.search(basedn, ldb.SCOPE_SUBTREE, + for msg in self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", [], controls=["show_deleted:0"]): try: @@ -174,14 +174,14 @@ class Ldb(ldb.Ldb): except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): # Ignore no such object errors pass - - res = self.search(basedn, ldb.SCOPE_SUBTREE, + + res = self.search(basedn, ldb.SCOPE_SUBTREE, "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", [], controls=["show_deleted:0"]) assert len(res) == 0 # delete the specials - for attr in ["@SUBCLASSES", "@MODULES", + for attr in ["@SUBCLASSES", "@MODULES", "@OPTIONS", "@PARTITION", "@KLUDGEACL"]: try: self.delete(attr) @@ -191,7 +191,7 @@ class Ldb(ldb.Ldb): def erase(self): """Erase this ldb, removing all records.""" - + self.erase_except_schema_controlled() # delete the specials @@ -207,13 +207,12 @@ class Ldb(ldb.Ldb): def erase_recursive(self, dn): try: - res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[], + res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[], controls=["show_deleted:0"]) except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): # Ignore no such object errors return - pass - + for msg in res: erase_recursive(self, msg.dn) @@ -223,7 +222,7 @@ class Ldb(ldb.Ldb): # Ignore no such object errors pass - res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", + res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", ["namingContexts"]) assert len(res) == 1 if not "namingContexts" in res[0]: @@ -285,14 +284,14 @@ class Ldb(ldb.Ldb): def set_invocation_id(self, invocation_id): """Set the invocation id for this SamDB handle. - + :param invocation_id: GUID of the invocation id. """ glue.dsdb_set_ntds_invocation_id(self, invocation_id) def set_opaque_integer(self, name, value): """Set an integer as an opaque (a flag or other value) value on the database - + :param name: The name for the opaque value :param value: The integer value """ @@ -302,7 +301,7 @@ class Ldb(ldb.Ldb): def substitute_var(text, values): """substitute strings of the form ${NAME} in str, replacing with substitutions from subobj. - + :param text: Text in which to subsitute. :param values: Dictionary with keys and values. """ @@ -318,21 +317,21 @@ def substitute_var(text, values): def check_all_substituted(text): """Make sure that all substitution variables in a string have been replaced. If not, raise an exception. - + :param text: The text to search for substitution variables """ if not "${" in text: return - + var_start = text.find("${") var_end = text.find("}", var_start) - + raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1]) def read_and_sub_file(file, subst_vars): """Read a file and sub in variables found in it - + :param file: File to be read (typically from setup directory) param subst_vars: Optional variables to subsitute in the file. """ -- cgit From 3239872bbcd81a690663f29c8fa20811d66f9dea Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Thu, 31 Dec 2009 16:52:15 +1100 Subject: s4-net: fixed pwsettings command Don't override user settings with current settings --- source4/scripting/python/samba/netcmd/pwsettings.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/samba/netcmd/pwsettings.py b/source4/scripting/python/samba/netcmd/pwsettings.py index eb3bb65790..30f6f20d68 100644 --- a/source4/scripting/python/samba/netcmd/pwsettings.py +++ b/source4/scripting/python/samba/netcmd/pwsettings.py @@ -88,10 +88,10 @@ class cmd_pwsettings(Command): try: pwd_props = int(res[0]["pwdProperties"][0]) pwd_hist_len = int(res[0]["pwdHistoryLength"][0]) - min_pwd_len = int(res[0]["minPwdLength"][0]) + cur_min_pwd_len = int(res[0]["minPwdLength"][0]) # ticks -> days - min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24)) - max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24)) + cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24)) + cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24)) except KeyError: raise CommandError("Could not retrieve password properties!") @@ -103,9 +103,9 @@ class cmd_pwsettings(Command): else: self.message("Password complexity: off") self.message("Password history length: %d" % pwd_hist_len) - self.message("Minimum password length: %d" % min_pwd_len) - self.message("Minimum password age (days): %d" % min_pwd_age) - self.message("Maximum password age (days): %d" % max_pwd_age) + self.message("Minimum password length: %d" % cur_min_pwd_len) + self.message("Minimum password age (days): %d" % cur_min_pwd_age) + self.message("Maximum password age (days): %d" % cur_max_pwd_age) elif subcommand == "set": msgs = [] m = ldb.Message() -- cgit