diff options
Diffstat (limited to 'source4/scripting')
-rw-r--r-- | source4/scripting/python/modules.c | 43 | ||||
-rw-r--r-- | source4/scripting/python/modules.h | 2 | ||||
-rw-r--r-- | source4/scripting/python/pyglue.c | 23 | ||||
-rw-r--r-- | source4/scripting/python/samba/__init__.py | 62 | ||||
-rw-r--r-- | source4/scripting/python/samba/getopt.py | 14 | ||||
-rw-r--r-- | source4/scripting/python/samba/netcmd/__init__.py | 145 | ||||
-rw-r--r-- | source4/scripting/python/samba/netcmd/domainlevel.py | 229 | ||||
-rwxr-xr-x | source4/scripting/python/samba/netcmd/enableaccount.py | 65 | ||||
-rwxr-xr-x | source4/scripting/python/samba/netcmd/newuser.py | 70 | ||||
-rw-r--r-- | source4/scripting/python/samba/netcmd/pwsettings.py | 190 | ||||
-rw-r--r-- | source4/scripting/python/samba/netcmd/setexpiry.py | 72 | ||||
-rw-r--r-- | source4/scripting/python/samba/netcmd/setpassword.py | 77 | ||||
-rw-r--r-- | source4/scripting/python/samba/provision.py | 2 | ||||
-rw-r--r-- | source4/scripting/python/samba/tests/netcmd.py | 34 |
14 files changed, 958 insertions, 70 deletions
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) 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..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 <jelmer@samba.org> 2007-2008 -# +# # Based on the original in EJS: # Copyright (C) Andrew Tridgell <tridge@samba.org> 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 <http://www.gnu.org/licenses/>. # @@ -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. """ @@ -370,15 +369,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 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 <jelmer@samba.org> 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 <http://www.gnu.org/licenses/>. # @@ -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 new file mode 100644 index 0000000000..a204ab897b --- /dev/null +++ b/source4/scripting/python/samba/netcmd/__init__.py @@ -0,0 +1,145 @@ +#!/usr/bin/python + +# Unix SMB/CIFS implementation. +# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 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 <http://www.gnu.org/licenses/>. +# + +import optparse +from samba import getopt as options, Ldb +import sys + + +class Option(optparse.Option): + pass + + +class Command(object): + """A net command.""" + + def _get_description(self): + return self.__doc__.splitlines()[0].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, *args): + parser, _ = self._create_parser() + parser.print_usage() + + description = property(_get_description) + + def _get_synopsis(self): + ret = self.name + if self.takes_args: + ret += " " + " ".join([x.upper() for x in self.takes_args]) + return ret + + synopsis = property(_get_synopsis) + + takes_args = [] + takes_options = [] + 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): + 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) + min_args = 0 + max_args = 0 + for i, arg in enumerate(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: + 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.""" + raise NotImplementedError(self.run) + + +class SuperCommand(Command): + """A command with subcommands.""" + + subcommands = {} + + def _run(self, myname, subcommand=None, *args): + if subcommand is None: + 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: + return self.subcommands[subcommand].usage(*args) + + +class CommandError(Exception): + pass + + +commands = {} +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() +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/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 <http://www.gnu.org/licenses/>. +# + +# 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 <options>)" + + 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/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 <http://www.gnu.org/licenses/>. +# + +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/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 <http://www.gnu.org/licenses/>. + +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] <username> [<password>]" + + 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) diff --git a/source4/scripting/python/samba/netcmd/pwsettings.py b/source4/scripting/python/samba/netcmd/pwsettings.py new file mode 100644 index 0000000000..30f6f20d68 --- /dev/null +++ b/source4/scripting/python/samba/netcmd/pwsettings.py @@ -0,0 +1,190 @@ +#!/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 <http://www.gnu.org/licenses/>. +# + +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 <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("--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 (<integer> | default). Default is 24.", type=str), + Option("--min-pwd-length", + help="The minimum password length (<integer> | default). Default is 7.", type=str), + Option("--min-pwd-age", + help="The minimum password age (<integer in days> | default). Default is 0.", type=str), + Option("--max-pwd-age", + help="The maximum password age (<integer in days> | default). Default is 43.", type=str), + ] + + 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) + + 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]) + cur_min_pwd_len = int(res[0]["minPwdLength"][0]) + # ticks -> days + 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!") + + if subcommand == "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" % 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() + 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 '%s'!" % subcommand) diff --git a/source4/scripting/python/samba/netcmd/setexpiry.py b/source4/scripting/python/samba/netcmd/setexpiry.py new file mode 100644 index 0000000000..0c5dc5afff --- /dev/null +++ b/source4/scripting/python/samba/netcmd/setexpiry.py @@ -0,0 +1,72 @@ +#!/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 <http://www.gnu.org/licenses/>. +# + +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): + """Set the expiration of a user account.""" + + 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) 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 <http://www.gnu.org/licenses/>. +# + +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) 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) 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 <jelmer@samba.org> 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 <http://www.gnu.org/licenses/>. +# + +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) |