Changeset 740 for vendor/current/source4/scripting
- Timestamp:
- Nov 14, 2012, 12:59:34 PM (13 years ago)
- Location:
- vendor/current/source4/scripting
- Files:
-
- 91 added
- 10 deleted
- 39 edited
Legend:
- Unmodified
- Added
- Removed
-
vendor/current/source4/scripting/bin/autoidl
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 3 -
vendor/current/source4/scripting/bin/fullschema
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # 3 3 # Works out the full schema … … 6 6 import base64 7 7 import optparse 8 import os9 8 import sys 10 9 … … 14 13 import samba 15 14 from samba import getopt as options, Ldb 16 from ldb import SCOPE_SUBTREE, SCOPE_BASE , LdbError15 from ldb import SCOPE_SUBTREE, SCOPE_BASE 17 16 import sys 18 17 -
vendor/current/source4/scripting/bin/get-descriptors
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # 3 3 # Unix SMB/CIFS implementation. … … 28 28 # 29 29 30 import getopt31 30 import optparse 32 31 import sys 33 import os34 32 import base64 35 import re36 33 37 34 sys.path.insert(0, "bin/python") … … 40 37 from samba.auth import system_session 41 38 import samba.getopt as options 42 from samba import param43 39 from samba.ndr import ndr_pack, ndr_unpack 44 40 from samba.dcerpc import security 45 41 from samba import Ldb 46 42 from samba.samdb import SamDB 47 from ldb import SCOPE_SUBTREE, SCOPE_ ONELEVEL, SCOPE_BASE, LdbError43 from ldb import SCOPE_SUBTREE, SCOPE_BASE 48 44 49 45 parser = optparse.OptionParser("get-descriptor [options]") … … 66 62 67 63 class DescrGetter: 64 68 65 def __init__(self, localdomain, remotedomain): 69 66 self.samdb = SamDB(session_info=system_session(), lp=lp, options=["modules:paged_searches"]) -
vendor/current/source4/scripting/bin/minschema
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # 3 3 # Works out the minimal schema for a set of objectclasses -
vendor/current/source4/scripting/bin/rebuildextendeddn
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # 3 3 # Unix SMB/CIFS implementation. … … 24 24 # 25 25 26 import getopt27 26 import optparse 28 27 import os … … 34 33 from samba.credentials import DONT_USE_KERBEROS 35 34 from samba.auth import system_session 36 from samba import Ldb, substitute_var, valid_netbios_name, check_all_substituted 37 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError, \ 38 timestring, CHANGETYPE_MODIFY, CHANGETYPE_NONE 35 from samba import Ldb 36 from ldb import SCOPE_SUBTREE, SCOPE_BASE 39 37 import ldb 40 38 import samba.getopt as options 41 from samba.samdb import SamDB42 39 from samba import param 43 from samba.provision import ProvisionPaths, ProvisionNames,provision_paths_from_lp,get_dnsyntax_attributes,get_linked_attributes 40 from samba.provision import ProvisionNames, provision_paths_from_lp 41 from samba.schema import get_dnsyntax_attributes, get_linked_attributes 44 42 45 43 parser = optparse.OptionParser("provision [options]") -
vendor/current/source4/scripting/bin/rpcclient
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 import sys, os, string -
vendor/current/source4/scripting/bin/samba3dump
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # 3 3 # Dump Samba3 data -
vendor/current/source4/scripting/bin/setup_dns.sh
r414 r740 17 17 } 18 18 19 OBJECTGUID=$(bin/ldbsearch - H "$PRIVATEDIR/sam.ldb" -b "CN=NTDS Settings,CN=$HOSTNAME,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=$RSUFFIX" objectguid|grep ^objectGUID| cut -d: -f2)19 OBJECTGUID=$(bin/ldbsearch -s base -H "$PRIVATEDIR/sam.ldb" -b "CN=NTDS Settings,CN=$HOSTNAME,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=$RSUFFIX" objectguid|grep ^objectGUID| cut -d: -f2) 20 20 21 21 echo "Found objectGUID $OBJECTGUID" … … 34 34 } 35 35 echo "Checking" 36 rndc flush 36 37 host $HOSTNAME.$DOMAIN 37 38 host $OBJECTGUID._msdcs.$DOMAIN -
vendor/current/source4/scripting/bin/smbstatus
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 3 # -
vendor/current/source4/scripting/bin/subunitrun
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Simple subunit testrunner for python … … 22 22 # Find right directory when running from source tree 23 23 sys.path.insert(0, "bin/python") 24 sys.path.insert(1, "../lib/subunit/python")25 24 26 from subunit import SubunitTestRunner27 from unittest import TestProgram28 25 import optparse 29 import os 30 from samba import param 26 import samba 27 samba.ensure_external_module("testtools", "testtools") 28 samba.ensure_external_module("subunit", "subunit/python") 29 from subunit.run import SubunitTestRunner 31 30 import samba.getopt as options 32 31 import samba.tests 32 33 33 34 34 parser = optparse.OptionParser("subunitrun [options] <tests>") 35 35 credopts = options.CredentialsOptions(parser) 36 36 parser.add_option_group(credopts) 37 sambaopts = options.SambaOptions(parser) 38 parser.add_option_group(sambaopts) 39 parser.add_option_group(options.VersionOptions(parser)) 37 try: 38 from subunit.run import TestProgram 39 except ImportError: 40 from unittest import TestProgram 41 else: 42 parser.add_option('-l', '--list', dest='listtests', default=False, 43 help='List tests rather than running them.', 44 action="store_true") 40 45 41 args = parser.parse_args()[1] 46 opts, args = parser.parse_args() 42 47 43 samba.tests.cmdline_loadparm = sambaopts.get_loadparm() 44 samba.tests.cmdline_credentials = credopts.get_credentials(samba.tests.cmdline_loadparm) 48 samba.tests.cmdline_credentials = credopts.get_credentials(samba.tests.env_loadparm()) 49 if getattr(opts, "listtests", False): 50 args.insert(0, "--list") 45 51 46 52 runner = SubunitTestRunner() -
vendor/current/source4/scripting/python/examples/netbios.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. -
vendor/current/source4/scripting/python/examples/samr.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 3 -
vendor/current/source4/scripting/python/examples/winreg.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # 3 3 # tool to manipulate a remote registry -
vendor/current/source4/scripting/python/modules.c
r414 r740 18 18 */ 19 19 20 #include <Python.h> 20 21 #include "includes.h" 21 22 #include "scripting/python/modules.h" 22 #include <Python.h>23 #include "dynconfig/dynconfig.h" 23 24 24 extern void init_ldb(void); 25 extern void init_security(void); 26 extern void init_registry(void); 27 extern void init_param(void); 28 extern void init_misc(void); 29 extern void init_ldb(void); 30 extern void init_auth(void); 31 extern void init_credentials(void); 32 extern void init_tdb(void); 33 extern void init_dcerpc(void); 34 extern void init_events(void); 35 extern void inituuid(void); 36 extern void init_net(void); 37 extern void initecho(void); 38 extern void initdfs(void); 39 extern void initdrsuapi(void); 40 extern void initwinreg(void); 41 extern void initepmapper(void); 42 extern void initinitshutdown(void); 43 extern void initmgmt(void); 44 extern void initnet(void); 45 extern void initatsvc(void); 46 extern void initsamr(void); 47 extern void initlsa(void); 48 extern void initsvcctl(void); 49 extern void initwkssvc(void); 50 extern void initunixinfo(void); 51 extern void init_libcli_nbt(void); 52 extern void init_libcli_smb(void); 25 static bool PySys_PathPrepend(PyObject *list, const char *path) 26 { 27 PyObject *py_path = PyString_FromString(path); 28 if (py_path == NULL) 29 return false; 53 30 54 static struct _inittab py_modules[] = { STATIC_LIBPYTHON_MODULES }; 55 56 void py_load_samba_modules(void) 57 { 58 int i; 59 for (i = 0; i < ARRAY_SIZE(py_modules); i++) { 60 PyImport_ExtendInittab(&py_modules[i]); 61 } 31 return (PyList_Insert(list, 0, py_path) == 0); 62 32 } 63 33 64 void py_update_path(const char *bindir)34 bool py_update_path(void) 65 35 { 66 char *newpath; 67 asprintf(&newpath, "%s/python:%s/../scripting/python:%s", bindir, bindir, Py_GetPath()); 68 PySys_SetPath(newpath); 69 free(newpath); 36 PyObject *mod_sys, *py_path; 37 38 mod_sys = PyImport_ImportModule("sys"); 39 if (mod_sys == NULL) { 40 return false; 41 } 42 43 py_path = PyObject_GetAttrString(mod_sys, "path"); 44 if (py_path == NULL) { 45 return false; 46 } 47 48 if (!PyList_Check(py_path)) { 49 return false; 50 } 51 52 if (!PySys_PathPrepend(py_path, dyn_PYTHONDIR)) { 53 return false; 54 } 55 56 if (strcmp(dyn_PYTHONARCHDIR, dyn_PYTHONDIR) != 0) { 57 if (!PySys_PathPrepend(py_path, dyn_PYTHONARCHDIR)) { 58 return false; 59 } 60 } 61 62 return true; 70 63 } -
vendor/current/source4/scripting/python/modules.h
r414 r740 21 21 #define __SAMBA_PYTHON_MODULES_H__ 22 22 23 void py_load_samba_modules(void); 24 void py_update_path(const char *bindir); 25 26 #define py_iconv_convenience(mem_ctx) smb_iconv_convenience_init(mem_ctx, "ASCII", PyUnicode_GetDefaultEncoding(), true) 23 bool py_update_path(void); 27 24 28 25 #endif /* __SAMBA_PYTHON_MODULES_H__ */ -
vendor/current/source4/scripting/python/pyglue.c
r414 r740 18 18 */ 19 19 20 #include <Python.h> 20 21 #include "includes.h" 21 #include "ldb.h"22 #include "ldb_errors.h"23 #include "ldb_wrap.h"24 #include "param/param.h"25 #include "auth/credentials/credentials.h"26 #include "dsdb/samdb/samdb.h"27 #include "lib/ldb-samba/ldif_handlers.h"28 #include "librpc/ndr/libndr.h"29 22 #include "version.h" 30 #include <Python.h>31 #include "lib/ldb/pyldb.h"32 #include "libcli/util/pyerrors.h"33 #include "libcli/security/security.h"34 #include "auth/pyauth.h"35 23 #include "param/pyparam.h" 36 #include "auth/credentials/pycredentials.h" 37 38 #ifndef Py_RETURN_NONE 39 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None 40 #endif 41 42 /* FIXME: These should be in a header file somewhere, once we finish moving 43 * away from SWIG .. */ 44 #define PyErr_LDB_OR_RAISE(py_ldb, ldb) \ 45 /* if (!PyLdb_Check(py_ldb)) { \ 46 PyErr_SetString(py_ldb_get_exception(), "Ldb connection object required"); \ 47 return NULL; \ 48 } */\ 49 ldb = PyLdb_AsLdbContext(py_ldb); 50 51 static void PyErr_SetLdbError(PyObject *error, int ret, struct ldb_context *ldb_ctx) 52 { 53 if (ret == LDB_ERR_PYTHON_EXCEPTION) 54 return; /* Python exception should already be set, just keep that */ 55 56 PyErr_SetObject(error, 57 Py_BuildValue(discard_const_p(char, "(i,s)"), ret, 58 ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx))); 59 } 60 61 static PyObject *py_ldb_get_exception(void) 62 { 63 PyObject *mod = PyImport_ImportModule("ldb"); 64 if (mod == NULL) 65 return NULL; 66 67 return PyObject_GetAttrString(mod, "LdbError"); 68 } 24 #include "lib/socket/netif.h" 25 26 void init_glue(void); 69 27 70 28 static PyObject *py_generate_random_str(PyObject *self, PyObject *args) … … 82 40 } 83 41 42 static PyObject *py_generate_random_password(PyObject *self, PyObject *args) 43 { 44 int min, max; 45 PyObject *ret; 46 char *retstr; 47 if (!PyArg_ParseTuple(args, "ii", &min, &max)) 48 return NULL; 49 50 retstr = generate_random_password(NULL, min, max); 51 if (retstr == NULL) { 52 return NULL; 53 } 54 ret = PyString_FromString(retstr); 55 talloc_free(retstr); 56 return ret; 57 } 58 84 59 static PyObject *py_unix2nttime(PyObject *self, PyObject *args) 85 60 { … … 91 66 unix_to_nt_time(&nt, t); 92 67 93 return PyInt_FromLong((uint64_t)nt); 68 return PyLong_FromLongLong((uint64_t)nt); 69 } 70 71 static PyObject *py_nttime2unix(PyObject *self, PyObject *args) 72 { 73 time_t t; 74 NTTIME nt; 75 if (!PyArg_ParseTuple(args, "K", &nt)) 76 return NULL; 77 78 t = nt_time_to_unix(nt); 79 80 return PyInt_FromLong((uint64_t)t); 81 } 82 83 static PyObject *py_nttime2string(PyObject *self, PyObject *args) 84 { 85 PyObject *ret; 86 NTTIME nt; 87 TALLOC_CTX *tmp_ctx; 88 const char *string; 89 if (!PyArg_ParseTuple(args, "K", &nt)) 90 return NULL; 91 92 tmp_ctx = talloc_new(NULL); 93 if (tmp_ctx == NULL) { 94 PyErr_NoMemory(); 95 return NULL; 96 } 97 98 string = nt_time_string(tmp_ctx, nt); 99 ret = PyString_FromString(string); 100 101 talloc_free(tmp_ctx); 102 103 return ret; 94 104 } 95 105 … … 103 113 } 104 114 105 static PyObject *py_ldb_set_credentials(PyObject *self, PyObject *args) 106 { 107 PyObject *py_creds, *py_ldb; 108 struct cli_credentials *creds; 109 struct ldb_context *ldb; 110 if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_creds)) 111 return NULL; 112 113 PyErr_LDB_OR_RAISE(py_ldb, ldb); 114 115 creds = cli_credentials_from_py_object(py_creds); 116 if (creds == NULL) { 117 PyErr_SetString(PyExc_TypeError, "Expected credentials object"); 118 return NULL; 119 } 120 121 ldb_set_opaque(ldb, "credentials", creds); 122 123 Py_RETURN_NONE; 124 } 125 126 static PyObject *py_ldb_set_loadparm(PyObject *self, PyObject *args) 127 { 128 PyObject *py_lp_ctx, *py_ldb; 115 static PyObject *py_get_debug_level(PyObject *self) 116 { 117 return PyInt_FromLong(DEBUGLEVEL); 118 } 119 120 /* 121 return the list of interface IPs we have configured 122 takes an loadparm context, returns a list of IPs in string form 123 124 Does not return addresses on 127.0.0.0/8 125 */ 126 static PyObject *py_interface_ips(PyObject *self, PyObject *args) 127 { 128 PyObject *pylist; 129 int count; 130 TALLOC_CTX *tmp_ctx; 131 PyObject *py_lp_ctx; 129 132 struct loadparm_context *lp_ctx; 130 struct ldb_context *ldb; 131 if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_lp_ctx)) 132 return NULL; 133 134 PyErr_LDB_OR_RAISE(py_ldb, ldb); 135 136 lp_ctx = lp_from_py_object(py_lp_ctx); 133 struct interface *ifaces; 134 int i, ifcount; 135 int all_interfaces; 136 137 if (!PyArg_ParseTuple(args, "Oi", &py_lp_ctx, &all_interfaces)) 138 return NULL; 139 140 tmp_ctx = talloc_new(NULL); 141 if (tmp_ctx == NULL) { 142 PyErr_NoMemory(); 143 return NULL; 144 } 145 146 lp_ctx = lpcfg_from_py_object(tmp_ctx, py_lp_ctx); 137 147 if (lp_ctx == NULL) { 138 PyErr_SetString(PyExc_TypeError, "Expected loadparm object"); 139 return NULL; 140 } 141 142 ldb_set_opaque(ldb, "loadparm", lp_ctx); 143 144 Py_RETURN_NONE; 145 } 146 147 148 static PyObject *py_ldb_set_session_info(PyObject *self, PyObject *args) 149 { 150 PyObject *py_session_info, *py_ldb; 151 struct auth_session_info *info; 152 struct ldb_context *ldb; 153 if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_session_info)) 154 return NULL; 155 156 PyErr_LDB_OR_RAISE(py_ldb, ldb); 157 /*if (!PyAuthSession_Check(py_session_info)) { 158 PyErr_SetString(PyExc_TypeError, "Expected session info object"); 159 return NULL; 160 }*/ 161 162 info = PyAuthSession_AsSession(py_session_info); 163 164 ldb_set_opaque(ldb, "sessionInfo", info); 165 166 Py_RETURN_NONE; 167 } 168 169 static PyObject *py_ldb_set_utf8_casefold(PyObject *self, PyObject *args) 170 { 171 PyObject *py_ldb; 172 struct ldb_context *ldb; 173 174 if (!PyArg_ParseTuple(args, "O", &py_ldb)) 175 return NULL; 176 177 PyErr_LDB_OR_RAISE(py_ldb, ldb); 178 179 ldb_set_utf8_fns(ldb, NULL, wrap_casefold); 180 181 Py_RETURN_NONE; 182 } 183 184 static PyObject *py_samdb_set_domain_sid(PyLdbObject *self, PyObject *args) 185 { 186 PyObject *py_ldb, *py_sid; 187 struct ldb_context *ldb; 188 struct dom_sid *sid; 189 bool ret; 190 191 if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_sid)) 192 return NULL; 193 194 PyErr_LDB_OR_RAISE(py_ldb, ldb); 195 196 sid = dom_sid_parse_talloc(NULL, PyString_AsString(py_sid)); 197 198 ret = samdb_set_domain_sid(ldb, sid); 199 if (!ret) { 200 PyErr_SetString(PyExc_RuntimeError, "set_domain_sid failed"); 201 return NULL; 202 } 203 Py_RETURN_NONE; 204 } 205 206 static PyObject *py_samdb_get_domain_sid(PyLdbObject *self, PyObject *args) 207 { 208 PyObject *py_ldb; 209 struct ldb_context *ldb; 210 const struct dom_sid *sid; 211 PyObject *ret; 212 char *retstr; 213 214 if (!PyArg_ParseTuple(args, "O", &py_ldb)) 215 return NULL; 216 217 PyErr_LDB_OR_RAISE(py_ldb, ldb); 218 219 sid = samdb_domain_sid(ldb); 220 if (!sid) { 221 PyErr_SetString(PyExc_RuntimeError, "samdb_domain_sid failed"); 222 return NULL; 223 } 224 retstr = dom_sid_string(NULL, sid); 225 ret = PyString_FromString(retstr); 226 talloc_free(retstr); 227 return ret; 228 } 229 230 static PyObject *py_ldb_register_samba_handlers(PyObject *self, PyObject *args) 231 { 232 PyObject *py_ldb; 233 struct ldb_context *ldb; 234 int ret; 235 236 if (!PyArg_ParseTuple(args, "O", &py_ldb)) 237 return NULL; 238 239 PyErr_LDB_OR_RAISE(py_ldb, ldb); 240 ret = ldb_register_samba_handlers(ldb); 241 242 PyErr_LDB_ERROR_IS_ERR_RAISE(py_ldb_get_exception(), ret, ldb); 243 Py_RETURN_NONE; 244 } 245 246 static PyObject *py_dsdb_set_ntds_invocation_id(PyObject *self, PyObject *args) 247 { 248 PyObject *py_ldb, *py_guid; 249 bool ret; 250 struct GUID guid; 251 struct ldb_context *ldb; 252 if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_guid)) 253 return NULL; 254 255 PyErr_LDB_OR_RAISE(py_ldb, ldb); 256 GUID_from_string(PyString_AsString(py_guid), &guid); 257 258 ret = samdb_set_ntds_invocation_id(ldb, &guid); 259 if (!ret) { 260 PyErr_SetString(PyExc_RuntimeError, "set_ntds_invocation_id failed"); 261 return NULL; 262 } 263 Py_RETURN_NONE; 264 } 265 266 static PyObject *py_dsdb_set_opaque_integer(PyObject *self, PyObject *args) 267 { 268 PyObject *py_ldb; 269 int value; 270 int *old_val, *new_val; 271 char *py_opaque_name, *opaque_name_talloc; 272 struct ldb_context *ldb; 273 TALLOC_CTX *tmp_ctx; 274 275 if (!PyArg_ParseTuple(args, "Osi", &py_ldb, &py_opaque_name, &value)) 276 return NULL; 277 278 PyErr_LDB_OR_RAISE(py_ldb, ldb); 279 280 /* see if we have a cached copy */ 281 old_val = (int *)ldb_get_opaque(ldb, 282 py_opaque_name); 283 284 if (old_val) { 285 *old_val = value; 286 Py_RETURN_NONE; 287 } 288 289 tmp_ctx = talloc_new(ldb); 290 if (tmp_ctx == NULL) { 291 goto failed; 292 } 293 294 new_val = talloc(tmp_ctx, int); 295 if (!new_val) { 296 goto failed; 297 } 298 299 opaque_name_talloc = talloc_strdup(tmp_ctx, py_opaque_name); 300 if (!opaque_name_talloc) { 301 goto failed; 302 } 303 304 *new_val = value; 305 306 /* cache the domain_sid in the ldb */ 307 if (ldb_set_opaque(ldb, opaque_name_talloc, new_val) != LDB_SUCCESS) { 308 goto failed; 309 } 310 311 talloc_steal(ldb, new_val); 312 talloc_steal(ldb, opaque_name_talloc); 148 talloc_free(tmp_ctx); 149 return NULL; 150 } 151 152 load_interfaces(tmp_ctx, lpcfg_interfaces(lp_ctx), &ifaces); 153 154 count = iface_count(ifaces); 155 156 /* first count how many are not loopback addresses */ 157 for (ifcount = i = 0; i<count; i++) { 158 const char *ip = iface_n_ip(ifaces, i); 159 if (!(!all_interfaces && iface_same_net(ip, "127.0.0.1", "255.0.0.0"))) { 160 ifcount++; 161 } 162 } 163 164 pylist = PyList_New(ifcount); 165 for (ifcount = i = 0; i<count; i++) { 166 const char *ip = iface_n_ip(ifaces, i); 167 if (!(!all_interfaces && iface_same_net(ip, "127.0.0.1", "255.0.0.0"))) { 168 PyList_SetItem(pylist, ifcount, PyString_FromString(ip)); 169 ifcount++; 170 } 171 } 313 172 talloc_free(tmp_ctx); 314 315 Py_RETURN_NONE; 316 317 failed: 318 talloc_free(tmp_ctx); 319 PyErr_SetString(PyExc_RuntimeError, "Failed to set opaque integer into the ldb!\n"); 320 return NULL; 321 } 322 323 static PyObject *py_dsdb_set_global_schema(PyObject *self, PyObject *args) 324 { 325 PyObject *py_ldb; 326 struct ldb_context *ldb; 327 int ret; 328 if (!PyArg_ParseTuple(args, "O", &py_ldb)) 329 return NULL; 330 331 PyErr_LDB_OR_RAISE(py_ldb, ldb); 332 333 ret = dsdb_set_global_schema(ldb); 334 PyErr_LDB_ERROR_IS_ERR_RAISE(py_ldb_get_exception(), ret, ldb); 335 336 Py_RETURN_NONE; 337 } 338 339 static PyObject *py_dsdb_set_schema_from_ldif(PyObject *self, PyObject *args) 340 { 341 WERROR result; 342 char *pf, *df; 343 PyObject *py_ldb; 344 struct ldb_context *ldb; 345 346 if (!PyArg_ParseTuple(args, "Oss", &py_ldb, &pf, &df)) 347 return NULL; 348 349 PyErr_LDB_OR_RAISE(py_ldb, ldb); 350 351 result = dsdb_set_schema_from_ldif(ldb, pf, df); 352 PyErr_WERROR_IS_ERR_RAISE(result); 353 354 Py_RETURN_NONE; 355 } 356 357 static PyObject *py_dsdb_convert_schema_to_openldap(PyObject *self, PyObject *args) 358 { 359 char *target_str, *mapping; 360 PyObject *py_ldb; 361 struct ldb_context *ldb; 362 PyObject *ret; 363 char *retstr; 364 365 if (!PyArg_ParseTuple(args, "Oss", &py_ldb, &target_str, &mapping)) 366 return NULL; 367 368 PyErr_LDB_OR_RAISE(py_ldb, ldb); 369 370 retstr = dsdb_convert_schema_to_openldap(ldb, target_str, mapping); 371 if (!retstr) { 372 PyErr_SetString(PyExc_RuntimeError, "dsdb_convert_schema_to_openldap failed"); 373 return NULL; 374 } 375 ret = PyString_FromString(retstr); 376 talloc_free(retstr); 377 return ret; 378 } 379 380 static PyObject *py_dsdb_write_prefixes_from_schema_to_ldb(PyObject *self, PyObject *args) 381 { 382 PyObject *py_ldb; 383 struct ldb_context *ldb; 384 WERROR result; 385 struct dsdb_schema *schema; 386 387 if (!PyArg_ParseTuple(args, "O", &py_ldb)) 388 return NULL; 389 390 PyErr_LDB_OR_RAISE(py_ldb, ldb); 391 392 schema = dsdb_get_schema(ldb); 393 if (!schema) { 394 PyErr_SetString(PyExc_RuntimeError, "Failed to set find a schema on ldb!\n"); 395 return NULL; 396 } 397 398 result = dsdb_write_prefixes_from_schema_to_ldb(NULL, ldb, schema); 399 PyErr_WERROR_IS_ERR_RAISE(result); 400 401 Py_RETURN_NONE; 402 } 403 404 static PyObject *py_dsdb_set_schema_from_ldb(PyObject *self, PyObject *args) 405 { 406 PyObject *py_ldb; 407 struct ldb_context *ldb; 408 PyObject *py_from_ldb; 409 struct ldb_context *from_ldb; 410 struct dsdb_schema *schema; 411 int ret; 412 if (!PyArg_ParseTuple(args, "OO", &py_ldb, &py_from_ldb)) 413 return NULL; 414 415 PyErr_LDB_OR_RAISE(py_ldb, ldb); 416 417 PyErr_LDB_OR_RAISE(py_from_ldb, from_ldb); 418 419 schema = dsdb_get_schema(from_ldb); 420 if (!schema) { 421 PyErr_SetString(PyExc_RuntimeError, "Failed to set find a schema on 'from' ldb!\n"); 422 return NULL; 423 } 424 425 ret = dsdb_reference_schema(ldb, schema, true); 426 PyErr_LDB_ERROR_IS_ERR_RAISE(py_ldb_get_exception(), ret, ldb); 427 428 Py_RETURN_NONE; 429 } 430 431 static PyObject *py_dom_sid_to_rid(PyLdbObject *self, PyObject *args) 432 { 433 PyObject *py_sid; 434 struct dom_sid *sid; 435 uint32_t rid; 436 NTSTATUS status; 437 438 if(!PyArg_ParseTuple(args, "O", &py_sid)) 439 return NULL; 440 441 sid = dom_sid_parse_talloc(NULL, PyString_AsString(py_sid)); 442 443 status = dom_sid_split_rid(NULL, sid, NULL, &rid); 444 if (!NT_STATUS_IS_OK(status)) { 445 PyErr_SetString(PyExc_RuntimeError, "dom_sid_split_rid failed"); 446 return NULL; 447 } 448 449 return PyInt_FromLong(rid); 173 return pylist; 450 174 } 451 175 452 176 static PyMethodDef py_misc_methods[] = { 453 177 { "generate_random_str", (PyCFunction)py_generate_random_str, METH_VARARGS, 454 "random_password(len) -> string\n" 455 "Generate random password with specified length." }, 178 "generate_random_str(len) -> string\n" 179 "Generate random string with specified length." }, 180 { "generate_random_password", (PyCFunction)py_generate_random_password, 181 METH_VARARGS, "generate_random_password(min, max) -> string\n" 182 "Generate random password with a length >= min and <= max." }, 456 183 { "unix2nttime", (PyCFunction)py_unix2nttime, METH_VARARGS, 457 184 "unix2nttime(timestamp) -> nttime" }, 458 { "ldb_set_credentials", (PyCFunction)py_ldb_set_credentials, METH_VARARGS, 459 "ldb_set_credentials(ldb, credentials) -> None\n" 460 "Set credentials to use when connecting." }, 461 { "ldb_set_session_info", (PyCFunction)py_ldb_set_session_info, METH_VARARGS, 462 "ldb_set_session_info(ldb, session_info)\n" 463 "Set session info to use when connecting." }, 464 { "ldb_set_loadparm", (PyCFunction)py_ldb_set_loadparm, METH_VARARGS, 465 "ldb_set_loadparm(ldb, session_info)\n" 466 "Set loadparm context to use when connecting." }, 467 { "samdb_set_domain_sid", (PyCFunction)py_samdb_set_domain_sid, METH_VARARGS, 468 "samdb_set_domain_sid(samdb, sid)\n" 469 "Set SID of domain to use." }, 470 { "samdb_get_domain_sid", (PyCFunction)py_samdb_get_domain_sid, METH_VARARGS, 471 "samdb_get_domain_sid(samdb)\n" 472 "Get SID of domain in use." }, 473 { "ldb_register_samba_handlers", (PyCFunction)py_ldb_register_samba_handlers, METH_VARARGS, 474 "ldb_register_samba_handlers(ldb)\n" 475 "Register Samba-specific LDB modules and schemas." }, 476 { "ldb_set_utf8_casefold", (PyCFunction)py_ldb_set_utf8_casefold, METH_VARARGS, 477 "ldb_set_utf8_casefold(ldb)\n" 478 "Set the right Samba casefolding function for UTF8 charset." }, 479 { "dsdb_set_ntds_invocation_id", (PyCFunction)py_dsdb_set_ntds_invocation_id, METH_VARARGS, 480 NULL }, 481 { "dsdb_set_opaque_integer", (PyCFunction)py_dsdb_set_opaque_integer, METH_VARARGS, 482 NULL }, 483 { "dsdb_set_global_schema", (PyCFunction)py_dsdb_set_global_schema, METH_VARARGS, 484 NULL }, 485 { "dsdb_set_schema_from_ldif", (PyCFunction)py_dsdb_set_schema_from_ldif, METH_VARARGS, 486 NULL }, 487 { "dsdb_write_prefixes_from_schema_to_ldb", (PyCFunction)py_dsdb_write_prefixes_from_schema_to_ldb, METH_VARARGS, 488 NULL }, 489 { "dsdb_set_schema_from_ldb", (PyCFunction)py_dsdb_set_schema_from_ldb, METH_VARARGS, 490 NULL }, 491 { "dsdb_convert_schema_to_openldap", (PyCFunction)py_dsdb_convert_schema_to_openldap, METH_VARARGS, 492 NULL }, 493 { "dom_sid_to_rid", (PyCFunction)py_dom_sid_to_rid, METH_VARARGS, 494 NULL }, 185 { "nttime2unix", (PyCFunction)py_nttime2unix, METH_VARARGS, 186 "nttime2unix(nttime) -> timestamp" }, 187 { "nttime2string", (PyCFunction)py_nttime2string, METH_VARARGS, 188 "nttime2string(nttime) -> string" }, 495 189 { "set_debug_level", (PyCFunction)py_set_debug_level, METH_VARARGS, 496 190 "set debug level" }, 191 { "get_debug_level", (PyCFunction)py_get_debug_level, METH_NOARGS, 192 "get debug level" }, 193 { "interface_ips", (PyCFunction)py_interface_ips, METH_VARARGS, 194 "get interface IP address list"}, 497 195 { NULL } 498 196 }; 499 197 500 void init glue(void)198 void init_glue(void) 501 199 { 502 200 PyObject *m; 503 201 504 m = Py_InitModule3("glue", py_misc_methods, 202 debug_setup_talloc_log(); 203 204 m = Py_InitModule3("_glue", py_misc_methods, 505 205 "Python bindings for miscellaneous Samba functions."); 506 206 if (m == NULL) 507 207 return; 508 208 509 PyModule_AddObject(m, "version", PyString_FromString(SAMBA_VERSION_STRING)); 510 511 /* "userAccountControl" flags */ 512 PyModule_AddObject(m, "UF_NORMAL_ACCOUNT", PyInt_FromLong(UF_NORMAL_ACCOUNT)); 513 PyModule_AddObject(m, "UF_TEMP_DUPLICATE_ACCOUNT", PyInt_FromLong(UF_TEMP_DUPLICATE_ACCOUNT)); 514 PyModule_AddObject(m, "UF_SERVER_TRUST_ACCOUNT", PyInt_FromLong(UF_SERVER_TRUST_ACCOUNT)); 515 PyModule_AddObject(m, "UF_WORKSTATION_TRUST_ACCOUNT", PyInt_FromLong(UF_WORKSTATION_TRUST_ACCOUNT)); 516 PyModule_AddObject(m, "UF_INTERDOMAIN_TRUST_ACCOUNT", PyInt_FromLong(UF_INTERDOMAIN_TRUST_ACCOUNT)); 517 PyModule_AddObject(m, "UF_PASSWD_NOTREQD", PyInt_FromLong(UF_PASSWD_NOTREQD)); 518 PyModule_AddObject(m, "UF_ACCOUNTDISABLE", PyInt_FromLong(UF_ACCOUNTDISABLE)); 519 520 /* "groupType" flags */ 521 PyModule_AddObject(m, "GTYPE_SECURITY_BUILTIN_LOCAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_BUILTIN_LOCAL_GROUP)); 522 PyModule_AddObject(m, "GTYPE_SECURITY_GLOBAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_GLOBAL_GROUP)); 523 PyModule_AddObject(m, "GTYPE_SECURITY_DOMAIN_LOCAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_DOMAIN_LOCAL_GROUP)); 524 PyModule_AddObject(m, "GTYPE_SECURITY_UNIVERSAL_GROUP", PyInt_FromLong(GTYPE_SECURITY_UNIVERSAL_GROUP)); 525 PyModule_AddObject(m, "GTYPE_DISTRIBUTION_GLOBAL_GROUP", PyInt_FromLong(GTYPE_DISTRIBUTION_GLOBAL_GROUP)); 526 PyModule_AddObject(m, "GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP", PyInt_FromLong(GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP)); 527 PyModule_AddObject(m, "GTYPE_DISTRIBUTION_UNIVERSAL_GROUP", PyInt_FromLong(GTYPE_DISTRIBUTION_UNIVERSAL_GROUP)); 528 529 /* "sAMAccountType" flags */ 530 PyModule_AddObject(m, "ATYPE_NORMAL_ACCOUNT", PyInt_FromLong(ATYPE_NORMAL_ACCOUNT)); 531 PyModule_AddObject(m, "ATYPE_WORKSTATION_TRUST", PyInt_FromLong(ATYPE_WORKSTATION_TRUST)); 532 PyModule_AddObject(m, "ATYPE_INTERDOMAIN_TRUST", PyInt_FromLong(ATYPE_INTERDOMAIN_TRUST)); 533 PyModule_AddObject(m, "ATYPE_SECURITY_GLOBAL_GROUP", PyInt_FromLong(ATYPE_SECURITY_GLOBAL_GROUP)); 534 PyModule_AddObject(m, "ATYPE_SECURITY_LOCAL_GROUP", PyInt_FromLong(ATYPE_SECURITY_LOCAL_GROUP)); 535 PyModule_AddObject(m, "ATYPE_SECURITY_UNIVERSAL_GROUP", PyInt_FromLong(ATYPE_SECURITY_UNIVERSAL_GROUP)); 536 PyModule_AddObject(m, "ATYPE_DISTRIBUTION_GLOBAL_GROUP", PyInt_FromLong(ATYPE_DISTRIBUTION_GLOBAL_GROUP)); 537 PyModule_AddObject(m, "ATYPE_DISTRIBUTION_LOCAL_GROUP", PyInt_FromLong(ATYPE_DISTRIBUTION_LOCAL_GROUP)); 538 PyModule_AddObject(m, "ATYPE_DISTRIBUTION_UNIVERSAL_GROUP", PyInt_FromLong(ATYPE_DISTRIBUTION_UNIVERSAL_GROUP)); 539 540 /* "domainFunctionality", "forestFunctionality" flags in the rootDSE */ 541 PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2000", PyInt_FromLong(DS_DOMAIN_FUNCTION_2000)); 542 PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2003_MIXED", PyInt_FromLong(DS_DOMAIN_FUNCTION_2003_MIXED)); 543 PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2003", PyInt_FromLong(DS_DOMAIN_FUNCTION_2003)); 544 PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2008", PyInt_FromLong(DS_DOMAIN_FUNCTION_2008)); 545 PyModule_AddObject(m, "DS_DOMAIN_FUNCTION_2008_R2", PyInt_FromLong(DS_DOMAIN_FUNCTION_2008_R2)); 546 547 /* "domainControllerFunctionality" flags in the rootDSE */ 548 PyModule_AddObject(m, "DS_DC_FUNCTION_2000", PyInt_FromLong(DS_DC_FUNCTION_2000)); 549 PyModule_AddObject(m, "DS_DC_FUNCTION_2003", PyInt_FromLong(DS_DC_FUNCTION_2003)); 550 PyModule_AddObject(m, "DS_DC_FUNCTION_2008", PyInt_FromLong(DS_DC_FUNCTION_2008)); 551 PyModule_AddObject(m, "DS_DC_FUNCTION_2008_R2", PyInt_FromLong(DS_DC_FUNCTION_2008_R2)); 552 } 553 209 PyModule_AddObject(m, "version", 210 PyString_FromString(SAMBA_VERSION_STRING)); 211 212 /* one of the most annoying things about python scripts is 213 that they don't die when you hit control-C. This fixes that 214 sillyness. As we do all database operations using 215 transactions, this is also safe. 216 */ 217 signal(SIGINT, SIG_DFL); 218 } 219 -
vendor/current/source4/scripting/python/samba/__init__.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. 4 4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008 5 # 5 # 6 6 # Based on the original in EJS: 7 7 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005 8 # 8 # 9 9 # This program is free software; you can redistribute it and/or modify 10 10 # it under the terms of the GNU General Public License as published by 11 11 # the Free Software Foundation; either version 3 of the License, or 12 12 # (at your option) any later version. 13 # 13 # 14 14 # This program is distributed in the hope that it will be useful, 15 15 # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 17 # GNU General Public License for more details. 18 # 18 # 19 19 # You should have received a copy of the GNU General Public License 20 20 # along with this program. If not, see <http://www.gnu.org/licenses/>. … … 26 26 27 27 import os 28 29 def _in_source_tree(): 30 """Check whether the script is being run from the source dir. """ 31 return os.path.exists("%s/../../../selftest/skip" % os.path.dirname(__file__)) 32 33 34 # When running, in-tree, make sure bin/python is in the PYTHONPATH 35 if _in_source_tree(): 36 import sys 37 srcdir = "%s/../../.." % os.path.dirname(__file__) 38 sys.path.append("%s/bin/python" % srcdir) 39 default_ldb_modules_dir = "%s/bin/modules/ldb" % srcdir 40 else: 41 default_ldb_modules_dir = None 28 import sys 29 30 def source_tree_topdir(): 31 '''return the top level directory (the one containing the source4 directory)''' 32 paths = [ "../../..", "../../../.." ] 33 for p in paths: 34 topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p)) 35 if os.path.exists(os.path.join(topdir, 'source4')): 36 return topdir 37 raise RuntimeError("unable to find top level source directory") 38 39 def in_source_tree(): 40 '''return True if we are running from within the samba source tree''' 41 try: 42 topdir = source_tree_topdir() 43 except RuntimeError: 44 return False 45 return True 46 42 47 43 48 44 49 import ldb 45 import glue 46 47 class Ldb( ldb.Ldb):48 """Simple Samba-specific LDB subclass that takes care 50 from samba._ldb import Ldb as _Ldb 51 52 class Ldb(_Ldb): 53 """Simple Samba-specific LDB subclass that takes care 49 54 of setting up the modules dir, credentials pointers, etc. 50 51 Please note that this is intended to be for all Samba LDB files, 52 not necessarily the Sam database. For Sam-specific helper 55 56 Please note that this is intended to be for all Samba LDB files, 57 not necessarily the Sam database. For Sam-specific helper 53 58 functions see samdb.py. 54 59 """ 60 55 61 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None, 56 62 credentials=None, flags=0, options=None): … … 66 72 67 73 This is different from a regular Ldb file in that the Samba-specific 68 modules-dir is used by default and that credentials and session_info 74 modules-dir is used by default and that credentials and session_info 69 75 can be passed through (required by some modules). 70 76 """ … … 72 78 if modules_dir is not None: 73 79 self.set_modules_dir(modules_dir) 74 elif default_ldb_modules_dir is not None:75 self.set_modules_dir(default_ldb_modules_dir)76 80 elif lp is not None: 77 81 self.set_modules_dir(os.path.join(lp.get("modules dir"), "ldb")) … … 89 93 # objectSid and objectGUID etc must take precedence over the 'binary 90 94 # attribute' declaration in the schema 91 glue.ldb_register_samba_handlers(self)95 self.register_samba_handlers() 92 96 93 97 # TODO set debug 94 def msg(l, text):98 def msg(l, text): 95 99 print text 96 100 #self.set_debug(msg) 97 101 98 glue.ldb_set_utf8_casefold(self)102 self.set_utf8_casefold() 99 103 100 104 # Allow admins to force non-sync ldb for all databases 101 105 if lp is not None: 102 106 nosync_p = lp.get("nosync", "ldb") 103 if nosync_p is not None and nosync_p == true: 104 flags |= FLG_NOSYNC 107 if nosync_p is not None and nosync_p == True: 108 flags |= ldb.FLG_NOSYNC 109 110 self.set_create_perms(0600) 105 111 106 112 if url is not None: 107 113 self.connect(url, flags, options) 108 114 109 def set_credentials(self, credentials): 110 glue.ldb_set_credentials(self, credentials) 111 112 def set_session_info(self, session_info): 113 glue.ldb_set_session_info(self, session_info) 114 115 def set_loadparm(self, lp_ctx): 116 glue.ldb_set_loadparm(self, lp_ctx) 117 118 def searchone(self, attribute, basedn=None, expression=None, 115 def searchone(self, attribute, basedn=None, expression=None, 119 116 scope=ldb.SCOPE_BASE): 120 117 """Search for one attribute as a string. 121 118 122 119 :param basedn: BaseDN for the search. 123 120 :param attribute: Name of the attribute … … 134 131 135 132 def erase_users_computers(self, dn): 136 """Erases user and computer objects from our AD. This is needed since the 'samldb' module denies the deletion of primary groups. Therefore all groups shouldn't be primary somewhere anymore.""" 133 """Erases user and computer objects from our AD. 134 135 This is needed since the 'samldb' module denies the deletion of primary 136 groups. Therefore all groups shouldn't be primary somewhere anymore. 137 """ 137 138 138 139 try: 139 140 res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[], 140 141 expression="(|(objectclass=user)(objectclass=computer))") 141 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): 142 # Ignore no such object errors 143 return 144 pass 142 except ldb.LdbError, (errno, _): 143 if errno == ldb.ERR_NO_SUCH_OBJECT: 144 # Ignore no such object errors 145 return 146 else: 147 raise 145 148 146 149 try: 147 150 for msg in res: 148 self.delete(msg.dn) 149 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): 150 # Ignore no such object errors 151 return 151 self.delete(msg.dn, ["relax:0"]) 152 except ldb.LdbError, (errno, _): 153 if errno != ldb.ERR_NO_SUCH_OBJECT: 154 # Ignore no such object errors 155 raise 152 156 153 157 def erase_except_schema_controlled(self): 154 """Erase this ldb, removing all records, except those that are controlled by Samba4's schema.""" 158 """Erase this ldb. 159 160 :note: Removes all records, except those that are controlled by 161 Samba4's schema. 162 """ 155 163 156 164 basedn = "" … … 160 168 161 169 # Delete the 'visible' records, and the invisble 'deleted' records (if this DB supports it) 162 for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 163 164 [], controls=["show_deleted:0"]):170 for msg in self.search(basedn, ldb.SCOPE_SUBTREE, 171 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", 172 [], controls=["show_deleted:0", "show_recycled:0"]): 165 173 try: 166 self.delete(msg.dn )167 except ldb.LdbError, ( ldb.ERR_NO_SUCH_OBJECT, _):168 # Ignore no such object errors169 pass170 171 res = self.search(basedn, ldb.SCOPE_SUBTREE, 172 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",173 [], controls=["show_deleted:0"])174 self.delete(msg.dn, ["relax:0"]) 175 except ldb.LdbError, (errno, _): 176 if errno != ldb.ERR_NO_SUCH_OBJECT: 177 # Ignore no such object errors 178 raise 179 180 res = self.search(basedn, ldb.SCOPE_SUBTREE, 181 "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", [], controls=["show_deleted:0", "show_recycled:0"]) 174 182 assert len(res) == 0 175 183 176 184 # delete the specials 177 for attr in ["@SUBCLASSES", "@MODULES", 185 for attr in ["@SUBCLASSES", "@MODULES", 178 186 "@OPTIONS", "@PARTITION", "@KLUDGEACL"]: 179 187 try: 180 self.delete(attr) 181 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): 182 # Ignore missing dn errors 183 pass 188 self.delete(attr, ["relax:0"]) 189 except ldb.LdbError, (errno, _): 190 if errno != ldb.ERR_NO_SUCH_OBJECT: 191 # Ignore missing dn errors 192 raise 184 193 185 194 def erase(self): 186 195 """Erase this ldb, removing all records.""" 187 188 196 self.erase_except_schema_controlled() 189 197 … … 191 199 for attr in ["@INDEXLIST", "@ATTRIBUTES"]: 192 200 try: 193 self.delete(attr) 194 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): 195 # Ignore missing dn errors 196 pass 197 198 def erase_partitions(self): 199 """Erase an ldb, removing all records.""" 200 201 def erase_recursive(self, dn): 202 try: 203 res = self.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=[], 204 controls=["show_deleted:0"]) 205 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): 206 # Ignore no such object errors 207 return 208 pass 209 210 for msg in res: 211 erase_recursive(self, msg.dn) 212 213 try: 214 self.delete(dn) 215 except ldb.LdbError, (ldb.ERR_NO_SUCH_OBJECT, _): 216 # Ignore no such object errors 217 pass 218 219 res = self.search("", ldb.SCOPE_BASE, "(objectClass=*)", 220 ["namingContexts"]) 221 assert len(res) == 1 222 if not "namingContexts" in res[0]: 223 return 224 for basedn in res[0]["namingContexts"]: 225 # Try to delete user/computer accounts to allow deletion of groups 226 self.erase_users_computers(basedn) 227 # Try and erase from the bottom-up in the tree 228 erase_recursive(self, basedn) 201 self.delete(attr, ["relax:0"]) 202 except ldb.LdbError, (errno, _): 203 if errno != ldb.ERR_NO_SUCH_OBJECT: 204 # Ignore missing dn errors 205 raise 229 206 230 207 def load_ldif_file_add(self, ldif_path): … … 235 212 self.add_ldif(open(ldif_path, 'r').read()) 236 213 237 def add_ldif(self, ldif ):214 def add_ldif(self, ldif, controls=None): 238 215 """Add data based on a LDIF string. 239 216 … … 242 219 for changetype, msg in self.parse_ldif(ldif): 243 220 assert changetype == ldb.CHANGETYPE_NONE 244 self.add(msg )245 246 def modify_ldif(self, ldif ):221 self.add(msg, controls) 222 223 def modify_ldif(self, ldif, controls=None): 247 224 """Modify database based on a LDIF string. 248 225 … … 250 227 """ 251 228 for changetype, msg in self.parse_ldif(ldif): 252 self.modify(msg) 253 254 def set_domain_sid(self, sid): 255 """Change the domain SID used by this LDB. 256 257 :param sid: The new domain sid to use. 258 """ 259 glue.samdb_set_domain_sid(self, sid) 260 261 def domain_sid(self): 262 """Read the domain SID used by this LDB. 263 264 """ 265 glue.samdb_get_domain_sid(self) 266 267 def set_schema_from_ldif(self, pf, df): 268 glue.dsdb_set_schema_from_ldif(self, pf, df) 269 270 def set_schema_from_ldb(self, ldb): 271 glue.dsdb_set_schema_from_ldb(self, ldb) 272 273 def write_prefixes_from_schema(self): 274 glue.dsdb_write_prefixes_from_schema_to_ldb(self) 275 276 def convert_schema_to_openldap(self, target, mapping): 277 return glue.dsdb_convert_schema_to_openldap(self, target, mapping) 278 279 def set_invocation_id(self, invocation_id): 280 """Set the invocation id for this SamDB handle. 281 282 :param invocation_id: GUID of the invocation id. 283 """ 284 glue.dsdb_set_ntds_invocation_id(self, invocation_id) 285 286 def set_opaque_integer(self, name, value): 287 """Set an integer as an opaque (a flag or other value) value on the database 288 289 :param name: The name for the opaque value 290 :param value: The integer value 291 """ 292 glue.dsdb_set_opaque_integer(self, name, value) 229 if changetype == ldb.CHANGETYPE_ADD: 230 self.add(msg, controls) 231 else: 232 self.modify(msg, controls) 293 233 294 234 295 235 def substitute_var(text, values): 296 """ substitute strings of the form ${NAME} in str, replacing297 with substitutions from subobj.298 236 """Substitute strings of the form ${NAME} in str, replacing 237 with substitutions from values. 238 299 239 :param text: Text in which to subsitute. 300 240 :param values: Dictionary with keys and values. … … 310 250 311 251 def check_all_substituted(text): 312 """Make sure that all substitution variables in a string have been replaced. 252 """Check that all substitution variables in a string have been replaced. 253 313 254 If not, raise an exception. 314 255 315 256 :param text: The text to search for substitution variables 316 257 """ 317 258 if not "${" in text: 318 259 return 319 260 320 261 var_start = text.find("${") 321 262 var_end = text.find("}", var_start) 322 323 raise Exception("Not all variables substituted: %s" % text[var_start:var_end+1]) 263 264 raise Exception("Not all variables substituted: %s" % 265 text[var_start:var_end+1]) 266 267 268 def read_and_sub_file(file_name, subst_vars): 269 """Read a file and sub in variables found in it 270 271 :param file_name: File to be read (typically from setup directory) 272 param subst_vars: Optional variables to subsitute in the file. 273 """ 274 data = open(file_name, 'r').read() 275 if subst_vars is not None: 276 data = substitute_var(data, subst_vars) 277 check_all_substituted(data) 278 return data 279 280 281 def setup_file(template, fname, subst_vars=None): 282 """Setup a file in the private dir. 283 284 :param template: Path of the template file. 285 :param fname: Path of the file to create. 286 :param subst_vars: Substitution variables. 287 """ 288 if os.path.exists(fname): 289 os.unlink(fname) 290 291 data = read_and_sub_file(template, subst_vars) 292 f = open(fname, 'w') 293 try: 294 f.write(data) 295 finally: 296 f.close() 324 297 325 298 … … 335 308 336 309 337 def dom_sid_to_rid(sid_str): 338 """Converts a domain SID to the relative RID. 339 340 :param sid_str: The domain SID formatted as string 341 """ 342 343 return glue.dom_sid_to_rid(sid_str) 344 345 346 version = glue.version 347 348 # "userAccountControl" flags 349 UF_NORMAL_ACCOUNT = glue.UF_NORMAL_ACCOUNT 350 UF_TEMP_DUPLICATE_ACCOUNT = glue.UF_TEMP_DUPLICATE_ACCOUNT 351 UF_SERVER_TRUST_ACCOUNT = glue.UF_SERVER_TRUST_ACCOUNT 352 UF_WORKSTATION_TRUST_ACCOUNT = glue.UF_WORKSTATION_TRUST_ACCOUNT 353 UF_INTERDOMAIN_TRUST_ACCOUNT = glue.UF_INTERDOMAIN_TRUST_ACCOUNT 354 UF_PASSWD_NOTREQD = glue.UF_PASSWD_NOTREQD 355 UF_ACCOUNTDISABLE = glue.UF_ACCOUNTDISABLE 356 357 # "groupType" flags 358 GTYPE_SECURITY_BUILTIN_LOCAL_GROUP = glue.GTYPE_SECURITY_BUILTIN_LOCAL_GROUP 359 GTYPE_SECURITY_GLOBAL_GROUP = glue.GTYPE_SECURITY_GLOBAL_GROUP 360 GTYPE_SECURITY_DOMAIN_LOCAL_GROUP = glue.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP 361 GTYPE_SECURITY_UNIVERSAL_GROUP = glue.GTYPE_SECURITY_UNIVERSAL_GROUP 362 GTYPE_DISTRIBUTION_GLOBAL_GROUP = glue.GTYPE_DISTRIBUTION_GLOBAL_GROUP 363 GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP = glue.GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP 364 GTYPE_DISTRIBUTION_UNIVERSAL_GROUP = glue.GTYPE_DISTRIBUTION_UNIVERSAL_GROUP 365 366 # "sAMAccountType" flags 367 ATYPE_NORMAL_ACCOUNT = glue.ATYPE_NORMAL_ACCOUNT 368 ATYPE_WORKSTATION_TRUST = glue.ATYPE_WORKSTATION_TRUST 369 ATYPE_INTERDOMAIN_TRUST = glue.ATYPE_INTERDOMAIN_TRUST 370 ATYPE_SECURITY_GLOBAL_GROUP = glue.ATYPE_SECURITY_GLOBAL_GROUP 371 ATYPE_SECURITY_LOCAL_GROUP = glue.ATYPE_SECURITY_LOCAL_GROUP 372 ATYPE_SECURITY_UNIVERSAL_GROUP = glue.ATYPE_SECURITY_UNIVERSAL_GROUP 373 ATYPE_DISTRIBUTION_GLOBAL_GROUP = glue.ATYPE_DISTRIBUTION_GLOBAL_GROUP 374 ATYPE_DISTRIBUTION_LOCAL_GROUP = glue.ATYPE_DISTRIBUTION_LOCAL_GROUP 375 ATYPE_DISTRIBUTION_UNIVERSAL_GROUP = glue.ATYPE_DISTRIBUTION_UNIVERSAL_GROUP 376 377 # "domainFunctionality", "forestFunctionality" flags in the rootDSE */ 378 DS_DOMAIN_FUNCTION_2000 = glue.DS_DOMAIN_FUNCTION_2000 379 DS_DOMAIN_FUNCTION_2003_MIXED = glue.DS_DOMAIN_FUNCTION_2003_MIXED 380 DS_DOMAIN_FUNCTION_2003 = glue.DS_DOMAIN_FUNCTION_2003 381 DS_DOMAIN_FUNCTION_2008 = glue.DS_DOMAIN_FUNCTION_2008 382 DS_DOMAIN_FUNCTION_2008_R2 = glue.DS_DOMAIN_FUNCTION_2008_R2 383 384 # "domainControllerFunctionality" flags in the rootDSE */ 385 DS_DC_FUNCTION_2000 = glue.DS_DC_FUNCTION_2000 386 DS_DC_FUNCTION_2003 = glue.DS_DC_FUNCTION_2003 387 DS_DC_FUNCTION_2008 = glue.DS_DC_FUNCTION_2008 388 DS_DC_FUNCTION_2008_R2 = glue.DS_DC_FUNCTION_2008_R2 389 310 def import_bundled_package(modulename, location): 311 """Import the bundled version of a package. 312 313 :note: This should only be called if the system version of the package 314 is not adequate. 315 316 :param modulename: Module name to import 317 :param location: Location to add to sys.path (can be relative to 318 ${srcdir}/lib) 319 """ 320 if in_source_tree(): 321 sys.path.insert(0, os.path.join(source_tree_topdir(), "lib", location)) 322 sys.modules[modulename] = __import__(modulename) 323 else: 324 sys.modules[modulename] = __import__( 325 "samba.external.%s" % modulename, fromlist=["samba.external"]) 326 327 328 def ensure_external_module(modulename, location): 329 """Add a location to sys.path if an external dependency can't be found. 330 331 :param modulename: Module name to import 332 :param location: Location to add to sys.path (can be relative to 333 ${srcdir}/lib) 334 """ 335 try: 336 __import__(modulename) 337 except ImportError: 338 import_bundled_package(modulename, location) 339 340 341 from samba import _glue 342 version = _glue.version 343 interface_ips = _glue.interface_ips 344 set_debug_level = _glue.set_debug_level 345 get_debug_level = _glue.get_debug_level 346 unix2nttime = _glue.unix2nttime 347 nttime2string = _glue.nttime2string 348 nttime2unix = _glue.nttime2unix 349 unix2nttime = _glue.unix2nttime 350 generate_random_password = _glue.generate_random_password -
vendor/current/source4/scripting/python/samba/getopt.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Samba-specific bits for optparse 4 4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 5 # 5 # 6 6 # This program is free software; you can redistribute it and/or modify 7 7 # it under the terms of the GNU General Public License as published by 8 8 # the Free Software Foundation; either version 3 of the License, or 9 9 # (at your option) any later version. 10 # 10 # 11 11 # This program is distributed in the hope that it will be useful, 12 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 14 # GNU General Public License for more details. 15 # 15 # 16 16 # You should have received a copy of the GNU General Public License 17 17 # along with this program. If not, see <http://www.gnu.org/licenses/>. … … 20 20 """Support for parsing Samba-related command-line options.""" 21 21 22 import optparse23 from credentials import Credentials, DONT_USE_KERBEROS, MUST_USE_KERBEROS24 from hostconfig import Hostconfig25 26 22 __docformat__ = "restructuredText" 23 24 import optparse, os 25 from samba.credentials import ( 26 Credentials, 27 DONT_USE_KERBEROS, 28 MUST_USE_KERBEROS, 29 ) 30 from samba.hostconfig import Hostconfig 31 import sys 32 27 33 28 34 class SambaOptions(optparse.OptionGroup): 29 35 """General Samba-related command line options.""" 30 def __init__(self, parser): 36 37 def __init__(self, parser): 38 from samba.param import LoadParm 31 39 optparse.OptionGroup.__init__(self, parser, "Samba Common Options") 32 40 self.add_option("-s", "--configfile", action="callback", 33 type=str, metavar="FILE", help="Configuration file", 41 type=str, metavar="FILE", help="Configuration file", 34 42 callback=self._load_configfile) 43 self.add_option("-d", "--debuglevel", action="callback", 44 type=int, metavar="DEBUGLEVEL", help="debug level", 45 callback=self._set_debuglevel) 46 self.add_option("--option", action="callback", 47 type=str, metavar="OPTION", help="set smb.conf option from command line", 48 callback=self._set_option) 49 self.add_option("--realm", action="callback", 50 type=str, metavar="REALM", help="set the realm name", 51 callback=self._set_realm) 35 52 self._configfile = None 53 self._lp = LoadParm() 36 54 37 55 def get_loadparm_path(self): … … 42 60 self._configfile = arg 43 61 62 def _set_debuglevel(self, option, opt_str, arg, parser): 63 self._lp.set('debug level', str(arg)) 64 65 def _set_realm(self, option, opt_str, arg, parser): 66 self._lp.set('realm', arg) 67 68 def _set_option(self, option, opt_str, arg, parser): 69 if arg.find('=') == -1: 70 print("--option takes a 'a=b' argument") 71 sys.exit(1) 72 a = arg.split('=') 73 self._lp.set(a[0], a[1]) 74 44 75 def get_loadparm(self): 45 76 """Return a loadparm object with data specified on the command line. """ 46 import os, param47 lp = param.LoadParm()48 77 if self._configfile is not None: 49 lp.load(self._configfile)78 self._lp.load(self._configfile) 50 79 elif os.getenv("SMB_CONF_PATH") is not None: 51 lp.load(os.getenv("SMB_CONF_PATH"))80 self._lp.load(os.getenv("SMB_CONF_PATH")) 52 81 else: 53 lp.load_default()54 return lp82 self._lp.load_default() 83 return self._lp 55 84 56 85 def get_hostconfig(self): … … 62 91 def __init__(self, parser): 63 92 optparse.OptionGroup.__init__(self, parser, "Version Options") 93 self.add_option("--version", action="callback", 94 callback=self._display_version, 95 help="Display version number") 96 97 def _display_version(self, option, opt_str, arg, parser): 98 import samba 99 print samba.version 100 sys.exit(0) 64 101 65 102 … … 67 104 """Command line options for specifying credentials.""" 68 105 def __init__(self, parser): 69 self.no_pass = False 106 self.no_pass = True 107 self.ipaddress = None 70 108 optparse.OptionGroup.__init__(self, parser, "Credentials Options") 71 109 self.add_option("--simple-bind-dn", metavar="DN", action="callback", … … 74 112 self.add_option("--password", metavar="PASSWORD", action="callback", 75 113 help="Password", type=str, callback=self._set_password) 76 self.add_option("-U", "--username", metavar="USERNAME", 114 self.add_option("-U", "--username", metavar="USERNAME", 77 115 action="callback", type=str, 78 116 help="Username", callback=self._parse_username) 79 self.add_option("-W", "--workgroup", metavar="WORKGROUP", 117 self.add_option("-W", "--workgroup", metavar="WORKGROUP", 80 118 action="callback", type=str, 81 119 help="Workgroup", callback=self._parse_workgroup) 82 120 self.add_option("-N", "--no-pass", action="store_true", 83 121 help="Don't ask for a password") 84 self.add_option("-k", "--kerberos", metavar="KERBEROS", 122 self.add_option("-k", "--kerberos", metavar="KERBEROS", 85 123 action="callback", type=str, 86 124 help="Use Kerberos", callback=self._set_kerberos) 125 self.add_option("", "--ipaddress", metavar="IPADDRESS", 126 action="callback", type=str, 127 help="IP address of server", callback=self._set_ipaddress) 87 128 self.creds = Credentials() 88 129 … … 95 136 def _set_password(self, option, opt_str, arg, parser): 96 137 self.creds.set_password(arg) 138 self.no_pass = False 139 140 def _set_ipaddress(self, option, opt_str, arg, parser): 141 self.ipaddress = arg 97 142 98 143 def _set_kerberos(self, option, opt_str, arg, parser): 99 if bool(arg) or arg.lower() == "yes":144 if arg.lower() in ["yes", 'true', '1']: 100 145 self.creds.set_kerberos_state(MUST_USE_KERBEROS) 146 elif arg.lower() in ["no", 'false', '0']: 147 self.creds.set_kerberos_state(DONT_USE_KERBEROS) 101 148 else: 102 self.creds.set_kerberos_state(DONT_USE_KERBEROS)149 raise optparse.BadOptionErr("invalid kerberos option: %s" % arg) 103 150 104 151 def _set_simple_bind_dn(self, option, opt_str, arg, parser): 105 152 self.creds.set_bind_dn(arg) 106 153 107 def get_credentials(self, lp ):154 def get_credentials(self, lp, fallback_machine=False): 108 155 """Obtain the credentials set on the command-line. 109 156 … … 112 159 """ 113 160 self.creds.guess(lp) 114 if notself.no_pass:161 if self.no_pass: 115 162 self.creds.set_cmdline_callbacks() 163 164 # possibly fallback to using the machine account, if we have 165 # access to the secrets db 166 if fallback_machine and not self.creds.authentication_requested(): 167 try: 168 self.creds.set_machine_account(lp) 169 except Exception: 170 pass 171 116 172 return self.creds 173 174 class CredentialsOptionsDouble(CredentialsOptions): 175 """Command line options for specifying credentials of two servers.""" 176 def __init__(self, parser): 177 CredentialsOptions.__init__(self, parser) 178 self.no_pass2 = True 179 self.add_option("--simple-bind-dn2", metavar="DN2", action="callback", 180 callback=self._set_simple_bind_dn2, type=str, 181 help="DN to use for a simple bind") 182 self.add_option("--password2", metavar="PASSWORD2", action="callback", 183 help="Password", type=str, callback=self._set_password2) 184 self.add_option("--username2", metavar="USERNAME2", 185 action="callback", type=str, 186 help="Username for second server", callback=self._parse_username2) 187 self.add_option("--workgroup2", metavar="WORKGROUP2", 188 action="callback", type=str, 189 help="Workgroup for second server", callback=self._parse_workgroup2) 190 self.add_option("--no-pass2", action="store_true", 191 help="Don't ask for a password for the second server") 192 self.add_option("--kerberos2", metavar="KERBEROS2", 193 action="callback", type=str, 194 help="Use Kerberos", callback=self._set_kerberos2) 195 self.creds2 = Credentials() 196 197 def _parse_username2(self, option, opt_str, arg, parser): 198 self.creds2.parse_string(arg) 199 200 def _parse_workgroup2(self, option, opt_str, arg, parser): 201 self.creds2.set_domain(arg) 202 203 def _set_password2(self, option, opt_str, arg, parser): 204 self.creds2.set_password(arg) 205 self.no_pass2 = False 206 207 def _set_kerberos2(self, option, opt_str, arg, parser): 208 if bool(arg) or arg.lower() == "yes": 209 self.creds2.set_kerberos_state(MUST_USE_KERBEROS) 210 else: 211 self.creds2.set_kerberos_state(DONT_USE_KERBEROS) 212 213 def _set_simple_bind_dn2(self, option, opt_str, arg, parser): 214 self.creds2.set_bind_dn(arg) 215 216 def get_credentials2(self, lp, guess=True): 217 """Obtain the credentials set on the command-line. 218 219 :param lp: Loadparm object to use. 220 :param guess: Try guess Credentials from environment 221 :return: Credentials object 222 """ 223 if guess: 224 self.creds2.guess(lp) 225 elif not self.creds2.get_username(): 226 self.creds2.set_anonymous() 227 228 if self.no_pass2: 229 self.creds2.set_cmdline_callbacks() 230 return self.creds2 -
vendor/current/source4/scripting/python/samba/hostconfig.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. 4 4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008 5 # 5 # 6 6 # This program is free software; you can redistribute it and/or modify 7 7 # it under the terms of the GNU General Public License as published by 8 8 # the Free Software Foundation; either version 3 of the License, or 9 9 # (at your option) any later version. 10 # 10 # 11 11 # This program is distributed in the hope that it will be useful, 12 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 14 # GNU General Public License for more details. 15 # 15 # 16 16 # You should have received a copy of the GNU General Public License 17 17 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 18 # 19 19 20 """Local host configuration.""" 21 20 22 from samdb import SamDB 21 23 22 24 class Hostconfig(object): 23 """Aggregate object that contains all information about the configuration 25 """Aggregate object that contains all information about the configuration 24 26 of a Samba host.""" 25 27 26 def __init__(self, lp): 28 def __init__(self, lp): 27 29 self.lp = lp 28 30 31 def get_shares(self): 32 return SharesContainer(self.lp) 33 29 34 def get_samdb(self, session_info, credentials): 30 return SamDB(url=self.lp.get("sam database"), 31 session_info=session_info, credentials=credentials, 35 """Access the SamDB host. 36 37 :param session_info: Session info to use 38 :param credentials: Credentials to access the SamDB with 39 """ 40 return SamDB(url=self.lp.get("sam database"), 41 session_info=session_info, credentials=credentials, 32 42 lp=self.lp) 33 43 44 45 # TODO: Rather than accessing Loadparm directly here, we should really 46 # have bindings to the param/shares.c and use those. 47 48 49 class SharesContainer(object): 50 """A shares container.""" 51 52 def __init__(self, lp): 53 self._lp = lp 54 55 def __getitem__(self, name): 56 if name == "global": 57 # [global] is not a share 58 raise KeyError 59 return Share(self._lp[name]) 60 61 def __len__(self): 62 if "global" in self._lp.services(): 63 return len(self._lp)-1 64 return len(self._lp) 65 66 def keys(self): 67 return [name for name in self._lp.services() if name != "global"] 68 69 def __iter__(self): 70 return iter(self.keys()) 71 72 73 class Share(object): 74 """A file share.""" 75 76 def __init__(self, service): 77 self._service = service 78 79 def __getitem__(self, name): 80 return self._service[name] 81 82 def __setitem__(self, name, value): 83 self._service[name] = value -
vendor/current/source4/scripting/python/samba/idmap.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 23 23 __docformat__ = "restructuredText" 24 24 25 import ldb 25 26 import samba 26 27 … … 51 52 options=options) 52 53 53 def setup_name_mapping(self, sid, type, unixid): 54 55 def increment_xid(self): 56 """Increment xidNumber, if not present it create and assign it to the lowerBound 57 58 :return xid can that be used for SID/unixid mapping 59 """ 60 res = self.search(expression="dn=CN=CONFIG", base="", 61 scope=ldb.SCOPE_SUBTREE) 62 id = res[0].get("xidNumber") 63 flag = ldb.FLAG_MOD_REPLACE 64 if id is None: 65 id = res[0].get("lowerBound") 66 flag = ldb.FLAG_MOD_ADD 67 newid = int(str(id)) + 1 68 msg = ldb.Message() 69 msg.dn = ldb.Dn(self, "CN=CONFIG") 70 msg["xidNumber"] = ldb.MessageElement(str(newid), flag, "xidNumber") 71 self.modify(msg) 72 return id 73 74 def setup_name_mapping(self, sid, type, unixid=None): 54 75 """Setup a mapping between a sam name and a unix name. 55 76 56 77 :param sid: SID of the NT-side of the mapping. 57 :param unixname: Unix name to map to.78 :param unixname: Unix id to map to, if none supplied the next one will be selected 58 79 """ 80 if unixid is None: 81 unixid = self.increment_xid() 59 82 type_string = "" 60 83 if type == self.TYPE_UID: -
vendor/current/source4/scripting/python/samba/ms_display_specifiers.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # 3 3 # Create DisplaySpecifiers LDIF (as a string) from the documents provided by -
vendor/current/source4/scripting/python/samba/ms_schema.py
r414 r740 1 #!/usr/bin/env python2 1 # 3 2 # create schema.ldif (as a string) from WSPP documentation … … 6 5 # 7 6 7 """Generate LDIF from WSPP documentation.""" 8 8 9 import re 9 10 import base64 11 import uuid 10 12 11 13 bitFields = {} … … 34 36 # ADTS: 2.2.10 35 37 bitFields["systemflags"] = { 36 'FLAG_ATTR_NOT_REPLICATED': 31, 'FLAG_CR_NTDS_NC': 31, 37 'FLAG_ATTR_REQ_PARTIAL_SET_MEMBER': 30, 'FLAG_CR_NTDS_DOMAIN': 30, 38 'FLAG_ATTR_IS_CONSTRUCTED': 29, 'FLAG_CR_NTDS_NOT_GC_REPLICATED': 29, 39 'FLAG_ATTR_IS_OPERATIONAL': 28, 40 'FLAG_SCHEMA_BASE_OBJECT': 27, 41 'FLAG_ATTR_IS_RDN': 26, 42 'FLAG_DISALLOW_MOVE_ON_DELETE': 6, 43 'FLAG_DOMAIN_DISALLOW_MOVE': 5, 44 'FLAG_DOMAIN_DISALLOW_RENAME': 4, 45 'FLAG_CONFIG_ALLOW_LIMITED_MOVE': 3, 46 'FLAG_CONFIG_ALLOW_MOVE': 2, 47 'FLAG_CONFIG_ALLOW_RENAME': 1, 48 'FLAG_DISALLOW_DELETE': 0 38 'FLAG_ATTR_NOT_REPLICATED': 31, 'FLAG_CR_NTDS_NC': 31, # NR 39 'FLAG_ATTR_REQ_PARTIAL_SET_MEMBER': 30, 'FLAG_CR_NTDS_DOMAIN': 30, # PS 40 'FLAG_ATTR_IS_CONSTRUCTED': 29, 'FLAG_CR_NTDS_NOT_GC_REPLICATED': 29, # CS 41 'FLAG_ATTR_IS_OPERATIONAL': 28, # OP 42 'FLAG_SCHEMA_BASE_OBJECT': 27, # BS 43 'FLAG_ATTR_IS_RDN': 26, # RD 44 'FLAG_DISALLOW_MOVE_ON_DELETE': 6, # DE 45 'FLAG_DOMAIN_DISALLOW_MOVE': 5, # DM 46 'FLAG_DOMAIN_DISALLOW_RENAME': 4, # DR 47 'FLAG_CONFIG_ALLOW_LIMITED_MOVE': 3, # AL 48 'FLAG_CONFIG_ALLOW_MOVE': 2, # AM 49 'FLAG_CONFIG_ALLOW_RENAME': 1, # AR 50 'FLAG_DISALLOW_DELETE': 0 # DD 49 51 } 50 52 … … 228 230 entry.insert(1, ["objectClass", ["top", objectClass]]) 229 231 entry.insert(2, ["cn", cn]) 232 entry.insert(2, ["objectGUID", str(uuid.uuid4())]) 233 entry.insert(2, ["adminDescription", cn]) 234 entry.insert(2, ["adminDisplayName", cn]) 230 235 231 236 for l in entry: … … 273 278 274 279 print read_ms_schema(attr_file, classes_file) 275 276 -
vendor/current/source4/scripting/python/samba/ndr.py
r414 r740 1 #!/usr/bin/python2 1 # -*- coding: utf-8 -*- 3 2 4 3 # Unix SMB/CIFS implementation. 5 4 # Copyright © Jelmer Vernooij <jelmer@samba.org> 2008 6 # 5 # 7 6 # This program is free software; you can redistribute it and/or modify 8 7 # it under the terms of the GNU General Public License as published by 9 8 # the Free Software Foundation; either version 3 of the License, or 10 9 # (at your option) any later version. 11 # 10 # 12 11 # This program is distributed in the hope that it will be useful, 13 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 14 # GNU General Public License for more details. 16 # 15 # 17 16 # You should have received a copy of the GNU General Public License 18 17 # along with this program. If not, see <http://www.gnu.org/licenses/>. 19 18 # 20 19 20 21 """Network Data Representation (NDR) marshalling and unmarshalling.""" 22 23 21 24 def ndr_pack(object): 22 return object.__ndr_pack__() 25 """Pack a NDR object. 26 27 :param object: Object to pack 28 :return: String object with marshalled object. 29 """ 30 ndr_pack = getattr(object, "__ndr_pack__", None) 31 if ndr_pack is None: 32 raise TypeError("%r is not a NDR object" % object) 33 return ndr_pack() 23 34 24 35 25 36 def ndr_unpack(cls, data): 37 """NDR unpack an object. 38 39 :param cls: Class of the object to unpack 40 :param data: Buffer to unpack 41 :return: Unpacked object 42 """ 26 43 object = cls() 27 44 object.__ndr_unpack__(data) 28 45 return object 46 47 48 def ndr_print(object): 49 return object.__ndr_print__() -
vendor/current/source4/scripting/python/samba/samba3.py
r414 r740 1 #!/usr/bin/python2 3 1 # Unix SMB/CIFS implementation. 4 2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 5 # 3 # 6 4 # This program is free software; you can redistribute it and/or modify 7 5 # it under the terms of the GNU General Public License as published by 8 6 # the Free Software Foundation; either version 3 of the License, or 9 7 # (at your option) any later version. 10 # 8 # 11 9 # This program is distributed in the hope that it will be useful, 12 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 12 # GNU General Public License for more details. 15 # 13 # 16 14 # You should have received a copy of the GNU General Public License 17 15 # along with this program. If not, see <http://www.gnu.org/licenses/>. … … 68 66 class Registry(TdbDatabase): 69 67 """Simple read-only support for reading the Samba3 registry. 70 68 71 69 :note: This object uses the same syntax for registry key paths as 72 70 Samba 3. This particular format uses forward slashes for key path … … 684 682 for i, l in enumerate(open(filename, 'r').xreadlines()): 685 683 l = l.strip() 686 if not l :684 if not l or l[0] == '#' or l[0] == ';': 687 685 continue 688 686 if l[0] == "[" and l[-1] == "]": … … 770 768 def get_policy_db(self): 771 769 return PolicyDatabase(self.libdir_path("account_policy.tdb")) 772 770 773 771 def get_registry(self): 774 772 return Registry(self.libdir_path("registry.tdb")) -
vendor/current/source4/scripting/python/samba/samdb.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. 4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-20 084 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010 5 5 # Copyright (C) Matthias Dieter Wallnoefer 2009 6 6 # 7 7 # Based on the original in EJS: 8 8 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005 9 # 9 # 10 10 # This program is free software; you can redistribute it and/or modify 11 11 # it under the terms of the GNU General Public License as published by 12 12 # the Free Software Foundation; either version 3 of the License, or 13 13 # (at your option) any later version. 14 # 14 # 15 15 # This program is distributed in the hope that it will be useful, 16 16 # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 18 # GNU General Public License for more details. 19 # 19 # 20 20 # You should have received a copy of the GNU General Public License 21 21 # along with this program. If not, see <http://www.gnu.org/licenses/>. … … 25 25 26 26 import samba 27 import glue28 27 import ldb 29 from samba.idmap import IDmapDB30 import pwd31 28 import time 32 29 import base64 30 from samba import dsdb 31 from samba.ndr import ndr_unpack, ndr_pack 32 from samba.dcerpc import drsblobs, misc 33 33 34 34 __docformat__ = "restructuredText" 35 35 36 36 37 class SamDB(samba.Ldb): 37 38 """The SAM database.""" 38 39 40 hash_oid_name = {} 41 39 42 def __init__(self, url=None, lp=None, modules_dir=None, session_info=None, 40 credentials=None, flags=0, options=None): 41 """Opens the SAM Database 42 For parameter meanings see the super class (samba.Ldb) 43 """ 44 43 credentials=None, flags=0, options=None, global_schema=True, 44 auto_connect=True, am_rodc=None): 45 45 self.lp = lp 46 if url is None: 47 url = lp.get("sam database") 46 if not auto_connect: 47 url = None 48 elif url is None and lp is not None: 49 url = lp.get("sam database") 48 50 49 51 super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir, 50 session_info=session_info, credentials=credentials, flags=flags, 52 session_info=session_info, credentials=credentials, flags=flags, 53 options=options) 54 55 if global_schema: 56 dsdb._dsdb_set_global_schema(self) 57 58 if am_rodc is not None: 59 dsdb._dsdb_set_am_rodc(self, am_rodc) 60 61 def connect(self, url=None, flags=0, options=None): 62 if self.lp is not None: 63 url = self.lp.private_path(url) 64 65 super(SamDB, self).connect(url=url, flags=flags, 51 66 options=options) 52 67 53 glue.dsdb_set_global_schema(self) 54 55 def connect(self, url=None, flags=0, options=None): 56 super(SamDB, self).connect(url=self.lp.private_path(url), flags=flags, 57 options=options) 68 def am_rodc(self): 69 return dsdb._am_rodc(self) 58 70 59 71 def domain_dn(self): 60 # find the DNs for the domain 61 res = self.search(base="", 62 scope=ldb.SCOPE_BASE, 63 expression="(defaultNamingContext=*)", 64 attrs=["defaultNamingContext"]) 65 assert(len(res) == 1 and res[0]["defaultNamingContext"] is not None) 66 return res[0]["defaultNamingContext"][0] 67 68 def enable_account(self, filter): 72 return str(self.get_default_basedn()) 73 74 def enable_account(self, search_filter): 69 75 """Enables an account 70 71 :param filter: LDAP filter to find the user (eg samccountname=name) 76 77 :param search_filter: LDAP filter to find the user (eg 78 samccountname=name) 72 79 """ 73 80 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, 74 expression= filter, attrs=["userAccountControl"])81 expression=search_filter, attrs=["userAccountControl"]) 75 82 assert(len(res) == 1) 76 83 user_dn = res[0].dn 77 84 78 85 userAccountControl = int(res[0]["userAccountControl"][0]) 79 if (userAccountControl & 0x2): 80 userAccountControl = userAccountControl & ~0x2 # remove disabled bit 81 if (userAccountControl & 0x20): 82 userAccountControl = userAccountControl & ~0x20 # remove 'no password required' bit 86 if userAccountControl & 0x2: 87 # remove disabled bit 88 userAccountControl = userAccountControl & ~0x2 89 if userAccountControl & 0x20: 90 # remove 'no password required' bit 91 userAccountControl = userAccountControl & ~0x20 83 92 84 93 mod = """ … … 89 98 """ % (user_dn, userAccountControl) 90 99 self.modify_ldif(mod) 91 92 def force_password_change_at_next_login(self, filter):100 101 def force_password_change_at_next_login(self, search_filter): 93 102 """Forces a password change at next login 94 95 :param filter: LDAP filter to find the user (eg samccountname=name) 103 104 :param search_filter: LDAP filter to find the user (eg 105 samccountname=name) 96 106 """ 97 107 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, 98 expression= filter, attrs=[])108 expression=search_filter, attrs=[]) 99 109 assert(len(res) == 1) 100 110 user_dn = res[0].dn … … 108 118 self.modify_ldif(mod) 109 119 110 def newuser(self, username, unixname, password, force_password_change_at_next_login_req=False): 111 """Adds a new user 112 113 Note: This call adds also the ID mapping for winbind; therefore it works 114 *only* on SAMBA 4. 115 120 def newgroup(self, groupname, groupou=None, grouptype=None, 121 description=None, mailaddress=None, notes=None, sd=None): 122 """Adds a new group with additional parameters 123 124 :param groupname: Name of the new group 125 :param grouptype: Type of the new group 126 :param description: Description of the new group 127 :param mailaddress: Email address of the new group 128 :param notes: Notes of the new group 129 :param sd: security descriptor of the object 130 """ 131 132 group_dn = "CN=%s,%s,%s" % (groupname, (groupou or "CN=Users"), self.domain_dn()) 133 134 # The new user record. Note the reliance on the SAMLDB module which 135 # fills in the default informations 136 ldbmessage = {"dn": group_dn, 137 "sAMAccountName": groupname, 138 "objectClass": "group"} 139 140 if grouptype is not None: 141 ldbmessage["groupType"] = "%d" % grouptype 142 143 if description is not None: 144 ldbmessage["description"] = description 145 146 if mailaddress is not None: 147 ldbmessage["mail"] = mailaddress 148 149 if notes is not None: 150 ldbmessage["info"] = notes 151 152 if sd is not None: 153 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd) 154 155 self.add(ldbmessage) 156 157 def deletegroup(self, groupname): 158 """Deletes a group 159 160 :param groupname: Name of the target group 161 """ 162 163 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn()) 164 self.transaction_start() 165 try: 166 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, 167 expression=groupfilter, attrs=[]) 168 if len(targetgroup) == 0: 169 raise Exception('Unable to find group "%s"' % groupname) 170 assert(len(targetgroup) == 1) 171 self.delete(targetgroup[0].dn) 172 except Exception: 173 self.transaction_cancel() 174 raise 175 else: 176 self.transaction_commit() 177 178 def add_remove_group_members(self, groupname, listofmembers, 179 add_members_operation=True): 180 """Adds or removes group members 181 182 :param groupname: Name of the target group 183 :param listofmembers: Comma-separated list of group members 184 :param add_members_operation: Defines if its an add or remove 185 operation 186 """ 187 188 groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn()) 189 groupmembers = listofmembers.split(',') 190 191 self.transaction_start() 192 try: 193 targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, 194 expression=groupfilter, attrs=['member']) 195 if len(targetgroup) == 0: 196 raise Exception('Unable to find group "%s"' % groupname) 197 assert(len(targetgroup) == 1) 198 199 modified = False 200 201 addtargettogroup = """ 202 dn: %s 203 changetype: modify 204 """ % (str(targetgroup[0].dn)) 205 206 for member in groupmembers: 207 targetmember = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, 208 expression="(|(sAMAccountName=%s)(CN=%s))" % (member, member), attrs=[]) 209 210 if len(targetmember) != 1: 211 continue 212 213 if add_members_operation is True and (targetgroup[0].get('member') is None or str(targetmember[0].dn) not in targetgroup[0]['member']): 214 modified = True 215 addtargettogroup += """add: member 216 member: %s 217 """ % (str(targetmember[0].dn)) 218 219 elif add_members_operation is False and (targetgroup[0].get('member') is not None and str(targetmember[0].dn) in targetgroup[0]['member']): 220 modified = True 221 addtargettogroup += """delete: member 222 member: %s 223 """ % (str(targetmember[0].dn)) 224 225 if modified is True: 226 self.modify_ldif(addtargettogroup) 227 228 except Exception: 229 self.transaction_cancel() 230 raise 231 else: 232 self.transaction_commit() 233 234 def newuser(self, username, password, 235 force_password_change_at_next_login_req=False, 236 useusernameascn=False, userou=None, surname=None, givenname=None, 237 initials=None, profilepath=None, scriptpath=None, homedrive=None, 238 homedirectory=None, jobtitle=None, department=None, company=None, 239 description=None, mailaddress=None, internetaddress=None, 240 telephonenumber=None, physicaldeliveryoffice=None, sd=None, 241 setpassword=True): 242 """Adds a new user with additional parameters 243 116 244 :param username: Name of the new user 117 :param unixname: Name of the unix user to map to118 245 :param password: Password for the new user 119 246 :param force_password_change_at_next_login_req: Force password change 120 """ 247 :param useusernameascn: Use username as cn rather that firstname + 248 initials + lastname 249 :param userou: Object container (without domainDN postfix) for new user 250 :param surname: Surname of the new user 251 :param givenname: First name of the new user 252 :param initials: Initials of the new user 253 :param profilepath: Profile path of the new user 254 :param scriptpath: Logon script path of the new user 255 :param homedrive: Home drive of the new user 256 :param homedirectory: Home directory of the new user 257 :param jobtitle: Job title of the new user 258 :param department: Department of the new user 259 :param company: Company of the new user 260 :param description: of the new user 261 :param mailaddress: Email address of the new user 262 :param internetaddress: Home page of the new user 263 :param telephonenumber: Phone number of the new user 264 :param physicaldeliveryoffice: Office location of the new user 265 :param sd: security descriptor of the object 266 :param setpassword: optionally disable password reset 267 """ 268 269 displayname = "" 270 if givenname is not None: 271 displayname += givenname 272 273 if initials is not None: 274 displayname += ' %s.' % initials 275 276 if surname is not None: 277 displayname += ' %s' % surname 278 279 cn = username 280 if useusernameascn is None and displayname is not "": 281 cn = displayname 282 283 user_dn = "CN=%s,%s,%s" % (cn, (userou or "CN=Users"), self.domain_dn()) 284 285 dnsdomain = ldb.Dn(self, self.domain_dn()).canonical_str().replace("/", "") 286 user_principal_name = "%s@%s" % (username, dnsdomain) 287 # The new user record. Note the reliance on the SAMLDB module which 288 # fills in the default informations 289 ldbmessage = {"dn": user_dn, 290 "sAMAccountName": username, 291 "userPrincipalName": user_principal_name, 292 "objectClass": "user"} 293 294 if surname is not None: 295 ldbmessage["sn"] = surname 296 297 if givenname is not None: 298 ldbmessage["givenName"] = givenname 299 300 if displayname is not "": 301 ldbmessage["displayName"] = displayname 302 ldbmessage["name"] = displayname 303 304 if initials is not None: 305 ldbmessage["initials"] = '%s.' % initials 306 307 if profilepath is not None: 308 ldbmessage["profilePath"] = profilepath 309 310 if scriptpath is not None: 311 ldbmessage["scriptPath"] = scriptpath 312 313 if homedrive is not None: 314 ldbmessage["homeDrive"] = homedrive 315 316 if homedirectory is not None: 317 ldbmessage["homeDirectory"] = homedirectory 318 319 if jobtitle is not None: 320 ldbmessage["title"] = jobtitle 321 322 if department is not None: 323 ldbmessage["department"] = department 324 325 if company is not None: 326 ldbmessage["company"] = company 327 328 if description is not None: 329 ldbmessage["description"] = description 330 331 if mailaddress is not None: 332 ldbmessage["mail"] = mailaddress 333 334 if internetaddress is not None: 335 ldbmessage["wWWHomePage"] = internetaddress 336 337 if telephonenumber is not None: 338 ldbmessage["telephoneNumber"] = telephonenumber 339 340 if physicaldeliveryoffice is not None: 341 ldbmessage["physicalDeliveryOfficeName"] = physicaldeliveryoffice 342 343 if sd is not None: 344 ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd) 345 121 346 self.transaction_start() 122 347 try: 123 user_dn = "CN=%s,CN=Users,%s" % (username, self.domain_dn()) 124 125 # The new user record. Note the reliance on the SAMLDB module which 126 # fills in the default informations 127 self.add({"dn": user_dn, 128 "sAMAccountName": username, 129 "objectClass": "user"}) 348 self.add(ldbmessage) 130 349 131 350 # Sets the password for it 132 self.setpassword("(dn=" + user_dn + ")", password, 133 force_password_change_at_next_login_req) 134 135 # Gets the user SID (for the account mapping setup) 136 res = self.search(user_dn, scope=ldb.SCOPE_BASE, 137 expression="objectclass=*", 138 attrs=["objectSid"]) 139 assert len(res) == 1 140 user_sid = self.schema_format_value("objectSid", res[0]["objectSid"][0]) 141 142 try: 143 idmap = IDmapDB(lp=self.lp) 144 145 user = pwd.getpwnam(unixname) 146 147 # setup ID mapping for this UID 148 idmap.setup_name_mapping(user_sid, idmap.TYPE_UID, user[2]) 149 150 except KeyError: 151 pass 152 except: 351 if setpassword: 352 self.setpassword("(samAccountName=%s)" % username, password, 353 force_password_change_at_next_login_req) 354 except Exception: 153 355 self.transaction_cancel() 154 356 raise 155 self.transaction_commit() 156 157 def setpassword(self, filter, password, force_password_change_at_next_login_req=False): 357 else: 358 self.transaction_commit() 359 360 def setpassword(self, search_filter, password, 361 force_change_at_next_login=False, username=None): 158 362 """Sets the password for a user 159 160 Note: This call uses the "userPassword" attribute to set the password. 161 This works correctly on SAMBA 4 and on Windows DCs with 162 "2003 Native" or higer domain function level. 163 164 :param filter: LDAP filter to find the user (eg samccountname=name) 363 364 :param search_filter: LDAP filter to find the user (eg 365 samccountname=name) 165 366 :param password: Password for the user 166 :param force_ password_change_at_next_login_req: Force password change367 :param force_change_at_next_login: Force password change 167 368 """ 168 369 self.transaction_start() 169 370 try: 170 371 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, 171 expression=filter, attrs=[]) 172 assert(len(res) == 1) 372 expression=search_filter, attrs=[]) 373 if len(res) == 0: 374 raise Exception('Unable to find user "%s"' % (username or search_filter)) 375 if len(res) > 1: 376 raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter)) 173 377 user_dn = res[0].dn 174 175 378 setpw = """ 176 379 dn: %s 177 380 changetype: modify 178 replace: u serPassword179 u serPassword:: %s180 """ % (user_dn, base64.b64encode( password))381 replace: unicodePwd 382 unicodePwd:: %s 383 """ % (user_dn, base64.b64encode(("\"" + password + "\"").encode('utf-16-le'))) 181 384 182 385 self.modify_ldif(setpw) 183 386 184 if force_ password_change_at_next_login_req:387 if force_change_at_next_login: 185 388 self.force_password_change_at_next_login( 186 389 "(dn=" + str(user_dn) + ")") 187 390 188 391 # modify the userAccountControl to remove the disabled bit 189 self.enable_account( filter)190 except :392 self.enable_account(search_filter) 393 except Exception: 191 394 self.transaction_cancel() 192 395 raise 193 self.transaction_commit() 194 195 def setexpiry(self, filter, expiry_seconds, no_expiry_req=False): 396 else: 397 self.transaction_commit() 398 399 def setexpiry(self, search_filter, expiry_seconds, no_expiry_req=False): 196 400 """Sets the account expiry for a user 197 198 :param filter: LDAP filter to find the user (eg samccountname=name) 401 402 :param search_filter: LDAP filter to find the user (eg 403 samaccountname=name) 199 404 :param expiry_seconds: expiry time from now in seconds 200 405 :param no_expiry_req: if set, then don't expire password … … 203 408 try: 204 409 res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, 205 expression= filter,410 expression=search_filter, 206 411 attrs=["userAccountControl", "accountExpires"]) 207 412 assert(len(res) == 1) … … 215 420 else: 216 421 userAccountControl = userAccountControl & ~0x10000 217 accountExpires = glue.unix2nttime(expiry_seconds + int(time.time()))422 accountExpires = samba.unix2nttime(expiry_seconds + int(time.time())) 218 423 219 424 setexp = """ … … 227 432 228 433 self.modify_ldif(setexp) 229 except :434 except Exception: 230 435 self.transaction_cancel() 231 436 raise 232 self.transaction_commit(); 233 437 else: 438 self.transaction_commit() 439 440 def set_domain_sid(self, sid): 441 """Change the domain SID used by this LDB. 442 443 :param sid: The new domain sid to use. 444 """ 445 dsdb._samdb_set_domain_sid(self, sid) 446 447 def get_domain_sid(self): 448 """Read the domain SID used by this LDB. """ 449 return dsdb._samdb_get_domain_sid(self) 450 451 domain_sid = property(get_domain_sid, set_domain_sid, 452 "SID for the domain") 453 454 def set_invocation_id(self, invocation_id): 455 """Set the invocation id for this SamDB handle. 456 457 :param invocation_id: GUID of the invocation id. 458 """ 459 dsdb._dsdb_set_ntds_invocation_id(self, invocation_id) 460 461 def get_invocation_id(self): 462 """Get the invocation_id id""" 463 return dsdb._samdb_ntds_invocation_id(self) 464 465 invocation_id = property(get_invocation_id, set_invocation_id, 466 "Invocation ID GUID") 467 468 def get_oid_from_attid(self, attid): 469 return dsdb._dsdb_get_oid_from_attid(self, attid) 470 471 def get_attid_from_lDAPDisplayName(self, ldap_display_name, 472 is_schema_nc=False): 473 return dsdb._dsdb_get_attid_from_lDAPDisplayName(self, 474 ldap_display_name, is_schema_nc) 475 476 def set_ntds_settings_dn(self, ntds_settings_dn): 477 """Set the NTDS Settings DN, as would be returned on the dsServiceName 478 rootDSE attribute. 479 480 This allows the DN to be set before the database fully exists 481 482 :param ntds_settings_dn: The new DN to use 483 """ 484 dsdb._samdb_set_ntds_settings_dn(self, ntds_settings_dn) 485 486 def get_ntds_GUID(self): 487 """Get the NTDS objectGUID""" 488 return dsdb._samdb_ntds_objectGUID(self) 489 490 def server_site_name(self): 491 """Get the server site name""" 492 return dsdb._samdb_server_site_name(self) 493 494 def load_partition_usn(self, base_dn): 495 return dsdb._dsdb_load_partition_usn(self, base_dn) 496 497 def set_schema(self, schema): 498 self.set_schema_from_ldb(schema.ldb) 499 500 def set_schema_from_ldb(self, ldb_conn): 501 dsdb._dsdb_set_schema_from_ldb(self, ldb_conn) 502 503 def dsdb_DsReplicaAttribute(self, ldb, ldap_display_name, ldif_elements): 504 return dsdb._dsdb_DsReplicaAttribute(ldb, ldap_display_name, ldif_elements) 505 506 def get_attribute_from_attid(self, attid): 507 """ Get from an attid the associated attribute 508 509 :param attid: The attribute id for searched attribute 510 :return: The name of the attribute associated with this id 511 """ 512 if len(self.hash_oid_name.keys()) == 0: 513 self._populate_oid_attid() 514 if self.hash_oid_name.has_key(self.get_oid_from_attid(attid)): 515 return self.hash_oid_name[self.get_oid_from_attid(attid)] 516 else: 517 return None 518 519 def _populate_oid_attid(self): 520 """Populate the hash hash_oid_name. 521 522 This hash contains the oid of the attribute as a key and 523 its display name as a value 524 """ 525 self.hash_oid_name = {} 526 res = self.search(expression="objectClass=attributeSchema", 527 controls=["search_options:1:2"], 528 attrs=["attributeID", 529 "lDAPDisplayName"]) 530 if len(res) > 0: 531 for e in res: 532 strDisplay = str(e.get("lDAPDisplayName")) 533 self.hash_oid_name[str(e.get("attributeID"))] = strDisplay 534 535 def get_attribute_replmetadata_version(self, dn, att): 536 """Get the version field trom the replPropertyMetaData for 537 the given field 538 539 :param dn: The on which we want to get the version 540 :param att: The name of the attribute 541 :return: The value of the version field in the replPropertyMetaData 542 for the given attribute. None if the attribute is not replicated 543 """ 544 545 res = self.search(expression="dn=%s" % dn, 546 scope=ldb.SCOPE_SUBTREE, 547 controls=["search_options:1:2"], 548 attrs=["replPropertyMetaData"]) 549 if len(res) == 0: 550 return None 551 552 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, 553 str(res[0]["replPropertyMetaData"])) 554 ctr = repl.ctr 555 if len(self.hash_oid_name.keys()) == 0: 556 self._populate_oid_attid() 557 for o in ctr.array: 558 # Search for Description 559 att_oid = self.get_oid_from_attid(o.attid) 560 if self.hash_oid_name.has_key(att_oid) and\ 561 att.lower() == self.hash_oid_name[att_oid].lower(): 562 return o.version 563 return None 564 565 def set_attribute_replmetadata_version(self, dn, att, value, 566 addifnotexist=False): 567 res = self.search(expression="dn=%s" % dn, 568 scope=ldb.SCOPE_SUBTREE, 569 controls=["search_options:1:2"], 570 attrs=["replPropertyMetaData"]) 571 if len(res) == 0: 572 return None 573 574 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, 575 str(res[0]["replPropertyMetaData"])) 576 ctr = repl.ctr 577 now = samba.unix2nttime(int(time.time())) 578 found = False 579 if len(self.hash_oid_name.keys()) == 0: 580 self._populate_oid_attid() 581 for o in ctr.array: 582 # Search for Description 583 att_oid = self.get_oid_from_attid(o.attid) 584 if self.hash_oid_name.has_key(att_oid) and\ 585 att.lower() == self.hash_oid_name[att_oid].lower(): 586 found = True 587 seq = self.sequence_number(ldb.SEQ_NEXT) 588 o.version = value 589 o.originating_change_time = now 590 o.originating_invocation_id = misc.GUID(self.get_invocation_id()) 591 o.originating_usn = seq 592 o.local_usn = seq 593 594 if not found and addifnotexist and len(ctr.array) >0: 595 o2 = drsblobs.replPropertyMetaData1() 596 o2.attid = 589914 597 att_oid = self.get_oid_from_attid(o2.attid) 598 seq = self.sequence_number(ldb.SEQ_NEXT) 599 o2.version = value 600 o2.originating_change_time = now 601 o2.originating_invocation_id = misc.GUID(self.get_invocation_id()) 602 o2.originating_usn = seq 603 o2.local_usn = seq 604 found = True 605 tab = ctr.array 606 tab.append(o2) 607 ctr.count = ctr.count + 1 608 ctr.array = tab 609 610 if found : 611 replBlob = ndr_pack(repl) 612 msg = ldb.Message() 613 msg.dn = res[0].dn 614 msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, 615 ldb.FLAG_MOD_REPLACE, 616 "replPropertyMetaData") 617 self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"]) 618 619 def write_prefixes_from_schema(self): 620 dsdb._dsdb_write_prefixes_from_schema_to_ldb(self) 621 622 def get_partitions_dn(self): 623 return dsdb._dsdb_get_partitions_dn(self) 624 625 def set_minPwdAge(self, value): 626 m = ldb.Message() 627 m.dn = ldb.Dn(self, self.domain_dn()) 628 m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge") 629 self.modify(m) 630 631 def get_minPwdAge(self): 632 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"]) 633 if len(res) == 0: 634 return None 635 elif not "minPwdAge" in res[0]: 636 return None 637 else: 638 return res[0]["minPwdAge"][0] 639 640 def set_minPwdLength(self, value): 641 m = ldb.Message() 642 m.dn = ldb.Dn(self, self.domain_dn()) 643 m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength") 644 self.modify(m) 645 646 def get_minPwdLength(self): 647 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"]) 648 if len(res) == 0: 649 return None 650 elif not "minPwdLength" in res[0]: 651 return None 652 else: 653 return res[0]["minPwdLength"][0] 654 655 def set_pwdProperties(self, value): 656 m = ldb.Message() 657 m.dn = ldb.Dn(self, self.domain_dn()) 658 m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties") 659 self.modify(m) 660 661 def get_pwdProperties(self): 662 res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"]) 663 if len(res) == 0: 664 return None 665 elif not "pwdProperties" in res[0]: 666 return None 667 else: 668 return res[0]["pwdProperties"][0] 669 670 def set_dsheuristics(self, dsheuristics): 671 m = ldb.Message() 672 m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s" 673 % self.get_config_basedn().get_linearized()) 674 if dsheuristics is not None: 675 m["dSHeuristics"] = ldb.MessageElement(dsheuristics, 676 ldb.FLAG_MOD_REPLACE, "dSHeuristics") 677 else: 678 m["dSHeuristics"] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, 679 "dSHeuristics") 680 self.modify(m) 681 682 def get_dsheuristics(self): 683 res = self.search("CN=Directory Service,CN=Windows NT,CN=Services,%s" 684 % self.get_config_basedn().get_linearized(), 685 scope=ldb.SCOPE_BASE, attrs=["dSHeuristics"]) 686 if len(res) == 0: 687 dsheuristics = None 688 elif "dSHeuristics" in res[0]: 689 dsheuristics = res[0]["dSHeuristics"][0] 690 else: 691 dsheuristics = None 692 693 return dsheuristics 694 695 def create_ou(self, ou_dn, description=None, name=None, sd=None): 696 """Creates an organizationalUnit object 697 :param ou_dn: dn of the new object 698 :param description: description attribute 699 :param name: name atttribute 700 :param sd: security descriptor of the object, can be 701 an SDDL string or security.descriptor type 702 """ 703 m = {"dn": ou_dn, 704 "objectClass": "organizationalUnit"} 705 706 if description: 707 m["description"] = description 708 if name: 709 m["name"] = name 710 711 if sd: 712 m["nTSecurityDescriptor"] = ndr_pack(sd) 713 self.add(m) -
vendor/current/source4/scripting/python/samba/tests/__init__.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. 4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-20 085 # 4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010 5 # 6 6 # This program is free software; you can redistribute it and/or modify 7 7 # it under the terms of the GNU General Public License as published by 8 8 # the Free Software Foundation; either version 3 of the License, or 9 9 # (at your option) any later version. 10 # 10 # 11 11 # This program is distributed in the hope that it will be useful, 12 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 14 # GNU General Public License for more details. 15 # 15 # 16 16 # You should have received a copy of the GNU General Public License 17 17 # along with this program. If not, see <http://www.gnu.org/licenses/>. … … 23 23 import ldb 24 24 import samba 25 import samba.auth 26 from samba import param 27 from samba.samdb import SamDB 28 import subprocess 25 29 import tempfile 26 import unittest 27 28 class LdbTestCase(unittest.TestCase): 29 30 31 # Other modules import these two classes from here, for convenience: 32 from testtools.testcase import ( 33 TestCase as TesttoolsTestCase, 34 TestSkipped, 35 ) 36 37 38 class TestCase(TesttoolsTestCase): 39 """A Samba test case.""" 40 41 def setUp(self): 42 super(TestCase, self).setUp() 43 test_debug_level = os.getenv("TEST_DEBUG_LEVEL") 44 if test_debug_level is not None: 45 test_debug_level = int(test_debug_level) 46 self._old_debug_level = samba.get_debug_level() 47 samba.set_debug_level(test_debug_level) 48 self.addCleanup(samba.set_debug_level, test_debug_level) 49 50 def get_loadparm(self): 51 return env_loadparm() 52 53 def get_credentials(self): 54 return cmdline_credentials 55 56 57 class LdbTestCase(TesttoolsTestCase): 30 58 """Trivial test case for running tests against a LDB.""" 59 31 60 def setUp(self): 61 super(LdbTestCase, self).setUp() 32 62 self.filename = os.tempnam() 33 63 self.ldb = samba.Ldb(self.filename) … … 42 72 43 73 44 class TestCaseInTempDir( unittest.TestCase):74 class TestCaseInTempDir(TestCase): 45 75 46 76 def setUp(self): … … 54 84 55 85 56 class SubstituteVarTestCase(unittest.TestCase): 57 58 def test_empty(self): 59 self.assertEquals("", samba.substitute_var("", {})) 60 61 def test_nothing(self): 62 self.assertEquals("foo bar", samba.substitute_var("foo bar", {"bar": "bla"})) 63 64 def test_replace(self): 65 self.assertEquals("foo bla", samba.substitute_var("foo ${bar}", {"bar": "bla"})) 66 67 def test_broken(self): 68 self.assertEquals("foo ${bdkjfhsdkfh sdkfh ", 69 samba.substitute_var("foo ${bdkjfhsdkfh sdkfh ", {"bar": "bla"})) 70 71 def test_unknown_var(self): 72 self.assertEquals("foo ${bla} gsff", 73 samba.substitute_var("foo ${bla} gsff", {"bar": "bla"})) 74 75 def test_check_all_substituted(self): 76 samba.check_all_substituted("nothing to see here") 77 self.assertRaises(Exception, samba.check_all_substituted, "Not subsituted: ${FOOBAR}") 78 79 80 class LdbExtensionTests(TestCaseInTempDir): 81 82 def test_searchone(self): 83 path = self.tempdir + "/searchone.ldb" 84 l = samba.Ldb(path) 85 try: 86 l.add({"dn": "foo=dc", "bar": "bla"}) 87 self.assertEquals("bla", l.searchone(basedn=ldb.Dn(l, "foo=dc"), attribute="bar")) 88 finally: 89 del l 90 os.unlink(path) 91 92 93 cmdline_loadparm = None 86 def env_loadparm(): 87 lp = param.LoadParm() 88 try: 89 lp.load(os.environ["SMB_CONF_PATH"]) 90 except KeyError: 91 raise Exception("SMB_CONF_PATH not set") 92 return lp 93 94 95 def env_get_var_value(var_name): 96 """Returns value for variable in os.environ 97 98 Function throws AssertionError if variable is defined. 99 Unit-test based python tests require certain input params 100 to be set in environment, otherwise they can't be run 101 """ 102 assert var_name in os.environ.keys(), "Please supply %s in environment" % var_name 103 return os.environ[var_name] 104 105 94 106 cmdline_credentials = None 95 107 96 class RpcInterfaceTestCase(unittest.TestCase): 97 98 def get_loadparm(self): 99 assert cmdline_loadparm is not None 100 return cmdline_loadparm 101 102 def get_credentials(self): 103 return cmdline_credentials 104 105 106 class ValidNetbiosNameTests(unittest.TestCase): 108 class RpcInterfaceTestCase(TestCase): 109 """DCE/RPC Test case.""" 110 111 112 class ValidNetbiosNameTests(TestCase): 107 113 108 114 def test_valid(self): … … 114 120 def test_invalid_characters(self): 115 121 self.assertFalse(samba.valid_netbios_name("*BLA")) 122 123 124 class BlackboxProcessError(subprocess.CalledProcessError): 125 """This exception is raised when a process run by check_output() returns 126 a non-zero exit status. Exception instance should contain 127 the exact exit code (S.returncode), command line (S.cmd), 128 process output (S.stdout) and process error stream (S.stderr)""" 129 def __init__(self, returncode, cmd, stdout, stderr): 130 super(BlackboxProcessError, self).__init__(returncode, cmd) 131 self.stdout = stdout 132 self.stderr = stderr 133 def __str__(self): 134 return "Command '%s'; exit status %d; stdout: '%s'; stderr: '%s'" % (self.cmd, self.returncode, 135 self.stdout, self.stderr) 136 137 class BlackboxTestCase(TestCase): 138 """Base test case for blackbox tests.""" 139 140 def _make_cmdline(self, line): 141 bindir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../bin")) 142 parts = line.split(" ") 143 if os.path.exists(os.path.join(bindir, parts[0])): 144 parts[0] = os.path.join(bindir, parts[0]) 145 line = " ".join(parts) 146 return line 147 148 def check_run(self, line): 149 line = self._make_cmdline(line) 150 subprocess.check_call(line, shell=True) 151 152 def check_output(self, line): 153 line = self._make_cmdline(line) 154 p = subprocess.Popen(line, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, close_fds=True) 155 retcode = p.wait() 156 if retcode: 157 raise BlackboxProcessError(retcode, line, p.stdout.read(), p.stderr.read()) 158 return p.stdout.read() 159 160 def connect_samdb(samdb_url, lp=None, session_info=None, credentials=None, 161 flags=0, ldb_options=None, ldap_only=False): 162 """Create SamDB instance and connects to samdb_url database. 163 164 :param samdb_url: Url for database to connect to. 165 :param lp: Optional loadparm object 166 :param session_info: Optional session information 167 :param credentials: Optional credentials, defaults to anonymous. 168 :param flags: Optional LDB flags 169 :param ldap_only: If set, only remote LDAP connection will be created. 170 171 Added value for tests is that we have a shorthand function 172 to make proper URL for ldb.connect() while using default 173 parameters for connection based on test environment 174 """ 175 samdb_url = samdb_url.lower() 176 if not "://" in samdb_url: 177 if not ldap_only and os.path.isfile(samdb_url): 178 samdb_url = "tdb://%s" % samdb_url 179 else: 180 samdb_url = "ldap://%s" % samdb_url 181 # use 'paged_search' module when connecting remotely 182 if samdb_url.startswith("ldap://"): 183 ldb_options = ["modules:paged_searches"] 184 elif ldap_only: 185 raise AssertionError("Trying to connect to %s while remote " 186 "connection is required" % samdb_url) 187 188 # set defaults for test environment 189 if lp is None: 190 lp = env_loadparm() 191 if session_info is None: 192 session_info = samba.auth.system_session(lp) 193 if credentials is None: 194 credentials = cmdline_credentials 195 196 return SamDB(url=samdb_url, 197 lp=lp, 198 session_info=session_info, 199 credentials=credentials, 200 flags=flags, 201 options=ldb_options) 202 203 204 def connect_samdb_ex(samdb_url, lp=None, session_info=None, credentials=None, 205 flags=0, ldb_options=None, ldap_only=False): 206 """Connects to samdb_url database 207 208 :param samdb_url: Url for database to connect to. 209 :param lp: Optional loadparm object 210 :param session_info: Optional session information 211 :param credentials: Optional credentials, defaults to anonymous. 212 :param flags: Optional LDB flags 213 :param ldap_only: If set, only remote LDAP connection will be created. 214 :return: (sam_db_connection, rootDse_record) tuple 215 """ 216 sam_db = connect_samdb(samdb_url, lp, session_info, credentials, 217 flags, ldb_options, ldap_only) 218 # fetch RootDse 219 res = sam_db.search(base="", expression="", scope=ldb.SCOPE_BASE, 220 attrs=["*"]) 221 return (sam_db, res[0]) 222 223 224 def delete_force(samdb, dn): 225 try: 226 samdb.delete(dn) 227 except ldb.LdbError, (num, _): 228 assert(num == ldb.ERR_NO_SUCH_OBJECT) -
vendor/current/source4/scripting/python/samba/tests/dcerpc/__init__.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 3 4 4 # Unix SMB/CIFS implementation. 5 5 # Copyright © Jelmer Vernooij <jelmer@samba.org> 2008 6 # 6 # 7 7 # This program is free software; you can redistribute it and/or modify 8 8 # it under the terms of the GNU General Public License as published by 9 9 # the Free Software Foundation; either version 3 of the License, or 10 10 # (at your option) any later version. 11 # 11 # 12 12 # This program is distributed in the hope that it will be useful, 13 13 # but WITHOUT ANY WARRANTY; without even the implied warranty of … … 17 17 # You should have received a copy of the GNU General Public License 18 18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 19 #20 19 20 """Tests for the DCE/RPC Python bindings.""" 21 -
vendor/current/source4/scripting/python/samba/tests/dcerpc/bare.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 3 … … 19 19 # 20 20 21 """Tests for samba.dcerpc.bare.""" 22 21 23 from samba.dcerpc import ClientConnection 22 from unittest import TestCase 23 from samba.tests import cmdline_loadparm 24 import samba.tests 24 25 25 26 class BareTestCase(TestCase): 26 class BareTestCase(samba.tests.TestCase): 27 27 28 28 def test_bare(self): 29 29 # Connect to the echo pipe 30 30 x = ClientConnection("ncalrpc:localhost[DEFAULT]", 31 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), lp_ctx=cmdline_loadparm) 31 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), 32 lp_ctx=samba.tests.env_loadparm()) 32 33 self.assertEquals("\x01\x00\x00\x00", x.request(0, chr(0) * 4)) 33 34 34 35 def test_alter_context(self): 35 36 x = ClientConnection("ncalrpc:localhost[DEFAULT]", 36 ("12345778-1234-abcd-ef00-0123456789ac", 1), lp_ctx=cmdline_loadparm) 37 ("12345778-1234-abcd-ef00-0123456789ac", 1), 38 lp_ctx=samba.tests.env_loadparm()) 37 39 y = ClientConnection("ncalrpc:localhost", 38 40 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), 39 basis_connection=x, lp_ctx= cmdline_loadparm)41 basis_connection=x, lp_ctx=samba.tests.env_loadparm()) 40 42 x.alter_context(("60a15ec5-4de8-11d7-a637-005056a20182", 1)) 41 43 # FIXME: self.assertEquals("\x01\x00\x00\x00", x.request(0, chr(0) * 4)) … … 43 45 def test_two_connections(self): 44 46 x = ClientConnection("ncalrpc:localhost[DEFAULT]", 45 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), lp_ctx=cmdline_loadparm) 47 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), 48 lp_ctx=samba.tests.env_loadparm()) 46 49 y = ClientConnection("ncalrpc:localhost", 47 50 ("60a15ec5-4de8-11d7-a637-005056a20182", 1), 48 basis_connection=x, lp_ctx= cmdline_loadparm)51 basis_connection=x, lp_ctx=samba.tests.env_loadparm()) 49 52 self.assertEquals("\x01\x00\x00\x00", y.request(0, chr(0) * 4)) -
vendor/current/source4/scripting/python/samba/tests/dcerpc/misc.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 18 18 # 19 19 20 import unittest 20 """Tests for samba.dcerpc.misc.""" 21 21 22 from samba.dcerpc import misc 23 import samba.tests 22 24 23 25 text1 = "76f53846-a7c2-476a-ae2c-20e2b80d7b34" 24 26 text2 = "344edffa-330a-4b39-b96e-2c34da52e8b1" 25 27 26 class GUIDTests( unittest.TestCase):28 class GUIDTests(samba.tests.TestCase): 27 29 28 30 def test_str(self): … … 44 46 self.assertEquals(0, cmp(guid1, guid2)) 45 47 self.assertEquals(guid1, guid2) 46 47 48 class PolicyHandleTests( unittest.TestCase):48 49 50 class PolicyHandleTests(samba.tests.TestCase): 49 51 50 52 def test_init(self): -
vendor/current/source4/scripting/python/samba/tests/dcerpc/registry.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 18 18 # 19 19 20 """Tests for samba.dcerpc.registry.""" 21 20 22 from samba.dcerpc import winreg 21 23 from samba.tests import RpcInterfaceTestCase … … 25 27 26 28 def setUp(self): 29 super(WinregTests, self).setUp() 27 30 self.conn = winreg.winreg("ncalrpc:", self.get_loadparm(), 28 31 self.get_credentials()) -
vendor/current/source4/scripting/python/samba/tests/dcerpc/rpcecho.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 18 18 # 19 19 20 """Tests for samba.dceprc.rpcecho.""" 21 20 22 from samba.dcerpc import echo 21 23 from samba.ndr import ndr_pack, ndr_unpack 22 import unittest 23 from samba.tests import RpcInterfaceTestCase 24 from samba.tests import RpcInterfaceTestCase, TestCase 24 25 25 26 … … 27 28 28 29 def setUp(self): 30 super(RpcEchoTests, self).setUp() 29 31 self.conn = echo.rpcecho("ncalrpc:", self.get_loadparm()) 30 32 … … 34 36 35 37 def test_abstract_syntax(self): 36 self.assertEquals(("60a15ec5-4de8-11d7-a637-005056a20182", 1), 38 self.assertEquals(("60a15ec5-4de8-11d7-a637-005056a20182", 1), 37 39 self.conn.abstract_syntax) 38 40 … … 60 62 61 63 62 class NdrEchoTests( unittest.TestCase):64 class NdrEchoTests(TestCase): 63 65 64 66 def test_info1_push(self): -
vendor/current/source4/scripting/python/samba/tests/dcerpc/sam.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # -*- coding: utf-8 -*- 3 3 … … 19 19 # 20 20 21 """Tests for samba.dcerpc.sam.""" 22 21 23 from samba.dcerpc import samr, security 22 24 from samba.tests import RpcInterfaceTestCase … … 33 35 34 36 def setUp(self): 37 super(SamrTests, self).setUp() 35 38 self.conn = samr.samr("ncalrpc:", self.get_loadparm()) 36 39 … … 40 43 def test_connect2(self): 41 44 handle = self.conn.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED) 45 self.assertTrue(handle is not None) 42 46 43 47 def test_EnumDomains(self): -
vendor/current/source4/scripting/python/samba/tests/dcerpc/unix.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 18 18 # 19 19 20 """Tests for samba.dcerpc.unixinfo.""" 21 22 20 23 from samba.dcerpc import unixinfo 21 24 from samba.tests import RpcInterfaceTestCase … … 24 27 25 28 def setUp(self): 29 super(UnixinfoTests, self).setUp() 26 30 self.conn = unixinfo.unixinfo("ncalrpc:", self.get_loadparm()) 27 31 28 def test_getpwuid (self):32 def test_getpwuid_int(self): 29 33 infos = self.conn.GetPWUid(range(512)) 30 34 self.assertEquals(512, len(infos)) … … 32 36 self.assertTrue(isinstance(infos[0].homedir, unicode)) 33 37 38 def test_getpwuid(self): 39 infos = self.conn.GetPWUid(map(long, range(512))) 40 self.assertEquals(512, len(infos)) 41 self.assertEquals("/bin/false", infos[0].shell) 42 self.assertTrue(isinstance(infos[0].homedir, unicode)) 43 34 44 def test_gidtosid(self): 35 self.conn.GidToSid(1000 )45 self.conn.GidToSid(1000L) 36 46 37 47 def test_uidtosid(self): 38 48 self.conn.UidToSid(1000) 49 50 def test_uidtosid_fail(self): 51 self.assertRaises(TypeError, self.conn.UidToSid, "100") -
vendor/current/source4/scripting/python/samba/tests/provision.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 18 18 # 19 19 20 """Tests for samba.provision.""" 21 20 22 import os 21 from samba.provision import setup_secretsdb, findnss 23 from samba.provision import setup_secretsdb, findnss, ProvisionPaths 22 24 import samba.tests 23 from ldb import Dn 24 from samba import param 25 import unittest 25 from samba.tests import env_loadparm, TestCase 26 26 27 lp = samba.tests.cmdline_loadparm 27 def create_dummy_secretsdb(path, lp=None): 28 """Create a dummy secrets database for use in tests. 28 29 29 setup_dir = "setup" 30 def setup_path(file): 31 return os.path.join(setup_dir, file) 30 :param path: Path to store the secrets db 31 :param lp: Optional loadparm context. A simple one will 32 be generated if not specified. 33 """ 34 if lp is None: 35 lp = env_loadparm() 36 paths = ProvisionPaths() 37 paths.secrets = path 38 paths.private_dir = os.path.dirname(path) 39 paths.keytab = "no.keytab" 40 paths.dns_keytab = "no.dns.keytab" 41 secrets_ldb = setup_secretsdb(paths, None, None, lp=lp) 42 secrets_ldb.transaction_commit() 43 return secrets_ldb 32 44 33 45 … … 35 47 """Some simple tests for individual functions in the provisioning code. 36 48 """ 49 37 50 def test_setup_secretsdb(self): 38 51 path = os.path.join(self.tempdir, "secrets.ldb") 39 ldb = setup_secretsdb(path, setup_path, None, None, lp=lp) 52 paths = ProvisionPaths() 53 paths.secrets = path 54 paths.private_dir = os.path.dirname(path) 55 paths.keytab = "no.keytab" 56 paths.dns_keytab = "no.dns.keytab" 57 ldb = setup_secretsdb(paths, None, None, lp=env_loadparm()) 40 58 try: 41 59 self.assertEquals("LSA Secrets", … … 46 64 47 65 48 class FindNssTests( unittest.TestCase):66 class FindNssTests(TestCase): 49 67 """Test findnss() function.""" 68 50 69 def test_nothing(self): 51 70 def x(y): … … 65 84 66 85 class Disabled(object): 86 67 87 def test_setup_templatesdb(self): 68 88 raise NotImplementedError(self.test_setup_templatesdb) … … 95 115 raise NotImplementedError(self.test_vampire) 96 116 97 def test_erase_partitions(self):98 raise NotImplementedError(self.test_erase_partitions)99 117 100 -
vendor/current/source4/scripting/python/samba/tests/samba3.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 18 18 # 19 19 20 import unittest 21 from samba.samba3 import GroupMappingDatabase, Registry, PolicyDatabase, SecretsDatabase, TdbSam 22 from samba.samba3 import WinsDatabase, SmbpasswdFile, ACB_NORMAL, IdmapDatabase, SAMUser, ParamFile 20 """Tests for samba.samba3.""" 21 22 from samba.samba3 import (GroupMappingDatabase, Registry, PolicyDatabase, 23 SecretsDatabase, TdbSam) 24 from samba.samba3 import (WinsDatabase, SmbpasswdFile, ACB_NORMAL, 25 IdmapDatabase, SAMUser, ParamFile) 26 from samba.tests import TestCase 23 27 import os 24 28 25 DATADIR=os.path.join(os.path.dirname(__file__), "../../../../../testdata/samba3") 26 print "Samba 3 data dir: %s" % DATADIR 27 28 class RegistryTestCase(unittest.TestCase): 29 def setUp(self): 29 for p in [ "../../../../../testdata/samba3", "../../../../testdata/samba3" ]: 30 DATADIR = os.path.join(os.path.dirname(__file__), p) 31 if os.path.exists(DATADIR): 32 break 33 34 35 class RegistryTestCase(TestCase): 36 37 def setUp(self): 38 super(RegistryTestCase, self).setUp() 30 39 self.registry = Registry(os.path.join(DATADIR, "registry.tdb")) 31 40 32 41 def tearDown(self): 33 42 self.registry.close() 43 super(RegistryTestCase, self).tearDown() 34 44 35 45 def test_length(self): … … 48 58 49 59 50 class PolicyTestCase(unittest.TestCase): 51 def setUp(self): 60 class PolicyTestCase(TestCase): 61 62 def setUp(self): 63 super(PolicyTestCase, self).setUp() 52 64 self.policy = PolicyDatabase(os.path.join(DATADIR, "account_policy.tdb")) 53 65 … … 65 77 66 78 67 class GroupsTestCase(unittest.TestCase): 68 def setUp(self): 79 class GroupsTestCase(TestCase): 80 81 def setUp(self): 82 super(GroupsTestCase, self).setUp() 69 83 self.groupdb = GroupMappingDatabase(os.path.join(DATADIR, "group_mapping.tdb")) 70 84 71 85 def tearDown(self): 72 86 self.groupdb.close() 87 super(GroupsTestCase, self).tearDown() 73 88 74 89 def test_group_length(self): … … 86 101 87 102 88 class SecretsDbTestCase(unittest.TestCase): 89 def setUp(self): 103 class SecretsDbTestCase(TestCase): 104 105 def setUp(self): 106 super(SecretsDbTestCase, self).setUp() 90 107 self.secretsdb = SecretsDatabase(os.path.join(DATADIR, "secrets.tdb")) 91 108 92 109 def tearDown(self): 93 110 self.secretsdb.close() 111 super(SecretsDbTestCase, self).tearDown() 94 112 95 113 def test_get_sid(self): … … 97 115 98 116 99 class TdbSamTestCase(unittest.TestCase): 100 def setUp(self): 117 class TdbSamTestCase(TestCase): 118 119 def setUp(self): 120 super(TdbSamTestCase, self).setUp() 101 121 self.samdb = TdbSam(os.path.join(DATADIR, "passdb.tdb")) 102 122 103 123 def tearDown(self): 104 124 self.samdb.close() 125 super(TdbSamTestCase, self).tearDown() 105 126 106 127 def test_usernames(self): … … 141 162 142 163 143 class WinsDatabaseTestCase(unittest.TestCase): 144 def setUp(self): 164 class WinsDatabaseTestCase(TestCase): 165 166 def setUp(self): 167 super(WinsDatabaseTestCase, self).setUp() 145 168 self.winsdb = WinsDatabase(os.path.join(DATADIR, "wins.dat")) 146 169 … … 153 176 def tearDown(self): 154 177 self.winsdb.close() 155 156 157 class SmbpasswdTestCase(unittest.TestCase): 158 def setUp(self): 178 super(WinsDatabaseTestCase, self).tearDown() 179 180 181 class SmbpasswdTestCase(TestCase): 182 183 def setUp(self): 184 super(SmbpasswdTestCase, self).setUp() 159 185 self.samdb = SmbpasswdFile(os.path.join(DATADIR, "smbpasswd")) 160 186 … … 173 199 def tearDown(self): 174 200 self.samdb.close() 175 176 177 class IdmapDbTestCase(unittest.TestCase): 178 def setUp(self): 179 self.idmapdb = IdmapDatabase(os.path.join(DATADIR, "winbindd_idmap.tdb")) 201 super(SmbpasswdTestCase, self).tearDown() 202 203 204 class IdmapDbTestCase(TestCase): 205 206 def setUp(self): 207 super(IdmapDbTestCase, self).setUp() 208 self.idmapdb = IdmapDatabase(os.path.join(DATADIR, 209 "winbindd_idmap.tdb")) 180 210 181 211 def test_user_hwm(self): … … 199 229 def tearDown(self): 200 230 self.idmapdb.close() 201 202 203 class ShareInfoTestCase(unittest.TestCase): 204 def setUp(self): 205 self.shareinfodb = ShareInfoDatabase(os.path.join(DATADIR, "share_info.tdb")) 206 207 # FIXME: needs proper data so it can be tested 208 209 def tearDown(self): 210 self.shareinfodb.close() 211 212 213 class ParamTestCase(unittest.TestCase): 231 super(IdmapDbTestCase, self).tearDown() 232 233 234 class ParamTestCase(TestCase): 235 214 236 def test_init(self): 215 237 file = ParamFile() -
vendor/current/source4/scripting/python/samba/tests/samdb.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. Tests for SamDB 4 4 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008 5 # 5 # 6 6 # This program is free software; you can redistribute it and/or modify 7 7 # it under the terms of the GNU General Public License as published by 8 8 # the Free Software Foundation; either version 3 of the License, or 9 9 # (at your option) any later version. 10 # 10 # 11 11 # This program is distributed in the hope that it will be useful, 12 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 14 # GNU General Public License for more details. 15 # 15 # 16 16 # You should have received a copy of the GNU General Public License 17 17 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 18 # 19 20 """Tests for samba.samdb.""" 21 22 import logging 23 import os 24 import uuid 25 19 26 from samba.auth import system_session 20 from samba. credentials import Credentials21 import os 22 from samba.provision import setup_samdb, guess_names, setup_templatesdb, make_smbconf, find_setup_dir23 from samba. samdb import SamDB27 from samba.provision import (setup_samdb, guess_names, make_smbconf, 28 provision_paths_from_lp) 29 from samba.provision import DEFAULT_POLICY_GUID, DEFAULT_DC_POLICY_GUID 30 from samba.provision.backend import ProvisionBackend 24 31 from samba.tests import TestCaseInTempDir 25 32 from samba.dcerpc import security 26 from unittest import TestCase 27 import uuid 33 from samba.schema import Schema 28 34 from samba import param 29 35 … … 31 37 class SamDBTestCase(TestCaseInTempDir): 32 38 """Base-class for tests with a Sam Database. 33 39 34 40 This is used by the Samba SamDB-tests, but e.g. also by the OpenChange 35 41 provisioning tests (which need a Sam). 36 42 """ 37 38 def setup_path(self, relpath):39 return os.path.join(find_setup_dir(), relpath)40 43 41 44 def setUp(self): … … 47 50 schemadn = "CN=Schema," + configdn 48 51 domainguid = str(uuid.uuid4()) 49 policyguid = str(uuid.uuid4()) 50 creds = Credentials() 51 creds.set_anonymous() 52 policyguid = DEFAULT_POLICY_GUID 52 53 domainsid = security.random_sid() 53 hostguid = str(uuid.uuid4())54 54 path = os.path.join(self.tempdir, "samdb.ldb") 55 55 session_info = system_session() … … 59 59 dnsdomain="example.com" 60 60 serverrole="domain controller" 61 policyguid_dc = DEFAULT_DC_POLICY_GUID 61 62 62 63 smbconf = os.path.join(self.tempdir, "smb.conf") 63 make_smbconf(smbconf, self.setup_path, hostname, domain, dnsdomain,64 make_smbconf(smbconf, hostname, domain, dnsdomain, 64 65 serverrole, self.tempdir) 65 66 … … 72 73 domaindn=self.domaindn, configdn=configdn, 73 74 schemadn=schemadn) 74 setup_templatesdb(os.path.join(self.tempdir, "templates.ldb"), 75 self.setup_path, session_info=session_info, lp=self.lp) 76 self.samdb = setup_samdb(path, self.setup_path, session_info, creds, 77 self.lp, names, 78 lambda x: None, domainsid, 79 domainguid, 80 policyguid, False, "secret", 81 "secret", "secret", invocationid, 82 "secret", "domain controller") 75 76 paths = provision_paths_from_lp(self.lp, names.dnsdomain) 77 78 logger = logging.getLogger("provision") 79 80 provision_backend = ProvisionBackend("ldb", paths=paths, 81 lp=self.lp, credentials=None, 82 names=names, logger=logger) 83 84 schema = Schema(domainsid, invocationid=invocationid, 85 schemadn=names.schemadn, serverdn=names.serverdn, 86 am_rodc=False) 87 88 self.samdb = setup_samdb(path, session_info, 89 provision_backend, self.lp, names, logger, 90 domainsid, domainguid, policyguid, policyguid_dc, False, 91 "secret", "secret", "secret", invocationid, "secret", 92 None, "domain controller", schema=schema) 83 93 84 94 def tearDown(self): 85 for f in [' templates.ldb', 'schema.ldb', 'configuration.ldb',95 for f in ['schema.ldb', 'configuration.ldb', 86 96 'users.ldb', 'samdb.ldb', 'smb.conf']: 87 97 os.remove(os.path.join(self.tempdir, f)) 88 98 super(SamDBTestCase, self).tearDown() 89 90 91 # disable this test till andrew works it out ...92 class SamDBTests(SamDBTestCase):93 """Tests for the SamDB implementation."""94 95 print "samdb add_foreign disabled for now"96 # def test_add_foreign(self): -
vendor/current/source4/scripting/python/samba/tests/upgrade.py
r414 r740 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 3 3 # Unix SMB/CIFS implementation. … … 18 18 # 19 19 20 from samba import Ldb 20 """Tests for samba.upgrade.""" 21 21 22 from samba.upgrade import import_wins 22 23 from samba.tests import LdbTestCase 23 24 24 25 class WinsUpgradeTests(LdbTestCase): 26 25 27 def test_upgrade(self): 26 28 winsdb = { -
vendor/current/source4/scripting/python/samba/upgrade.py
r414 r740 1 #!/usr/bin/python 1 # backend code for upgrading from Samba3 2 # Copyright Jelmer Vernooij 2005-2007 2 3 # 3 # backend code for upgrading from Samba3 4 # Copyright Jelmer Vernooij 2005-2007 5 # Released under the GNU GPL v3 or later 4 # This program is free software; you can redistribute it and/or modify 5 # it under the terms of the GNU General Public License as published by 6 # the Free Software Foundation; either version 3 of the License, or 7 # (at your option) any later version. 6 8 # 9 # This program is distributed in the hope that it will be useful, 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 # GNU General Public License for more details. 13 # 14 # You should have received a copy of the GNU General Public License 15 # along with this program. If not, see <http://www.gnu.org/licenses/>. 16 # 7 17 8 18 """Support code for upgrading from Samba 3 to Samba 4.""" … … 10 20 __docformat__ = "restructuredText" 11 21 12 from provision import provision, FILL_DRS13 22 import grp 14 23 import ldb 15 24 import time 16 25 import pwd 17 import registry 18 from samba import Ldb 26 27 from samba import Ldb, registry 19 28 from samba.param import LoadParm 29 from samba.provision import provision 20 30 21 31 def import_sam_policy(samldb, policy, dn): … … 35 45 samba3DisconnectTime: %d 36 46 37 """ % (dn, policy.min_password_length, 47 """ % (dn, policy.min_password_length, 38 48 policy.password_history, policy.minimum_password_age, 39 49 policy.maximum_password_age, policy.lockout_duration, … … 44 54 def import_sam_account(samldb,acc,domaindn,domainsid): 45 55 """Import a Samba 3 SAM account. 46 56 47 57 :param samldb: Samba 4 SAM Database handle 48 58 :param acc: Samba 3 account … … 60 70 if acc.fullname is None: 61 71 acc.fullname = acc.username 62 72 63 73 assert acc.fullname is not None 64 74 assert acc.nt_username is not None … … 79 89 "samba3DirDrive": acc.dir_drive, 80 90 "samba3MungedDial": acc.munged_dial, 81 "samba3Homedir": acc.homedir, 82 "samba3LogonScript": acc.logon_script, 91 "samba3Homedir": acc.homedir, 92 "samba3LogonScript": acc.logon_script, 83 93 "samba3ProfilePath": acc.profile_path, 84 94 "samba3Workstations": acc.workstations, … … 96 106 def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn): 97 107 """Upgrade a SAM group. 98 108 99 109 :param samldb: SAM database. 100 110 :param gid: Group GID … … 110 120 if nt_name in ("Domain Guests", "Domain Users", "Domain Admins"): 111 121 return None 112 122 113 123 if gid == -1: 114 124 gr = grp.getgrnam(nt_name) … … 122 132 123 133 assert unixname is not None 124 134 125 135 samldb.add({ 126 136 "dn": "cn=%s,%s" % (nt_name, domaindn), 127 137 "objectClass": ["top", "group"], 128 138 "description": comment, 129 "cn": nt_name, 139 "cn": nt_name, 130 140 "objectSid": sid, 131 141 "unixName": unixname, … … 161 171 def import_wins(samba4_winsdb, samba3_winsdb): 162 172 """Import settings from a Samba3 WINS database. 163 173 164 174 :param samba4_winsdb: WINS database to import to 165 175 :param samba3_winsdb: WINS database to import from … … 209 219 "maxVersion": str(version_id)}) 210 220 211 def upgrade_provision(samba3, setup_dir, message, credentials, session_info, smbconf, targetdir):212 oldconf = samba3.get_conf()213 214 if oldconf.get("domain logons") == "True":215 serverrole = "domain controller"216 else:217 if oldconf.get("security") == "user":218 serverrole = "standalone"219 else:220 serverrole = "member server"221 222 domainname = oldconf.get("workgroup")223 if domainname:224 domainname = str(domainname)225 realm = oldconf.get("realm")226 netbiosname = oldconf.get("netbios name")227 228 secrets_db = samba3.get_secrets_db()229 230 if domainname is None:231 domainname = secrets_db.domains()[0]232 message("No domain specified in smb.conf file, assuming '%s'" % domainname)233 234 if realm is None:235 realm = domainname.lower()236 message("No realm specified in smb.conf file, assuming '%s'\n" % realm)237 238 domainguid = secrets_db.get_domain_guid(domainname)239 domainsid = secrets_db.get_sid(domainname)240 if domainsid is None:241 message("Can't find domain secrets for '%s'; using random SID\n" % domainname)242 243 if netbiosname is not None:244 machinepass = secrets_db.get_machine_password(netbiosname)245 else:246 machinepass = None247 248 result = provision(setup_dir=setup_dir, message=message,249 samdb_fill=FILL_DRS, smbconf=smbconf, session_info=session_info,250 credentials=credentials, realm=realm,251 domain=domainname, domainsid=domainsid, domainguid=domainguid,252 machinepass=machinepass, serverrole=serverrole, targetdir=targetdir)253 254 import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db())255 256 # FIXME: import_registry(registry.Registry(), samba3.get_registry())257 258 # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn)259 260 groupdb = samba3.get_groupmapping_db()261 for sid in groupdb.groupsids():262 (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid)263 # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn)264 265 # FIXME: Aliases266 267 passdb = samba3.get_sam_db()268 for name in passdb:269 user = passdb[name]270 #FIXME: import_sam_account(result.samdb, user, domaindn, domainsid)271 272 if hasattr(passdb, 'ldap_url'):273 message("Enabling Samba3 LDAP mappings for SAM database")274 275 enable_samba3sam(result.samdb, passdb.ldap_url)276 277 278 221 def enable_samba3sam(samdb, ldapurl): 279 222 """Enable Samba 3 LDAP URL database. … … 293 236 294 237 smbconf_keep = [ 295 "dos charset", 238 "dos charset", 296 239 "unix charset", 297 240 "display charset", … … 390 333 391 334 :param oldconf: Old configuration structure 392 :param mark: Whether removed configuration variables should be 335 :param mark: Whether removed configuration variables should be 393 336 kept in the new configuration as "samba3:<name>" 394 337 """ … … 435 378 436 379 380 def upgrade_provision(samba3, logger, credentials, session_info, 381 smbconf, targetdir): 382 oldconf = samba3.get_conf() 383 384 if oldconf.get("domain logons") == "True": 385 serverrole = "domain controller" 386 else: 387 if oldconf.get("security") == "user": 388 serverrole = "standalone" 389 else: 390 serverrole = "member server" 391 392 domainname = oldconf.get("workgroup") 393 realm = oldconf.get("realm") 394 netbiosname = oldconf.get("netbios name") 395 396 secrets_db = samba3.get_secrets_db() 397 398 if domainname is None: 399 domainname = secrets_db.domains()[0] 400 logger.warning("No domain specified in smb.conf file, assuming '%s'", 401 domainname) 402 403 if realm is None: 404 if oldconf.get("domain logons") == "True": 405 logger.warning("No realm specified in smb.conf file and being a DC. That upgrade path doesn't work! Please add a 'realm' directive to your old smb.conf to let us know which one you want to use (generally it's the upcased DNS domainname).") 406 return 407 else: 408 realm = domainname.upper() 409 logger.warning("No realm specified in smb.conf file, assuming '%s'", 410 realm) 411 412 domainguid = secrets_db.get_domain_guid(domainname) 413 domainsid = secrets_db.get_sid(domainname) 414 if domainsid is None: 415 logger.warning("Can't find domain secrets for '%s'; using random SID", 416 domainname) 417 418 if netbiosname is not None: 419 machinepass = secrets_db.get_machine_password(netbiosname) 420 else: 421 machinepass = None 422 423 result = provision(logger=logger, 424 session_info=session_info, credentials=credentials, 425 targetdir=targetdir, realm=realm, domain=domainname, 426 domainguid=domainguid, domainsid=domainsid, 427 hostname=netbiosname, machinepass=machinepass, 428 serverrole=serverrole) 429 430 import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db()) 431 432 # FIXME: import_registry(registry.Registry(), samba3.get_registry()) 433 434 # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn) 435 436 groupdb = samba3.get_groupmapping_db() 437 for sid in groupdb.groupsids(): 438 (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid) 439 # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn) 440 441 # FIXME: Aliases 442 443 passdb = samba3.get_sam_db() 444 for name in passdb: 445 user = passdb[name] 446 #FIXME: import_sam_account(result.samdb, user, domaindn, domainsid) 447 448 if hasattr(passdb, 'ldap_url'): 449 logger.info("Enabling Samba3 LDAP mappings for SAM database") 450 451 enable_samba3sam(result.samdb, passdb.ldap_url) 452 -
vendor/current/source4/scripting/python/uuidmodule.c
r414 r740 18 18 */ 19 19 20 #include <Python.h> 20 21 #include "includes.h" 21 #include <Python.h>22 22 #include "librpc/ndr/libndr.h" 23 23
Note:
See TracChangeset
for help on using the changeset viewer.