From 87afc3aee1ea593069322a49355dd8780d99e123 Mon Sep 17 00:00:00 2001 From: Jelmer Vernooij Date: Fri, 28 Dec 2012 15:37:14 +0100 Subject: Move python modules from source4/scripting/python/ to python/. Reviewed-by: Andrew Bartlett Autobuild-User(master): Andrew Bartlett Autobuild-Date(master): Sat Mar 2 03:57:34 CET 2013 on sn-devel-104 --- source4/scripting/python/examples/dnsserver.py | 89 - source4/scripting/python/examples/netbios.py | 28 - source4/scripting/python/examples/samr.py | 117 - source4/scripting/python/examples/winreg.py | 87 - source4/scripting/python/modules.c | 63 - source4/scripting/python/modules.h | 25 - source4/scripting/python/pyglue.c | 250 --- source4/scripting/python/samba/__init__.py | 363 ---- source4/scripting/python/samba/common.py | 99 - source4/scripting/python/samba/dbchecker.py | 947 -------- source4/scripting/python/samba/drs_utils.py | 255 --- source4/scripting/python/samba/getopt.py | 251 --- source4/scripting/python/samba/hostconfig.py | 81 - source4/scripting/python/samba/idmap.py | 98 - source4/scripting/python/samba/join.py | 1149 ---------- source4/scripting/python/samba/kcc_utils.py | 2182 ------------------- .../python/samba/ms_display_specifiers.py | 187 -- source4/scripting/python/samba/ms_schema.py | 290 --- source4/scripting/python/samba/ndr.py | 50 - source4/scripting/python/samba/netcmd/__init__.py | 231 -- source4/scripting/python/samba/netcmd/common.py | 71 - source4/scripting/python/samba/netcmd/dbcheck.py | 143 -- .../scripting/python/samba/netcmd/delegation.py | 263 --- source4/scripting/python/samba/netcmd/dns.py | 1186 ---------- source4/scripting/python/samba/netcmd/domain.py | 1344 ------------ source4/scripting/python/samba/netcmd/drs.py | 510 ----- source4/scripting/python/samba/netcmd/dsacl.py | 182 -- source4/scripting/python/samba/netcmd/fsmo.py | 277 --- source4/scripting/python/samba/netcmd/gpo.py | 1177 ---------- source4/scripting/python/samba/netcmd/group.py | 376 ---- source4/scripting/python/samba/netcmd/ldapcmp.py | 998 --------- source4/scripting/python/samba/netcmd/main.py | 70 - source4/scripting/python/samba/netcmd/ntacl.py | 260 --- source4/scripting/python/samba/netcmd/processes.py | 78 - source4/scripting/python/samba/netcmd/rodc.py | 108 - source4/scripting/python/samba/netcmd/sites.py | 105 - source4/scripting/python/samba/netcmd/spn.py | 205 -- source4/scripting/python/samba/netcmd/testparm.py | 209 -- source4/scripting/python/samba/netcmd/time.py | 59 - source4/scripting/python/samba/netcmd/user.py | 605 ------ source4/scripting/python/samba/netcmd/vampire.py | 55 - source4/scripting/python/samba/ntacls.py | 240 --- .../scripting/python/samba/provision/__init__.py | 2279 -------------------- .../scripting/python/samba/provision/backend.py | 840 -------- source4/scripting/python/samba/provision/common.py | 82 - .../scripting/python/samba/provision/descriptor.py | 359 --- .../scripting/python/samba/provision/sambadns.py | 1135 ---------- source4/scripting/python/samba/samba3/__init__.py | 408 ---- source4/scripting/python/samba/samdb.py | 886 -------- source4/scripting/python/samba/schema.py | 204 -- source4/scripting/python/samba/sd_utils.py | 80 - source4/scripting/python/samba/sites.py | 125 -- source4/scripting/python/samba/tdb_util.py | 41 - source4/scripting/python/samba/tests/__init__.py | 237 -- source4/scripting/python/samba/tests/auth.py | 31 - .../python/samba/tests/blackbox/__init__.py | 17 - .../python/samba/tests/blackbox/ndrdump.py | 49 - .../python/samba/tests/blackbox/samba_tool_drs.py | 97 - source4/scripting/python/samba/tests/common.py | 40 - source4/scripting/python/samba/tests/core.py | 63 - .../scripting/python/samba/tests/credentials.py | 98 - .../python/samba/tests/dcerpc/__init__.py | 20 - .../scripting/python/samba/tests/dcerpc/bare.py | 51 - .../python/samba/tests/dcerpc/dnsserver.py | 241 --- .../scripting/python/samba/tests/dcerpc/misc.py | 62 - .../python/samba/tests/dcerpc/registry.py | 51 - .../python/samba/tests/dcerpc/rpc_talloc.py | 84 - .../scripting/python/samba/tests/dcerpc/rpcecho.py | 71 - source4/scripting/python/samba/tests/dcerpc/sam.py | 50 - .../scripting/python/samba/tests/dcerpc/srvsvc.py | 68 - .../scripting/python/samba/tests/dcerpc/testrpc.py | 141 -- .../scripting/python/samba/tests/dcerpc/unix.py | 49 - source4/scripting/python/samba/tests/dns.py | 622 ------ source4/scripting/python/samba/tests/docs.py | 127 -- source4/scripting/python/samba/tests/dsdb.py | 130 -- source4/scripting/python/samba/tests/gensec.py | 146 -- source4/scripting/python/samba/tests/getopt.py | 55 - source4/scripting/python/samba/tests/hostconfig.py | 74 - .../python/samba/tests/libsmb_samba_internal.py | 78 - source4/scripting/python/samba/tests/messaging.py | 67 - source4/scripting/python/samba/tests/netcmd.py | 90 - source4/scripting/python/samba/tests/ntacls.py | 83 - source4/scripting/python/samba/tests/param.py | 57 - source4/scripting/python/samba/tests/policy.py | 34 - source4/scripting/python/samba/tests/posixacl.py | 732 ------- source4/scripting/python/samba/tests/provision.py | 203 -- source4/scripting/python/samba/tests/registry.py | 60 - source4/scripting/python/samba/tests/samba3.py | 219 -- source4/scripting/python/samba/tests/samba3sam.py | 1125 ---------- .../python/samba/tests/samba_tool/__init__.py | 15 - .../python/samba/tests/samba_tool/base.py | 114 - .../scripting/python/samba/tests/samba_tool/gpo.py | 79 - .../python/samba/tests/samba_tool/group.py | 169 -- .../python/samba/tests/samba_tool/ntacl.py | 135 -- .../python/samba/tests/samba_tool/processes.py | 35 - .../python/samba/tests/samba_tool/timecmd.py | 43 - .../python/samba/tests/samba_tool/user.py | 362 ---- source4/scripting/python/samba/tests/samdb.py | 96 - source4/scripting/python/samba/tests/security.py | 143 -- source4/scripting/python/samba/tests/source.py | 264 --- source4/scripting/python/samba/tests/strings.py | 103 - .../scripting/python/samba/tests/unicodenames.py | 29 - source4/scripting/python/samba/tests/upgrade.py | 40 - .../python/samba/tests/upgradeprovision.py | 135 -- .../python/samba/tests/upgradeprovisionneeddc.py | 179 -- source4/scripting/python/samba/tests/xattr.py | 126 -- source4/scripting/python/samba/upgrade.py | 938 -------- source4/scripting/python/samba/upgradehelpers.py | 913 -------- .../scripting/python/samba/web_server/__init__.py | 79 - source4/scripting/python/samba/xattr.py | 61 - source4/scripting/python/samba_external/README | 4 - source4/scripting/python/uuidmodule.c | 58 - source4/scripting/python/wscript_build | 39 - 113 files changed, 31383 deletions(-) delete mode 100755 source4/scripting/python/examples/dnsserver.py delete mode 100644 source4/scripting/python/examples/netbios.py delete mode 100755 source4/scripting/python/examples/samr.py delete mode 100755 source4/scripting/python/examples/winreg.py delete mode 100644 source4/scripting/python/modules.c delete mode 100644 source4/scripting/python/modules.h delete mode 100644 source4/scripting/python/pyglue.c delete mode 100644 source4/scripting/python/samba/__init__.py delete mode 100644 source4/scripting/python/samba/common.py delete mode 100644 source4/scripting/python/samba/dbchecker.py delete mode 100644 source4/scripting/python/samba/drs_utils.py delete mode 100644 source4/scripting/python/samba/getopt.py delete mode 100644 source4/scripting/python/samba/hostconfig.py delete mode 100644 source4/scripting/python/samba/idmap.py delete mode 100644 source4/scripting/python/samba/join.py delete mode 100644 source4/scripting/python/samba/kcc_utils.py delete mode 100644 source4/scripting/python/samba/ms_display_specifiers.py delete mode 100644 source4/scripting/python/samba/ms_schema.py delete mode 100644 source4/scripting/python/samba/ndr.py delete mode 100644 source4/scripting/python/samba/netcmd/__init__.py delete mode 100644 source4/scripting/python/samba/netcmd/common.py delete mode 100644 source4/scripting/python/samba/netcmd/dbcheck.py delete mode 100644 source4/scripting/python/samba/netcmd/delegation.py delete mode 100644 source4/scripting/python/samba/netcmd/dns.py delete mode 100644 source4/scripting/python/samba/netcmd/domain.py delete mode 100644 source4/scripting/python/samba/netcmd/drs.py delete mode 100644 source4/scripting/python/samba/netcmd/dsacl.py delete mode 100644 source4/scripting/python/samba/netcmd/fsmo.py delete mode 100644 source4/scripting/python/samba/netcmd/gpo.py delete mode 100644 source4/scripting/python/samba/netcmd/group.py delete mode 100644 source4/scripting/python/samba/netcmd/ldapcmp.py delete mode 100644 source4/scripting/python/samba/netcmd/main.py delete mode 100644 source4/scripting/python/samba/netcmd/ntacl.py delete mode 100644 source4/scripting/python/samba/netcmd/processes.py delete mode 100644 source4/scripting/python/samba/netcmd/rodc.py delete mode 100644 source4/scripting/python/samba/netcmd/sites.py delete mode 100644 source4/scripting/python/samba/netcmd/spn.py delete mode 100644 source4/scripting/python/samba/netcmd/testparm.py delete mode 100644 source4/scripting/python/samba/netcmd/time.py delete mode 100644 source4/scripting/python/samba/netcmd/user.py delete mode 100644 source4/scripting/python/samba/netcmd/vampire.py delete mode 100644 source4/scripting/python/samba/ntacls.py delete mode 100644 source4/scripting/python/samba/provision/__init__.py delete mode 100644 source4/scripting/python/samba/provision/backend.py delete mode 100644 source4/scripting/python/samba/provision/common.py delete mode 100644 source4/scripting/python/samba/provision/descriptor.py delete mode 100644 source4/scripting/python/samba/provision/sambadns.py delete mode 100644 source4/scripting/python/samba/samba3/__init__.py delete mode 100644 source4/scripting/python/samba/samdb.py delete mode 100644 source4/scripting/python/samba/schema.py delete mode 100644 source4/scripting/python/samba/sd_utils.py delete mode 100644 source4/scripting/python/samba/sites.py delete mode 100644 source4/scripting/python/samba/tdb_util.py delete mode 100644 source4/scripting/python/samba/tests/__init__.py delete mode 100644 source4/scripting/python/samba/tests/auth.py delete mode 100644 source4/scripting/python/samba/tests/blackbox/__init__.py delete mode 100644 source4/scripting/python/samba/tests/blackbox/ndrdump.py delete mode 100644 source4/scripting/python/samba/tests/blackbox/samba_tool_drs.py delete mode 100644 source4/scripting/python/samba/tests/common.py delete mode 100644 source4/scripting/python/samba/tests/core.py delete mode 100644 source4/scripting/python/samba/tests/credentials.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/__init__.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/bare.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/dnsserver.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/misc.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/registry.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/rpc_talloc.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/rpcecho.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/sam.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/srvsvc.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/testrpc.py delete mode 100644 source4/scripting/python/samba/tests/dcerpc/unix.py delete mode 100644 source4/scripting/python/samba/tests/dns.py delete mode 100644 source4/scripting/python/samba/tests/docs.py delete mode 100644 source4/scripting/python/samba/tests/dsdb.py delete mode 100644 source4/scripting/python/samba/tests/gensec.py delete mode 100644 source4/scripting/python/samba/tests/getopt.py delete mode 100644 source4/scripting/python/samba/tests/hostconfig.py delete mode 100644 source4/scripting/python/samba/tests/libsmb_samba_internal.py delete mode 100644 source4/scripting/python/samba/tests/messaging.py delete mode 100644 source4/scripting/python/samba/tests/netcmd.py delete mode 100644 source4/scripting/python/samba/tests/ntacls.py delete mode 100644 source4/scripting/python/samba/tests/param.py delete mode 100644 source4/scripting/python/samba/tests/policy.py delete mode 100644 source4/scripting/python/samba/tests/posixacl.py delete mode 100644 source4/scripting/python/samba/tests/provision.py delete mode 100644 source4/scripting/python/samba/tests/registry.py delete mode 100644 source4/scripting/python/samba/tests/samba3.py delete mode 100644 source4/scripting/python/samba/tests/samba3sam.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/__init__.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/base.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/gpo.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/group.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/ntacl.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/processes.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/timecmd.py delete mode 100644 source4/scripting/python/samba/tests/samba_tool/user.py delete mode 100644 source4/scripting/python/samba/tests/samdb.py delete mode 100644 source4/scripting/python/samba/tests/security.py delete mode 100644 source4/scripting/python/samba/tests/source.py delete mode 100644 source4/scripting/python/samba/tests/strings.py delete mode 100644 source4/scripting/python/samba/tests/unicodenames.py delete mode 100644 source4/scripting/python/samba/tests/upgrade.py delete mode 100644 source4/scripting/python/samba/tests/upgradeprovision.py delete mode 100644 source4/scripting/python/samba/tests/upgradeprovisionneeddc.py delete mode 100644 source4/scripting/python/samba/tests/xattr.py delete mode 100644 source4/scripting/python/samba/upgrade.py delete mode 100644 source4/scripting/python/samba/upgradehelpers.py delete mode 100644 source4/scripting/python/samba/web_server/__init__.py delete mode 100644 source4/scripting/python/samba/xattr.py delete mode 100644 source4/scripting/python/samba_external/README delete mode 100644 source4/scripting/python/uuidmodule.c delete mode 100644 source4/scripting/python/wscript_build (limited to 'source4/scripting/python') diff --git a/source4/scripting/python/examples/dnsserver.py b/source4/scripting/python/examples/dnsserver.py deleted file mode 100755 index c65b1c40998..00000000000 --- a/source4/scripting/python/examples/dnsserver.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python - -# script to test the dnsserver RPC protocol - -import sys -from optparse import OptionParser - -sys.path.insert(0, "bin/python") - -import samba -import samba.getopt as options -from samba.dcerpc import dnsserver, security, dnsp - - -########### main code ########### -if __name__ == "__main__": - parser = OptionParser("dnsserver [options] server") - sambaopts = options.SambaOptions(parser) - credopts = options.CredentialsOptionsDouble(parser) - parser.add_option_group(credopts) - - (opts, args) = parser.parse_args() - - if len(args) < 3: - print("Usage: dnsserver.py [options] DNSSERVER DNSZONE NEWNAME") - sys.exit(1) - - server = args[0] - dnszone = args[1] - newname = args[2] - - lp = sambaopts.get_loadparm() - creds = credopts.get_credentials(lp) - - if not creds.authentication_requested(): - parser.error("You must supply credentials") - - binding_str = "ncacn_ip_tcp:%s[print,sign]" % server - - dns_conn = dnsserver.dnsserver(binding_str, lp, creds) - - print("querying a NS record") - res = dns_conn.DnssrvEnumRecords2(0x00070000, - 0, - server, - dnszone, - newname, - None, - dnsp.DNS_TYPE_NS, - 0x0f, - None, - None) - - print("adding a NS glue record") - name = dnsserver.DNS_RPC_NAME() - name.str = newname - - addrec = dnsserver.DNS_RPC_RECORD() - addrec.wType = dnsp.DNS_TYPE_NS - addrec.dwFlags = 0 - addrec.dwSerial = 0 - addrec.dwTtlSeconds = 3600 - addrec.dwTimeStamp = 0 - addrec.dwReserved = 0 - addrec.data = name - - addrecbuf = dnsserver.DNS_RPC_RECORD_BUF() - addrecbuf.rec = addrec - - res = dns_conn.DnssrvUpdateRecord2(0x00070000, - 0, - server, - dnszone, - newname, - addrecbuf, - None) - - - print("querying the NS record") - res = dns_conn.DnssrvEnumRecords2(0x00070000, - 0, - server, - dnszone, - newname, - None, - dnsp.DNS_TYPE_NS, - 0x0f, - None, - None) diff --git a/source4/scripting/python/examples/netbios.py b/source4/scripting/python/examples/netbios.py deleted file mode 100644 index a29b09f0517..00000000000 --- a/source4/scripting/python/examples/netbios.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -# Unix SMB/CIFS implementation. -# Copyright (C) Jelmer Vernooij 2008 -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# - -from samba.netbios import Node - -n = Node() -(reply_from, names, addresses) = n.query_name("GANIEDA", "192.168.4.0", - timeout=4) - -print "Received reply from %s:" % (reply_from, ) -print "Names: %r" % (names, ) -print "Addresses: %r" % (addresses, ) diff --git a/source4/scripting/python/examples/samr.py b/source4/scripting/python/examples/samr.py deleted file mode 100755 index 9b8e31e434b..00000000000 --- a/source4/scripting/python/examples/samr.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# Unix SMB/CIFS implementation. -# Copyright © Jelmer Vernooij 2008 -# -# Based on samr.js © Andrew Tridgell -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# - -import sys - -sys.path.insert(0, "bin/python") - -from samba.dcerpc import samr, security - -def display_lsa_string(str): - return str.string - -def FillUserInfo(samr, dom_handle, users, level): - """fill a user array with user information from samrQueryUserInfo""" - for i in range(len(users)): - user_handle = samr.OpenUser(handle, security.SEC_FLAG_MAXIMUM_ALLOWED, users[i].idx) - info = samr.QueryUserInfo(user_handle, level) - info.name = users[i].name - info.idx = users[i].idx - users[i] = info - samr.Close(user_handle) - -def toArray((handle, array, num_entries)): - ret = [] - for x in range(num_entries): - ret.append((array.entries[x].idx, array.entries[x].name)) - return ret - - -def test_Connect(samr): - """test the samr_Connect interface""" - print "Testing samr_Connect" - return samr.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED) - -def test_LookupDomain(samr, handle, domain): - """test the samr_LookupDomain interface""" - print "Testing samr_LookupDomain" - return samr.LookupDomain(handle, domain) - -def test_OpenDomain(samr, handle, sid): - """test the samr_OpenDomain interface""" - print "Testing samr_OpenDomain" - return samr.OpenDomain(handle, security.SEC_FLAG_MAXIMUM_ALLOWED, sid) - -def test_EnumDomainUsers(samr, dom_handle): - """test the samr_EnumDomainUsers interface""" - print "Testing samr_EnumDomainUsers" - users = toArray(samr.EnumDomainUsers(dom_handle, 0, 0, -1)) - print "Found %d users" % len(users) - for idx, user in users: - print "\t%s\t(%d)" % (user.string, idx) - -def test_EnumDomainGroups(samr, dom_handle): - """test the samr_EnumDomainGroups interface""" - print "Testing samr_EnumDomainGroups" - groups = toArray(samr.EnumDomainGroups(dom_handle, 0, 0)) - print "Found %d groups" % len(groups) - for idx, group in groups: - print "\t%s\t(%d)" % (group.string, idx) - -def test_domain_ops(samr, dom_handle): - """test domain specific ops""" - test_EnumDomainUsers(samr, dom_handle) - test_EnumDomainGroups(samr, dom_handle) - -def test_EnumDomains(samr, handle): - """test the samr_EnumDomains interface""" - print "Testing samr_EnumDomains" - - domains = toArray(samr.EnumDomains(handle, 0, -1)) - print "Found %d domains" % len(domains) - for idx, domain in domains: - print "\t%s (%d)" % (display_lsa_string(domain), idx) - for idx, domain in domains: - print "Testing domain %s" % display_lsa_string(domain) - sid = samr.LookupDomain(handle, domain) - dom_handle = test_OpenDomain(samr, handle, sid) - test_domain_ops(samr, dom_handle) - samr.Close(dom_handle) - -if len(sys.argv) != 2: - print "Usage: samr.js " - sys.exit(1) - -binding = sys.argv[1] - -print "Connecting to %s" % binding -try: - samr = samr.samr(binding) -except Exception, e: - print "Failed to connect to %s: %s" % (binding, e.message) - sys.exit(1) - -handle = test_Connect(samr) -test_EnumDomains(samr, handle) -samr.Close(handle) - -print "All OK" diff --git a/source4/scripting/python/examples/winreg.py b/source4/scripting/python/examples/winreg.py deleted file mode 100755 index 484a69b8424..00000000000 --- a/source4/scripting/python/examples/winreg.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# tool to manipulate a remote registry -# Copyright Andrew Tridgell 2005 -# Copyright Jelmer Vernooij 2007 -# Released under the GNU GPL v3 or later -# - -import sys - -# Find right directory when running from source tree -sys.path.insert(0, "bin/python") - -from samba.dcerpc import winreg -import optparse -import samba.getopt as options - -parser = optparse.OptionParser("%s [path]" % sys.argv[0]) -sambaopts = options.SambaOptions(parser) -parser.add_option_group(sambaopts) -parser.add_option("--createkey", type="string", metavar="KEYNAME", - help="create a key") - -opts, args = parser.parse_args() - -if len(args) < 1: - parser.print_usage() - sys.exit(-1) - -binding = args[0] - -print "Connecting to " + binding -conn = winreg.winreg(binding, sambaopts.get_loadparm()) - -def list_values(key): - (num_values, max_valnamelen, max_valbufsize) = conn.QueryInfoKey(key, winreg.String())[4:8] - for i in range(num_values): - name = winreg.StringBuf() - name.size = max_valnamelen - (name, type, data, _, data_len) = conn.EnumValue(key, i, name, 0, "", max_valbufsize, 0) - print "\ttype=%-30s size=%4d '%s'" % type, len, name - if type in (winreg.REG_SZ, winreg.REG_EXPAND_SZ): - print "\t\t'%s'" % data -# if (v.type == reg.REG_MULTI_SZ) { -# for (j in v.value) { -# printf("\t\t'%s'\n", v.value[j]) -# } -# } -# if (v.type == reg.REG_DWORD || v.type == reg.REG_DWORD_BIG_ENDIAN) { -# printf("\t\t0x%08x (%d)\n", v.value, v.value) -# } -# if (v.type == reg.REG_QWORD) { -# printf("\t\t0x%llx (%lld)\n", v.value, v.value) -# } - -def list_path(key, path): - count = 0 - (num_subkeys, max_subkeylen, max_subkeysize) = conn.QueryInfoKey(key, winreg.String())[1:4] - for i in range(num_subkeys): - name = winreg.StringBuf() - name.size = max_subkeysize - keyclass = winreg.StringBuf() - keyclass.size = max_subkeysize - (name, _, _) = conn.EnumKey(key, i, name, keyclass=keyclass, last_changed_time=None)[0] - subkey = conn.OpenKey(key, name, 0, winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS) - count += list_path(subkey, "%s\\%s" % (path, name)) - list_values(subkey) - return count - -if len(args) > 1: - root = args[1] -else: - root = "HKLM" - -if opts.createkey: - reg.create_key("HKLM\\SOFTWARE", opt.createkey) -else: - print "Listing registry tree '%s'" % root - try: - root_key = getattr(conn, "Open%s" % root)(None, winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS) - except AttributeError: - print "Unknown root key name %s" % root - sys.exit(1) - count = list_path(root_key, root) - if count == 0: - print "No entries found" - sys.exit(1) diff --git a/source4/scripting/python/modules.c b/source4/scripting/python/modules.c deleted file mode 100644 index 78cdbc0d879..00000000000 --- a/source4/scripting/python/modules.c +++ /dev/null @@ -1,63 +0,0 @@ -/* - Unix SMB/CIFS implementation. - Samba utility functions - Copyright (C) Jelmer Vernooij 2007 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -#include -#include "includes.h" -#include "scripting/python/modules.h" -#include "dynconfig/dynconfig.h" - -static bool PySys_PathPrepend(PyObject *list, const char *path) -{ - PyObject *py_path = PyString_FromString(path); - if (py_path == NULL) - return false; - - return (PyList_Insert(list, 0, py_path) == 0); -} - -bool py_update_path(void) -{ - PyObject *mod_sys, *py_path; - - mod_sys = PyImport_ImportModule("sys"); - if (mod_sys == NULL) { - return false; - } - - py_path = PyObject_GetAttrString(mod_sys, "path"); - if (py_path == NULL) { - return false; - } - - if (!PyList_Check(py_path)) { - return false; - } - - if (!PySys_PathPrepend(py_path, dyn_PYTHONDIR)) { - return false; - } - - if (strcmp(dyn_PYTHONARCHDIR, dyn_PYTHONDIR) != 0) { - if (!PySys_PathPrepend(py_path, dyn_PYTHONARCHDIR)) { - return false; - } - } - - return true; -} diff --git a/source4/scripting/python/modules.h b/source4/scripting/python/modules.h deleted file mode 100644 index e7e97aa1bf4..00000000000 --- a/source4/scripting/python/modules.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - Unix SMB/CIFS implementation. - Samba utility functions - Copyright (C) Jelmer Vernooij 2007 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -#ifndef __SAMBA_PYTHON_MODULES_H__ -#define __SAMBA_PYTHON_MODULES_H__ - -bool py_update_path(void); - -#endif /* __SAMBA_PYTHON_MODULES_H__ */ diff --git a/source4/scripting/python/pyglue.c b/source4/scripting/python/pyglue.c deleted file mode 100644 index 735f03a1e16..00000000000 --- a/source4/scripting/python/pyglue.c +++ /dev/null @@ -1,250 +0,0 @@ -/* - Unix SMB/CIFS implementation. - Copyright (C) Jelmer Vernooij 2007 - Copyright (C) Matthias Dieter Wallnöfer 2009 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -#include -#include "includes.h" -#include "version.h" -#include "param/pyparam.h" -#include "lib/socket/netif.h" - -void init_glue(void); - -#ifndef Py_RETURN_NONE -#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None -#endif - -static PyObject *py_generate_random_str(PyObject *self, PyObject *args) -{ - int len; - PyObject *ret; - char *retstr; - if (!PyArg_ParseTuple(args, "i", &len)) - return NULL; - - retstr = generate_random_str(NULL, len); - ret = PyString_FromString(retstr); - talloc_free(retstr); - return ret; -} - -static PyObject *py_generate_random_password(PyObject *self, PyObject *args) -{ - int min, max; - PyObject *ret; - char *retstr; - if (!PyArg_ParseTuple(args, "ii", &min, &max)) - return NULL; - - retstr = generate_random_password(NULL, min, max); - if (retstr == NULL) { - return NULL; - } - ret = PyString_FromString(retstr); - talloc_free(retstr); - return ret; -} - -static PyObject *py_unix2nttime(PyObject *self, PyObject *args) -{ - time_t t; - unsigned int _t; - NTTIME nt; - - if (!PyArg_ParseTuple(args, "I", &_t)) { - return NULL; - } - t = _t; - - unix_to_nt_time(&nt, t); - - return PyLong_FromLongLong((uint64_t)nt); -} - -static PyObject *py_nttime2unix(PyObject *self, PyObject *args) -{ - time_t t; - NTTIME nt; - if (!PyArg_ParseTuple(args, "K", &nt)) - return NULL; - - t = nt_time_to_unix(nt); - - return PyInt_FromLong((uint64_t)t); -} - -static PyObject *py_nttime2string(PyObject *self, PyObject *args) -{ - PyObject *ret; - NTTIME nt; - TALLOC_CTX *tmp_ctx; - const char *string; - if (!PyArg_ParseTuple(args, "K", &nt)) - return NULL; - - tmp_ctx = talloc_new(NULL); - if (tmp_ctx == NULL) { - PyErr_NoMemory(); - return NULL; - } - - string = nt_time_string(tmp_ctx, nt); - ret = PyString_FromString(string); - - talloc_free(tmp_ctx); - - return ret; -} - -static PyObject *py_set_debug_level(PyObject *self, PyObject *args) -{ - unsigned level; - if (!PyArg_ParseTuple(args, "I", &level)) - return NULL; - (DEBUGLEVEL) = level; - Py_RETURN_NONE; -} - -static PyObject *py_get_debug_level(PyObject *self) -{ - return PyInt_FromLong(DEBUGLEVEL); -} - -/* - return the list of interface IPs we have configured - takes an loadparm context, returns a list of IPs in string form - - Does not return addresses on 127.0.0.0/8 - */ -static PyObject *py_interface_ips(PyObject *self, PyObject *args) -{ - PyObject *pylist; - int count; - TALLOC_CTX *tmp_ctx; - PyObject *py_lp_ctx; - struct loadparm_context *lp_ctx; - struct interface *ifaces; - int i, ifcount; - int all_interfaces = 1; - - if (!PyArg_ParseTuple(args, "O|i", &py_lp_ctx, &all_interfaces)) - return NULL; - - tmp_ctx = talloc_new(NULL); - if (tmp_ctx == NULL) { - PyErr_NoMemory(); - return NULL; - } - - lp_ctx = lpcfg_from_py_object(tmp_ctx, py_lp_ctx); - if (lp_ctx == NULL) { - talloc_free(tmp_ctx); - return NULL; - } - - load_interface_list(tmp_ctx, lp_ctx, &ifaces); - - count = iface_list_count(ifaces); - - /* first count how many are not loopback addresses */ - for (ifcount = i = 0; i string\n" - "Generate random string with specified length." }, - { "generate_random_password", (PyCFunction)py_generate_random_password, - METH_VARARGS, "generate_random_password(min, max) -> string\n" - "Generate random password with a length >= min and <= max." }, - { "unix2nttime", (PyCFunction)py_unix2nttime, METH_VARARGS, - "unix2nttime(timestamp) -> nttime" }, - { "nttime2unix", (PyCFunction)py_nttime2unix, METH_VARARGS, - "nttime2unix(nttime) -> timestamp" }, - { "nttime2string", (PyCFunction)py_nttime2string, METH_VARARGS, - "nttime2string(nttime) -> string" }, - { "set_debug_level", (PyCFunction)py_set_debug_level, METH_VARARGS, - "set debug level" }, - { "get_debug_level", (PyCFunction)py_get_debug_level, METH_NOARGS, - "get debug level" }, - { "interface_ips", (PyCFunction)py_interface_ips, METH_VARARGS, - "interface_ips(lp_ctx[, all_interfaces) -> list_of_ifaces\n" - "\n" - "get interface IP address list"}, - { "strcasecmp_m", (PyCFunction)py_strcasecmp_m, METH_VARARGS, - "(for testing) compare two strings using Samba's strcasecmp_m()"}, - { "strstr_m", (PyCFunction)py_strstr_m, METH_VARARGS, - "(for testing) find one string in another with Samba's strstr_m()"}, - { NULL } -}; - -void init_glue(void) -{ - PyObject *m; - - debug_setup_talloc_log(); - - m = Py_InitModule3("_glue", py_misc_methods, - "Python bindings for miscellaneous Samba functions."); - if (m == NULL) - return; - - PyModule_AddObject(m, "version", - PyString_FromString(SAMBA_VERSION_STRING)); -} - diff --git a/source4/scripting/python/samba/__init__.py b/source4/scripting/python/samba/__init__.py deleted file mode 100644 index cd2a309fc0a..00000000000 --- a/source4/scripting/python/samba/__init__.py +++ /dev/null @@ -1,363 +0,0 @@ -# Unix SMB/CIFS implementation. -# Copyright (C) Jelmer Vernooij 2007-2008 -# -# Based on the original in EJS: -# Copyright (C) Andrew Tridgell 2005 -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# - -"""Samba 4.""" - -__docformat__ = "restructuredText" - -import os -import sys -import samba.param - - -def source_tree_topdir(): - """Return the top level source directory.""" - paths = ["../../..", "../../../.."] - for p in paths: - topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p)) - if os.path.exists(os.path.join(topdir, 'source4')): - return topdir - raise RuntimeError("unable to find top level source directory") - - -def in_source_tree(): - """Return True if we are running from within the samba source tree""" - try: - topdir = source_tree_topdir() - except RuntimeError: - return False - return True - - -import ldb -from samba._ldb import Ldb as _Ldb - - -class Ldb(_Ldb): - """Simple Samba-specific LDB subclass that takes care - of setting up the modules dir, credentials pointers, etc. - - Please note that this is intended to be for all Samba LDB files, - not necessarily the Sam database. For Sam-specific helper - functions see samdb.py. - """ - - def __init__(self, url=None, lp=None, modules_dir=None, session_info=None, - credentials=None, flags=0, options=None): - """Opens a Samba Ldb file. - - :param url: Optional LDB URL to open - :param lp: Optional loadparm object - :param modules_dir: Optional modules directory - :param session_info: Optional session information - :param credentials: Optional credentials, defaults to anonymous. - :param flags: Optional LDB flags - :param options: Additional options (optional) - - This is different from a regular Ldb file in that the Samba-specific - modules-dir is used by default and that credentials and session_info - can be passed through (required by some modules). - """ - - if modules_dir is not None: - self.set_modules_dir(modules_dir) - else: - self.set_modules_dir(os.path.join(samba.param.modules_dir(), "ldb")) - - if session_info is not None: - self.set_session_info(session_info) - - if credentials is not None: - self.set_credentials(credentials) - - if lp is not None: - self.set_loadparm(lp) - - # This must be done before we load the schema, as these handlers for - # objectSid and objectGUID etc must take precedence over the 'binary - # attribute' declaration in the schema - self.register_samba_handlers() - - # TODO set debug - def msg(l, text): - print text - #self.set_debug(msg) - - self.set_utf8_casefold() - - # Allow admins to force non-sync ldb for all databases - if lp is not None: - nosync_p = lp.get("nosync", "ldb") - if nosync_p is not None and nosync_p: - flags |= ldb.FLG_NOSYNC - - self.set_create_perms(0600) - - if url is not None: - self.connect(url, flags, options) - - def searchone(self, attribute, basedn=None, expression=None, - scope=ldb.SCOPE_BASE): - """Search for one attribute as a string. - - :param basedn: BaseDN for the search. - :param attribute: Name of the attribute - :param expression: Optional search expression. - :param scope: Search scope (defaults to base). - :return: Value of attribute as a string or None if it wasn't found. - """ - res = self.search(basedn, scope, expression, [attribute]) - if len(res) != 1 or res[0][attribute] is None: - return None - values = set(res[0][attribute]) - assert len(values) == 1 - return self.schema_format_value(attribute, values.pop()) - - def erase_users_computers(self, dn): - """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. - """ - - try: - res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[], - expression="(|(objectclass=user)(objectclass=computer))") - except ldb.LdbError, (errno, _): - if errno == ldb.ERR_NO_SUCH_OBJECT: - # Ignore no such object errors - return - else: - raise - - try: - for msg in res: - self.delete(msg.dn, ["relax:0"]) - except ldb.LdbError, (errno, _): - if errno != ldb.ERR_NO_SUCH_OBJECT: - # Ignore no such object errors - raise - - def erase_except_schema_controlled(self): - """Erase this ldb. - - :note: Removes all records, except those that are controlled by - Samba4's schema. - """ - - basedn = "" - - # Try to delete user/computer accounts to allow deletion of groups - self.erase_users_computers(basedn) - - # Delete the 'visible' records, and the invisble 'deleted' records (if - # this DB supports it) - for msg in self.search(basedn, ldb.SCOPE_SUBTREE, - "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", - [], controls=["show_deleted:0", "show_recycled:0"]): - try: - self.delete(msg.dn, ["relax:0"]) - except ldb.LdbError, (errno, _): - if errno != ldb.ERR_NO_SUCH_OBJECT: - # Ignore no such object errors - raise - - res = self.search(basedn, ldb.SCOPE_SUBTREE, - "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", - [], controls=["show_deleted:0", "show_recycled:0"]) - assert len(res) == 0 - - # delete the specials - for attr in ["@SUBCLASSES", "@MODULES", - "@OPTIONS", "@PARTITION", "@KLUDGEACL"]: - try: - self.delete(attr, ["relax:0"]) - except ldb.LdbError, (errno, _): - if errno != ldb.ERR_NO_SUCH_OBJECT: - # Ignore missing dn errors - raise - - def erase(self): - """Erase this ldb, removing all records.""" - self.erase_except_schema_controlled() - - # delete the specials - for attr in ["@INDEXLIST", "@ATTRIBUTES"]: - try: - self.delete(attr, ["relax:0"]) - except ldb.LdbError, (errno, _): - if errno != ldb.ERR_NO_SUCH_OBJECT: - # Ignore missing dn errors - raise - - def load_ldif_file_add(self, ldif_path): - """Load a LDIF file. - - :param ldif_path: Path to LDIF file. - """ - self.add_ldif(open(ldif_path, 'r').read()) - - def add_ldif(self, ldif, controls=None): - """Add data based on a LDIF string. - - :param ldif: LDIF text. - """ - for changetype, msg in self.parse_ldif(ldif): - assert changetype == ldb.CHANGETYPE_NONE - self.add(msg, controls) - - def modify_ldif(self, ldif, controls=None): - """Modify database based on a LDIF string. - - :param ldif: LDIF text. - """ - for changetype, msg in self.parse_ldif(ldif): - if changetype == ldb.CHANGETYPE_ADD: - self.add(msg, controls) - else: - self.modify(msg, controls) - - -def substitute_var(text, values): - """Substitute strings of the form ${NAME} in str, replacing - with substitutions from values. - - :param text: Text in which to subsitute. - :param values: Dictionary with keys and values. - """ - - for (name, value) in values.items(): - assert isinstance(name, str), "%r is not a string" % name - assert isinstance(value, str), "Value %r for %s is not a string" % (value, name) - text = text.replace("${%s}" % name, value) - - return text - - -def check_all_substituted(text): - """Check that all substitution variables in a string have been replaced. - - If not, raise an exception. - - :param text: The text to search for substitution variables - """ - if not "${" in text: - return - - var_start = text.find("${") - var_end = text.find("}", var_start) - - raise Exception("Not all variables substituted: %s" % - text[var_start:var_end+1]) - - -def read_and_sub_file(file_name, subst_vars): - """Read a file and sub in variables found in it - - :param file_name: File to be read (typically from setup directory) - param subst_vars: Optional variables to subsitute in the file. - """ - data = open(file_name, 'r').read() - if subst_vars is not None: - data = substitute_var(data, subst_vars) - check_all_substituted(data) - return data - - -def setup_file(template, fname, subst_vars=None): - """Setup a file in the private dir. - - :param template: Path of the template file. - :param fname: Path of the file to create. - :param subst_vars: Substitution variables. - """ - if os.path.exists(fname): - os.unlink(fname) - - data = read_and_sub_file(template, subst_vars) - f = open(fname, 'w') - try: - f.write(data) - finally: - f.close() - -MAX_NETBIOS_NAME_LEN = 15 -def is_valid_netbios_char(c): - return (c.isalnum() or c in " !#$%&'()-.@^_{}~") - - -def valid_netbios_name(name): - """Check whether a name is valid as a NetBIOS name. """ - # See crh's book (1.4.1.1) - if len(name) > MAX_NETBIOS_NAME_LEN: - return False - for x in name: - if not is_valid_netbios_char(x): - return False - return True - - -def import_bundled_package(modulename, location): - """Import the bundled version of a package. - - :note: This should only be called if the system version of the package - is not adequate. - - :param modulename: Module name to import - :param location: Location to add to sys.path (can be relative to - ${srcdir}/lib) - """ - if in_source_tree(): - sys.path.insert(0, os.path.join(source_tree_topdir(), "lib", location)) - sys.modules[modulename] = __import__(modulename) - else: - sys.modules[modulename] = __import__( - "samba.external.%s" % modulename, fromlist=["samba.external"]) - - -def ensure_external_module(modulename, location): - """Add a location to sys.path if an external dependency can't be found. - - :param modulename: Module name to import - :param location: Location to add to sys.path (can be relative to - ${srcdir}/lib) - """ - try: - __import__(modulename) - except ImportError: - import_bundled_package(modulename, location) - - -def dn_from_dns_name(dnsdomain): - """return a DN from a DNS name domain/forest root""" - return "DC=" + ",DC=".join(dnsdomain.split(".")) - -import _glue -version = _glue.version -interface_ips = _glue.interface_ips -set_debug_level = _glue.set_debug_level -get_debug_level = _glue.get_debug_level -unix2nttime = _glue.unix2nttime -nttime2string = _glue.nttime2string -nttime2unix = _glue.nttime2unix -unix2nttime = _glue.unix2nttime -generate_random_password = _glue.generate_random_password -strcasecmp_m = _glue.strcasecmp_m -strstr_m = _glue.strstr_m diff --git a/source4/scripting/python/samba/common.py b/source4/scripting/python/samba/common.py deleted file mode 100644 index e47f276f819..00000000000 --- a/source4/scripting/python/samba/common.py +++ /dev/null @@ -1,99 +0,0 @@ -# Samba common functions -# -# Copyright (C) Matthieu Patou -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# - - -import ldb -import dsdb - - -def confirm(msg, forced=False, allow_all=False): - """confirm an action with the user - - :param msg: A string to print to the user - :param forced: Are the answer forced - """ - if forced: - print("%s [YES]" % msg) - return True - - mapping = { - 'Y': True, - 'YES': True, - '': False, - 'N': False, - 'NO': False, - } - - prompt = '[y/N]' - - if allow_all: - mapping['ALL'] = 'ALL' - mapping['NONE'] = 'NONE' - prompt = '[y/N/all/none]' - - while True: - v = raw_input(msg + ' %s ' % prompt) - v = v.upper() - if v in mapping: - return mapping[v] - print("Unknown response '%s'" % v) - - -def normalise_int32(ivalue): - '''normalise a ldap integer to signed 32 bit''' - if int(ivalue) & 0x80000000 and int(ivalue) > 0: - return str(int(ivalue) - 0x100000000) - return str(ivalue) - - -class dsdb_Dn(object): - '''a class for binary DN''' - - def __init__(self, samdb, dnstring, syntax_oid=None): - '''create a dsdb_Dn''' - if syntax_oid is None: - # auto-detect based on string - if dnstring.startswith("B:"): - syntax_oid = dsdb.DSDB_SYNTAX_BINARY_DN - elif dnstring.startswith("S:"): - syntax_oid = dsdb.DSDB_SYNTAX_STRING_DN - else: - syntax_oid = dsdb.DSDB_SYNTAX_OR_NAME - if syntax_oid in [dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_STRING_DN]: - # it is a binary DN - colons = dnstring.split(':') - if len(colons) < 4: - raise RuntimeError("Invalid DN %s" % dnstring) - prefix_len = 4 + len(colons[1]) + int(colons[1]) - self.prefix = dnstring[0:prefix_len] - self.binary = self.prefix[4:-1] - self.dnstring = dnstring[prefix_len:] - else: - self.dnstring = dnstring - self.prefix = '' - self.binary = '' - self.dn = ldb.Dn(samdb, self.dnstring) - - def __str__(self): - return self.prefix + str(self.dn.extended_str(mode=1)) - - def get_binary_integer(self): - '''return binary part of a dsdb_Dn as an integer, or None''' - if self.prefix == '': - return None - return int(self.binary, 16) diff --git a/source4/scripting/python/samba/dbchecker.py b/source4/scripting/python/samba/dbchecker.py deleted file mode 100644 index 06fd82752f7..00000000000 --- a/source4/scripting/python/samba/dbchecker.py +++ /dev/null @@ -1,947 +0,0 @@ -# Samba4 AD database checker -# -# Copyright (C) Andrew Tridgell 2011 -# Copyright (C) Matthieu Patou 2011 -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . -# - -import ldb -from samba import dsdb -from samba import common -from samba.dcerpc import misc -from samba.ndr import ndr_unpack, ndr_pack -from samba.dcerpc import drsblobs -from samba.common import dsdb_Dn -from samba.dcerpc import security - - -class dbcheck(object): - """check a SAM database for errors""" - - def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False, - yes=False, quiet=False, in_transaction=False): - self.samdb = samdb - self.dict_oid_name = None - self.samdb_schema = (samdb_schema or samdb) - self.verbose = verbose - self.fix = fix - self.yes = yes - self.quiet = quiet - self.remove_all_unknown_attributes = False - self.remove_all_empty_attributes = False - self.fix_all_normalisation = False - self.fix_all_DN_GUIDs = False - self.remove_all_deleted_DN_links = False - self.fix_all_target_mismatch = False - self.fix_all_metadata = False - self.fix_time_metadata = False - self.fix_all_missing_backlinks = False - self.fix_all_orphaned_backlinks = False - self.fix_rmd_flags = False - self.fix_ntsecuritydescriptor = False - self.seize_fsmo_role = False - self.move_to_lost_and_found = False - self.fix_instancetype = False - self.in_transaction = in_transaction - self.infrastructure_dn = ldb.Dn(samdb, "CN=Infrastructure," + samdb.domain_dn()) - self.naming_dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn()) - self.schema_dn = samdb.get_schema_basedn() - self.rid_dn = ldb.Dn(samdb, "CN=RID Manager$,CN=System," + samdb.domain_dn()) - self.ntds_dsa = samdb.get_dsServiceName() - self.class_schemaIDGUID = {} - - res = self.samdb.search(base=self.ntds_dsa, scope=ldb.SCOPE_BASE, attrs=['msDS-hasMasterNCs', 'hasMasterNCs']) - if "msDS-hasMasterNCs" in res[0]: - self.write_ncs = res[0]["msDS-hasMasterNCs"] - else: - # If the Forest Level is less than 2003 then there is no - # msDS-hasMasterNCs, so we fall back to hasMasterNCs - # no need to merge as all the NCs that are in hasMasterNCs must - # also be in msDS-hasMasterNCs (but not the opposite) - if "hasMasterNCs" in res[0]: - self.write_ncs = res[0]["hasMasterNCs"] - else: - self.write_ncs = None - - - def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']): - '''perform a database check, returning the number of errors found''' - - res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls) - self.report('Checking %u objects' % len(res)) - error_count = 0 - - for object in res: - error_count += self.check_object(object.dn, attrs=attrs) - - if DN is None: - error_count += self.check_rootdse() - - if error_count != 0 and not self.fix: - self.report("Please use --fix to fix these errors") - - self.report('Checked %u objects (%u errors)' % (len(res), error_count)) - return error_count - - def report(self, msg): - '''print a message unless quiet is set''' - if not self.quiet: - print(msg) - - def confirm(self, msg, allow_all=False, forced=False): - '''confirm a change''' - if not self.fix: - return False - if self.quiet: - return self.yes - if self.yes: - forced = True - return common.confirm(msg, forced=forced, allow_all=allow_all) - - ################################################################ - # a local confirm function with support for 'all' - def confirm_all(self, msg, all_attr): - '''confirm a change with support for "all" ''' - if not self.fix: - return False - if self.quiet: - return self.yes - if getattr(self, all_attr) == 'NONE': - return False - if getattr(self, all_attr) == 'ALL': - forced = True - else: - forced = self.yes - c = common.confirm(msg, forced=forced, allow_all=True) - if c == 'ALL': - setattr(self, all_attr, 'ALL') - return True - if c == 'NONE': - setattr(self, all_attr, 'NONE') - return False - return c - - def do_modify(self, m, controls, msg, validate=True): - '''perform a modify with optional verbose output''' - if self.verbose: - self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY)) - try: - controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK] - self.samdb.modify(m, controls=controls, validate=validate) - except Exception, err: - self.report("%s : %s" % (msg, err)) - return False - return True - - def do_rename(self, from_dn, to_rdn, to_base, controls, msg): - '''perform a modify with optional verbose output''' - if self.verbose: - self.report("""dn: %s -changeType: modrdn -newrdn: %s -deleteOldRdn: 1 -newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base))) - try: - to_dn = to_rdn + to_base - controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK] - self.samdb.rename(from_dn, to_dn, controls=controls) - except Exception, err: - self.report("%s : %s" % (msg, err)) - return False - return True - - def err_empty_attribute(self, dn, attrname): - '''fix empty attributes''' - self.report("ERROR: Empty attribute %s in %s" % (attrname, dn)) - if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'): - self.report("Not fixing empty attribute %s" % attrname) - return - - m = ldb.Message() - m.dn = dn - m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname) - if self.do_modify(m, ["relax:0", "show_recycled:1"], - "Failed to remove empty attribute %s" % attrname, validate=False): - self.report("Removed empty attribute %s" % attrname) - - def err_normalise_mismatch(self, dn, attrname, values): - '''fix attribute normalisation errors''' - self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn)) - mod_list = [] - for val in values: - normalised = self.samdb.dsdb_normalise_attributes( - self.samdb_schema, attrname, [val]) - if len(normalised) != 1: - self.report("Unable to normalise value '%s'" % val) - mod_list.append((val, '')) - elif (normalised[0] != val): - self.report("value '%s' should be '%s'" % (val, normalised[0])) - mod_list.append((val, normalised[0])) - if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'): - self.report("Not fixing attribute %s" % attrname) - return - - m = ldb.Message() - m.dn = dn - for i in range(0, len(mod_list)): - (val, nval) = mod_list[i] - m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname) - if nval != '': - m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, - attrname) - - if self.do_modify(m, ["relax:0", "show_recycled:1"], - "Failed to normalise attribute %s" % attrname, - validate=False): - self.report("Normalised attribute %s" % attrname) - - def err_normalise_mismatch_replace(self, dn, attrname, values): - '''fix attribute normalisation errors''' - normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values) - self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn)) - self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised))) - if list(normalised) == values: - return - if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'): - self.report("Not fixing attribute '%s'" % attrname) - return - - m = ldb.Message() - m.dn = dn - m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname) - - if self.do_modify(m, ["relax:0", "show_recycled:1"], - "Failed to normalise attribute %s" % attrname, - validate=False): - self.report("Normalised attribute %s" % attrname) - - def is_deleted_objects_dn(self, dsdb_dn): - '''see if a dsdb_Dn is the special Deleted Objects DN''' - return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:" - - def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn): - """handle a DN pointing to a deleted object""" - self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val)) - self.report("Target GUID points at deleted DN %s" % correct_dn) - if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'): - self.report("Not removing") - return - m = ldb.Message() - m.dn = dn - m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname) - if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK], - "Failed to remove deleted DN attribute %s" % attrname): - self.report("Removed deleted DN on attribute %s" % attrname) - - def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn): - """handle a missing target DN (both GUID and DN string form are missing)""" - # check if its a backlink - linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname) - if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1: - self.report("Not removing dangling forward link") - return - self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn) - - def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr): - """handle a missing GUID extended DN component""" - self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val)) - controls=["extended_dn:1:1", "show_recycled:1"] - try: - res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE, - attrs=[], controls=controls) - except ldb.LdbError, (enum, estr): - self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr)) - self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn) - return - if len(res) == 0: - self.report("unable to find object for DN %s" % dsdb_dn.dn) - self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn) - return - dsdb_dn.dn = res[0].dn - - if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'): - self.report("Not fixing %s" % errstr) - return - m = ldb.Messag