本文整理汇总了Python中samba.samdb.SamDB.delete方法的典型用法代码示例。如果您正苦于以下问题:Python SamDB.delete方法的具体用法?Python SamDB.delete怎么用?Python SamDB.delete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类samba.samdb.SamDB
的用法示例。
在下文中一共展示了SamDB.delete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None):
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
filter = ("(&(sAMAccountName=%s)(objectClass=group))" %
groupname)
try:
res = samdb.search(base=samdb.domain_dn(),
scope=ldb.SCOPE_SUBTREE,
expression=filter,
attrs=["dn"])
group_dn = res[0].dn
except IndexError:
raise CommandError('Unable to find group "%s"' % (groupname))
try:
samdb.delete(group_dn)
except Exception as e:
# FIXME: catch more specific exception
raise CommandError('Failed to remove group "%s"' % groupname, e)
self.outf.write("Deleted group %s\n" % groupname)
示例2: run
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
def run(self, psoname, H=None, credopts=None, sambaopts=None,
versionopts=None):
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb))
# sanity-check the PSO exists
check_pso_valid(samdb, pso_dn, psoname)
samdb.delete(pso_dn)
self.message("Deleted PSO %s" % psoname)
示例3: test_add_replicated_objects
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
def test_add_replicated_objects(self):
for o in (
{
'dn': "ou=%s1,%s" % (self.tag, self.base_dn),
"objectclass": "organizationalUnit"
},
{
'dn': "cn=%s2,%s" % (self.tag, self.base_dn),
"objectclass": "user"
},
{
'dn': "cn=%s3,%s" % (self.tag, self.base_dn),
"objectclass": "group"
},
{
'dn': "cn=%s4,%s" % (self.tag, self.service),
"objectclass": "NTDSConnection",
'enabledConnection': 'TRUE',
'fromServer': self.base_dn,
'options': '0'
},
):
try:
self.samdb.add(o)
self.fail("Failed to fail to add %s" % o['dn'])
except ldb.LdbError as e:
(ecode, emsg) = e.args
if ecode != ldb.ERR_REFERRAL:
print(emsg)
self.fail("Adding %s: ldb error: %s %s, wanted referral" %
(o['dn'], ecode, emsg))
else:
m = re.search(r'(ldap://[^>]+)>', emsg)
if m is None:
self.fail("referral seems not to refer to anything")
address = m.group(1)
try:
tmpdb = SamDB(address, credentials=CREDS,
session_info=system_session(LP), lp=LP)
tmpdb.add(o)
tmpdb.delete(o['dn'])
except ldb.LdbError as e:
self.fail("couldn't modify referred location %s" %
address)
if address.lower().startswith(self.samdb.domain_dns_name()):
self.fail("referral address did not give a specific DC")
示例4: LATests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class LATests(samba.tests.TestCase):
def setUp(self):
super(LATests, self).setUp()
self.samdb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.samdb.domain_dn()
self.ou = "OU=la,%s" % self.base_dn
if opts.delete_in_setup:
try:
self.samdb.delete(self.ou, ['tree_delete:1'])
except ldb.LdbError, e:
print "tried deleting %s, got error %s" % (self.ou, e)
self.samdb.add({'objectclass': 'organizationalUnit',
'dn': self.ou})
示例5: run
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
def run(self, computername, credopts=None, sambaopts=None,
versionopts=None, H=None):
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
samaccountname = computername
if not computername.endswith('$'):
samaccountname = "%s$" % computername
filter = ("(&(sAMAccountName=%s)(sAMAccountType=%u))" %
(ldb.binary_encode(samaccountname),
dsdb.ATYPE_WORKSTATION_TRUST))
try:
res = samdb.search(base=samdb.domain_dn(),
scope=ldb.SCOPE_SUBTREE,
expression=filter,
attrs=["userAccountControl", "dNSHostName"])
computer_dn = res[0].dn
computer_ac = int(res[0]["userAccountControl"][0])
if "dNSHostName" in res[0]:
computer_dns_host_name = res[0]["dNSHostName"][0]
else:
computer_dns_host_name = None
except IndexError:
raise CommandError('Unable to find computer "%s"' % computername)
computer_is_workstation = (
computer_ac & dsdb.UF_WORKSTATION_TRUST_ACCOUNT)
if computer_is_workstation == False:
raise CommandError('Failed to remove computer "%s": '
'Computer is not a workstation - removal denied'
% computername)
try:
samdb.delete(computer_dn)
if computer_dns_host_name:
remove_dns_references(
samdb, self.get_logger(), computer_dns_host_name,
ignore_no_name=True)
except Exception as e:
raise CommandError('Failed to remove computer "%s"' %
samaccountname, e)
self.outf.write("Deleted computer %s\n" % computername)
示例6: VLVTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class VLVTests(samba.tests.TestCase):
def create_user(self, i, n, prefix='vlvtest', suffix='', attrs=None):
name = "%s%d%s" % (prefix, i, suffix)
user = {
'cn': name,
"objectclass": "user",
'givenName': "abcdefghijklmnopqrstuvwxyz"[i % 26],
"roomNumber": "%sbc" % (n - i),
"carLicense": "后来经",
"employeeNumber": "%s%sx" % (abs(i * (99 - i)), '\n' * (i & 255)),
"accountExpires": "%s" % (10 ** 9 + 1000000 * i),
"msTSExpireDate4": "19%02d0101010000.0Z" % (i % 100),
"flags": str(i * (n - i)),
"serialNumber": "abc %s%s%s" % ('AaBb |-/'[i & 7],
' 3z}'[i & 3],
'"@'[i & 1],),
}
# _user_broken_attrs tests are broken due to problems outside
# of VLV.
_user_broken_attrs = {
# Sort doesn't look past a NUL byte.
"photo": "\x00%d" % (n - i),
"audio": "%sn octet string %s%s ♫♬\x00lalala" % ('Aa'[i & 1],
chr(i & 255), i),
"displayNamePrintable": "%d\x00%c" % (i, i & 255),
"adminDisplayName": "%d\x00b" % (n-i),
"title": "%d%sb" % (n - i, '\x00' * i),
"comment": "Favourite colour is %d" % (n % (i + 1)),
# Names that vary only in case. Windows returns
# equivalent addresses in the order they were put
# in ('a st', 'A st',...).
"street": "%s st" % (chr(65 | (i & 14) | ((i & 1) * 32))),
}
if attrs is not None:
user.update(attrs)
user['dn'] = "cn=%s,%s" % (user['cn'], self.ou)
if opts.skip_attr_regex:
match = re.compile(opts.skip_attr_regex).search
for k in user.keys():
if match(k):
del user[k]
self.users.append(user)
self.ldb.add(user)
return user
def setUp(self):
super(VLVTests, self).setUp()
self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb.domain_dn()
self.ou = "ou=vlv,%s" % self.base_dn
if opts.delete_in_setup:
try:
self.ldb.delete(self.ou, ['tree_delete:1'])
except ldb.LdbError as e:
print("tried deleting %s, got error %s" % (self.ou, e))
self.ldb.add({
"dn": self.ou,
"objectclass": "organizationalUnit"})
self.users = []
for i in range(N_ELEMENTS):
self.create_user(i, N_ELEMENTS)
attrs = self.users[0].keys()
self.binary_sorted_keys = ['audio',
'photo',
"msTSExpireDate4",
'serialNumber',
"displayNamePrintable"]
self.numeric_sorted_keys = ['flags',
'accountExpires']
self.timestamp_keys = ['msTSExpireDate4']
self.int64_keys = set(['accountExpires'])
self.locale_sorted_keys = [x for x in attrs if
x not in (self.binary_sorted_keys +
self.numeric_sorted_keys)]
# don't try spaces, etc in cn
self.delicate_keys = ['cn']
def tearDown(self):
super(VLVTests, self).tearDown()
if not opts.delete_in_setup:
self.ldb.delete(self.ou, ['tree_delete:1'])
def get_full_list(self, attr, include_cn=False):
"""Fetch the whole list sorted on the attribute, using the VLV.
#.........这里部分代码省略.........
示例7: deprovision_schema
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
def deprovision_schema(setup_path, names, lp, creds, reporter, ldif, msg, modify_mode=False):
"""Deprovision/unmodify schema using LDIF specified file, by reverting the
modifications contained therein.
:param setup_path: Path to the setup directory.
:param names: provision names object.
:param lp: Loadparm context
:param creds: Credentials Context
:param reporter: A progress reporter instance (subclass of AbstractProgressReporter)
:param ldif: path to the LDIF file
:param msg: reporter message
:param modify_mode: whether entries are added or modified
"""
session_info = system_session()
db = SamDB(url=get_ldb_url(lp, creds, names), session_info=session_info,
credentials=creds, lp=lp)
db.transaction_start()
try:
reporter.reportNextStep(msg)
ldif_content = read_and_sub_file(setup_path(ldif),
{"FIRSTORG": names.firstorg,
"FIRSTORGDN": names.firstorgdn,
"CONFIGDN": names.configdn,
"SCHEMADN": names.schemadn,
"DOMAINDN": names.domaindn,
"DOMAIN": names.domain,
"DNSDOMAIN": names.dnsdomain,
"NETBIOSNAME": names.netbiosname,
"HOSTNAME": names.hostname
})
if modify_mode:
lines = ldif_content.splitlines()
keep_line = False
entries = []
current_entry = []
entries.append(current_entry)
for line in lines:
skip_this_line = False
if line.startswith("dn:") or line == "":
# current_entry.append("")
current_entry = []
entries.append(current_entry)
keep_line = True
elif line.startswith("add:"):
keep_line = True
line = "delete:" + line[4:]
elif line.startswith("replace:"):
keep_line = False
elif line.startswith("#") or line.strip() == "":
skip_this_line = True
if keep_line and not skip_this_line:
current_entry.append(line)
entries.reverse()
for entry in entries:
ldif_content = "\n".join(entry)
print ldif_content
try:
db.modify_ldif(ldif_content)
except:
pass
else:
lines = ldif_content.splitlines()
lines.reverse()
for line in lines:
if line.startswith("dn:"):
db.delete(line[4:])
except:
db.transaction_cancel()
raise
db.transaction_commit()
示例8: LATests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class LATests(samba.tests.TestCase):
def setUp(self):
super(LATests, self).setUp()
self.samdb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.samdb.domain_dn()
self.ou = "OU=la,%s" % self.base_dn
if opts.delete_in_setup:
try:
self.samdb.delete(self.ou, ['tree_delete:1'])
except ldb.LdbError as e:
print("tried deleting %s, got error %s" % (self.ou, e))
self.samdb.add({'objectclass': 'organizationalUnit',
'dn': self.ou})
def tearDown(self):
super(LATests, self).tearDown()
if not opts.no_cleanup:
self.samdb.delete(self.ou, ['tree_delete:1'])
def add_object(self, cn, objectclass, more_attrs={}):
dn = "CN=%s,%s" % (cn, self.ou)
attrs = {'cn': cn,
'objectclass': objectclass,
'dn': dn}
attrs.update(more_attrs)
self.samdb.add(attrs)
return dn
def add_objects(self, n, objectclass, prefix=None, more_attrs={}):
if prefix is None:
prefix = objectclass
dns = []
for i in range(n):
dns.append(self.add_object("%s%d" % (prefix, i + 1),
objectclass,
more_attrs=more_attrs))
return dns
def add_linked_attribute(self, src, dest, attr='member',
controls=None):
m = ldb.Message()
m.dn = ldb.Dn(self.samdb, src)
m[attr] = ldb.MessageElement(dest, ldb.FLAG_MOD_ADD, attr)
self.samdb.modify(m, controls=controls)
def remove_linked_attribute(self, src, dest, attr='member',
controls=None):
m = ldb.Message()
m.dn = ldb.Dn(self.samdb, src)
m[attr] = ldb.MessageElement(dest, ldb.FLAG_MOD_DELETE, attr)
self.samdb.modify(m, controls=controls)
def replace_linked_attribute(self, src, dest, attr='member',
controls=None):
m = ldb.Message()
m.dn = ldb.Dn(self.samdb, src)
m[attr] = ldb.MessageElement(dest, ldb.FLAG_MOD_REPLACE, attr)
self.samdb.modify(m, controls=controls)
def attr_search(self, obj, attr, scope=ldb.SCOPE_BASE, **controls):
if opts.no_reveal_internals:
if 'reveal_internals' in controls:
del controls['reveal_internals']
controls = ['%s:%d' % (k, int(v)) for k, v in controls.items()]
res = self.samdb.search(obj,
scope=scope,
attrs=[attr],
controls=controls)
return res
def assert_links(self, obj, expected, attr, msg='', **kwargs):
res = self.attr_search(obj, attr, **kwargs)
if len(expected) == 0:
if attr in res[0]:
self.fail("found attr '%s' in %s" % (attr, res[0]))
return
try:
results = list([x[attr] for x in res][0])
except KeyError:
self.fail("missing attr '%s' on %s" % (attr, obj))
expected = sorted(expected)
results = sorted(results)
if expected != results:
print(msg)
print("expected %s" % expected)
print("received %s" % results)
self.assertEqual(results, expected)
def assert_back_links(self, obj, expected, attr='memberOf', **kwargs):
#.........这里部分代码省略.........
示例9: BaseSortTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class BaseSortTests(samba.tests.TestCase):
avoid_tricky_sort = False
maxDiff = 2000
def create_user(self, i, n, prefix='sorttest', suffix='', attrs=None,
tricky=False):
name = "%s%d%s" % (prefix, i, suffix)
user = {
'cn': name,
"objectclass": "user",
'givenName': "abcdefghijklmnopqrstuvwxyz"[i % 26],
"roomNumber": "%sb\x00c" % (n - i),
"carLicense": "后来经",
"employeeNumber": "%s%sx" % (abs(i * (99 - i)), '\n' * (i & 255)),
"accountExpires": "%s" % (10 ** 9 + 1000000 * i),
"msTSExpireDate4": "19%02d0101010000.0Z" % (i % 100),
"flags": str(i * (n - i)),
"serialNumber": "abc %s%s%s" % ('AaBb |-/'[i & 7],
' 3z}'[i & 3],
'"@'[i & 1],),
"comment": "Favourite colour is %d" % (n % (i + 1)),
}
if self.avoid_tricky_sort:
# We are not even going to try passing tests that assume
# some kind of Unicode awareness.
for k, v in user.items():
user[k] = re.sub(r'[^\w,.]', 'X', v)
else:
# Add some even trickier ones!
fiendish_index = i % len(FIENDISH_TESTS)
user.update({
# Sort doesn't look past a NUL byte.
"photo": "\x00%d" % (n - i),
"audio": "%sn octet string %s%s ♫♬\x00lalala" % ('Aa'[i & 1],
chr(i & 255),
i),
"displayNamePrintable": "%d\x00%c" % (i, i & 255),
"adminDisplayName": "%d\x00b" % (n-i),
"title": "%d%sb" % (n - i, '\x00' * i),
# Names that vary only in case. Windows returns
# equivalent addresses in the order they were put
# in ('a st', 'A st',...). We don't check that.
"street": "%s st" % (chr(65 | (i & 14) | ((i & 1) * 32))),
"streetAddress": FIENDISH_TESTS[fiendish_index],
"postalAddress": FIENDISH_TESTS[-fiendish_index],
})
if attrs is not None:
user.update(attrs)
user['dn'] = "cn=%s,%s" % (user['cn'], self.ou)
self.users.append(user)
self.ldb.add(user)
return user
def setUp(self):
super(BaseSortTests, self).setUp()
self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb.domain_dn()
self.ou = "ou=sort,%s" % self.base_dn
if False:
try:
self.ldb.delete(self.ou, ['tree_delete:1'])
except ldb.LdbError, e:
print "tried deleting %s, got error %s" % (self.ou, e)
self.ldb.add({
"dn": self.ou,
"objectclass": "organizationalUnit"})
self.users = []
n = opts.elements
for i in range(n):
self.create_user(i, n)
attrs = set(self.users[0].keys()) - set([
'objectclass', 'dn'])
self.binary_sorted_keys = attrs.intersection(['audio',
'photo',
"msTSExpireDate4",
'serialNumber',
"displayNamePrintable"])
self.numeric_sorted_keys = attrs.intersection(['flags',
'accountExpires'])
self.timestamp_keys = attrs.intersection(['msTSExpireDate4'])
self.int64_keys = set(['accountExpires'])
self.locale_sorted_keys = [x for x in attrs if
x not in (self.binary_sorted_keys |
self.numeric_sorted_keys)]
self.expected_results = {}
#.........这里部分代码省略.........
示例10: VLVTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class VLVTests(samba.tests.TestCase):
def create_user(self, i, n, prefix='vlvtest', suffix='', attrs=None):
name = "%s%d%s" % (prefix, i, suffix)
user = {
'cn': name,
"objectclass": "user",
'givenName': "abcdefghijklmnopqrstuvwxyz"[i % 26],
"roomNumber": "%sbc" % (n - i),
"carLicense": "后来经",
"employeeNumber": "%s%sx" % (abs(i * (99 - i)), '\n' * (i & 255)),
"accountExpires": "%s" % (10 ** 9 + 1000000 * i),
"msTSExpireDate4": "19%02d0101010000.0Z" % (i % 100),
"flags": str(i * (n - i)),
"serialNumber": "abc %s%s%s" % ('AaBb |-/'[i & 7],
' 3z}'[i & 3],
'"@'[i & 1],),
}
# _user_broken_attrs tests are broken due to problems outside
# of VLV.
_user_broken_attrs = {
# Sort doesn't look past a NUL byte.
"photo": "\x00%d" % (n - i),
"audio": "%sn octet string %s%s ♫♬\x00lalala" % ('Aa'[i & 1],
chr(i & 255), i),
"displayNamePrintable": "%d\x00%c" % (i, i & 255),
"adminDisplayName": "%d\x00b" % (n-i),
"title": "%d%sb" % (n - i, '\x00' * i),
"comment": "Favourite colour is %d" % (n % (i + 1)),
# Names that vary only in case. Windows returns
# equivalent addresses in the order they were put
# in ('a st', 'A st',...).
"street": "%s st" % (chr(65 | (i & 14) | ((i & 1) * 32))),
}
if attrs is not None:
user.update(attrs)
user['dn'] = "cn=%s,%s" % (user['cn'], self.ou)
if opts.skip_attr_regex:
match = re.compile(opts.skip_attr_regex).search
for k in user.keys():
if match(k):
del user[k]
self.users.append(user)
self.ldb.add(user)
return user
def setUp(self):
super(VLVTests, self).setUp()
self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb.domain_dn()
self.ou = "ou=vlv,%s" % self.base_dn
if opts.delete_in_setup:
try:
self.ldb.delete(self.ou, ['tree_delete:1'])
except ldb.LdbError, e:
print "tried deleting %s, got error %s" % (self.ou, e)
self.ldb.add({
"dn": self.ou,
"objectclass": "organizationalUnit"})
self.users = []
for i in range(N_ELEMENTS):
self.create_user(i, N_ELEMENTS)
attrs = self.users[0].keys()
self.binary_sorted_keys = ['audio',
'photo',
"msTSExpireDate4",
'serialNumber',
"displayNamePrintable"]
self.numeric_sorted_keys = ['flags',
'accountExpires']
self.timestamp_keys = ['msTSExpireDate4']
self.int64_keys = set(['accountExpires'])
self.locale_sorted_keys = [x for x in attrs if
x not in (self.binary_sorted_keys +
self.numeric_sorted_keys)]
# don't try spaces, etc in cn
self.delicate_keys = ['cn']
示例11: DsdbLockTestCase
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class DsdbLockTestCase(SamDBTestCase):
def test_db_lock1(self):
basedn = self.samdb.get_default_basedn()
(r1, w1) = os.pipe()
pid = os.fork()
if pid == 0:
# In the child, close the main DB, re-open just one DB
del(self.samdb)
gc.collect()
self.samdb = SamDB(session_info=self.session,
lp=self.lp)
self.samdb.transaction_start()
dn = "cn=test_db_lock_user,cn=users," + str(basedn)
self.samdb.add({
"dn": dn,
"objectclass": "user",
})
self.samdb.delete(dn)
# Obtain a write lock
self.samdb.transaction_prepare_commit()
os.write(w1, b"prepared")
time.sleep(2)
# Drop the write lock
self.samdb.transaction_cancel()
os._exit(0)
self.assertEqual(os.read(r1, 8), b"prepared")
start = time.time()
# We need to hold this iterator open to hold the all-record lock.
res = self.samdb.search_iterator()
# This should take at least 2 seconds because the transaction
# has a write lock on one backend db open
# Release the locks
for l in res:
pass
end = time.time()
self.assertGreater(end - start, 1.9)
(got_pid, status) = os.waitpid(pid, 0)
self.assertEqual(got_pid, pid)
self.assertTrue(os.WIFEXITED(status))
self.assertEqual(os.WEXITSTATUS(status), 0)
def test_db_lock2(self):
basedn = self.samdb.get_default_basedn()
(r1, w1) = os.pipe()
(r2, w2) = os.pipe()
pid = os.fork()
if pid == 0:
# In the child, close the main DB, re-open
del(self.samdb)
gc.collect()
self.samdb = SamDB(session_info=self.session,
lp=self.lp)
# We need to hold this iterator open to hold the all-record lock.
res = self.samdb.search_iterator()
os.write(w2, b"start")
if (os.read(r1, 7) != b"started"):
os._exit(1)
os.write(w2, b"add")
if (os.read(r1, 5) != b"added"):
os._exit(2)
# Wait 2 seconds to block prepare_commit() in the child.
os.write(w2, b"prepare")
time.sleep(2)
# Release the locks
for l in res:
pass
if (os.read(r1, 8) != b"prepared"):
os._exit(3)
os._exit(0)
# We can start the transaction during the search
# because both just grab the all-record read lock.
self.assertEqual(os.read(r2, 5), b"start")
self.samdb.transaction_start()
os.write(w1, b"started")
self.assertEqual(os.read(r2, 3), b"add")
dn = "cn=test_db_lock_user,cn=users," + str(basedn)
self.samdb.add({
"dn": dn,
#.........这里部分代码省略.........
示例12: UserTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
#.........这里部分代码省略.........
def _test_link_many_users_offset_1(self, n=BATCH_SIZE):
s = self.state.next_relinked_user
e = s + n
for i in range(s, e):
g = (i + 1) % N_GROUPS
self._link_user_and_group(i, g)
self.state.next_relinked_user = e
test_02_01_link_users_again_1000 = _test_link_many_users_offset_1
test_02_02_link_users_again_2000 = _test_link_many_users_offset_1
test_02_03_link_users_again_3000 = _test_link_many_users_offset_1
test_02_10_join_partially_linked_dc = _test_join
test_02_11_unindexed_search_partially_linked_dc = _test_unindexed_search
test_02_12_indexed_search_partially_linked_dc = _test_indexed_search
def _test_link_many_users_3_groups(self, n=BATCH_SIZE, groups=3):
s = self.state.next_linked_user_3
e = s + n
self.state.next_linked_user_3 = e
for i in range(s, e):
g = (i + 2) % groups
if g not in (i % N_GROUPS, (i + 1) % N_GROUPS):
self._link_user_and_group(i, g)
test_03_01_link_users_again_1000_few_groups = _test_link_many_users_3_groups
test_03_02_link_users_again_2000_few_groups = _test_link_many_users_3_groups
test_03_03_link_users_again_3000_few_groups = _test_link_many_users_3_groups
def _test_remove_links_0(self, n=BATCH_SIZE):
s = self.state.next_removed_link_0
e = s + n
self.state.next_removed_link_0 = e
for i in range(s, e):
g = i % N_GROUPS
self._unlink_user_and_group(i, g)
test_04_01_remove_some_links_1000 = _test_remove_links_0
test_04_02_remove_some_links_2000 = _test_remove_links_0
test_04_03_remove_some_links_3000 = _test_remove_links_0
# back to using _test_add_many_users
test_05_01_adding_users_after_links_4000 = _test_add_many_users
# reset the link count, to replace the original links
def test_06_01_relink_users_1000(self):
self.state.next_linked_user = 0
self._test_link_many_users()
test_06_02_link_users_2000 = _test_link_many_users
test_06_03_link_users_3000 = _test_link_many_users
test_06_04_link_users_4000 = _test_link_many_users
test_06_05_link_users_again_4000 = _test_link_many_users_offset_1
test_06_06_link_users_again_4000_few_groups = _test_link_many_users_3_groups
test_07_01_adding_users_after_links_5000 = _test_add_many_users
def _test_link_random_users_and_groups(self, n=BATCH_SIZE, groups=100):
self._prepare_n_groups(groups)
for i in range(n):
u = random.randrange(self.state.next_user_id)
g = random.randrange(groups)
try:
self._link_user_and_group(u, g)
except LdbError:
pass
test_08_01_link_random_users_100_groups = _test_link_random_users_and_groups
test_08_02_link_random_users_100_groups = _test_link_random_users_and_groups
test_10_01_unindexed_search_full_dc = _test_unindexed_search
test_10_02_indexed_search_full_dc = _test_indexed_search
test_11_02_join_full_dc = _test_join
def test_20_01_delete_50_groups(self):
for i in range(self.state.n_groups - 50, self.state.n_groups):
self.ldb.delete("cn=g%d,%s" % (i, self.ou_groups))
self.state.n_groups -= 50
def _test_delete_many_users(self, n=BATCH_SIZE):
e = self.state.next_user_id
s = max(0, e - n)
self.state.next_user_id = s
for i in range(s, e):
self.ldb.delete("cn=u%d,%s" % (i, self.ou_users))
test_21_01_delete_users_5000_lightly_linked = _test_delete_many_users
test_21_02_delete_users_4000_lightly_linked = _test_delete_many_users
test_21_03_delete_users_3000 = _test_delete_many_users
def test_22_01_delete_all_groups(self):
for i in range(self.state.n_groups):
self.ldb.delete("cn=g%d,%s" % (i, self.ou_groups))
self.state.n_groups = 0
test_23_01_delete_users_after_groups_2000 = _test_delete_many_users
test_23_00_delete_users_after_groups_1000 = _test_delete_many_users
test_24_02_join_after_cleanup = _test_join
示例13: DsdbTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class DsdbTests(TestCase):
def setUp(self):
super(DsdbTests, self).setUp()
self.lp = samba.tests.env_loadparm()
self.creds = Credentials()
self.creds.guess(self.lp)
self.session = system_session()
self.samdb = SamDB(session_info=self.session,
credentials=self.creds,
lp=self.lp)
# Create a test user
user_name = "dsdb-user-" + str(uuid.uuid4().hex[0:6])
user_pass = samba.generate_random_password(32, 32)
user_description = "Test user for dsdb test"
base_dn = self.samdb.domain_dn()
self.account_dn = "cn=" + user_name + ",cn=Users," + base_dn
self.samdb.newuser(username=user_name,
password=user_pass,
description=user_description)
# Cleanup (teardown)
self.addCleanup(delete_force, self.samdb, self.account_dn)
def test_get_oid_from_attrid(self):
oid = self.samdb.get_oid_from_attid(591614)
self.assertEquals(oid, "1.2.840.113556.1.4.1790")
def test_error_replpropertymetadata(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
ctr = repl.ctr
for o in ctr.array:
# Search for Description
if o.attid == 13:
old_version = o.version
o.version = o.version + 1
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
self.assertRaises(ldb.LdbError, self.samdb.modify, msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def test_error_replpropertymetadata_nochange(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
self.assertRaises(ldb.LdbError, self.samdb.modify, msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def test_error_replpropertymetadata_allow_sort(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
self.samdb.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0", "local_oid:1.3.6.1.4.1.7165.4.3.25:0"])
def test_twoatt_replpropertymetadata(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData", "uSNChanged"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
ctr = repl.ctr
for o in ctr.array:
# Search for Description
if o.attid == 13:
old_version = o.version
o.version = o.version + 1
o.local_usn = int(str(res[0]["uSNChanged"])) + 1
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
msg["description"] = ldb.MessageElement("new val", ldb.FLAG_MOD_REPLACE, "description")
self.assertRaises(ldb.LdbError, self.samdb.modify, msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def test_set_replpropertymetadata(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData", "uSNChanged"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
ctr = repl.ctr
for o in ctr.array:
#.........这里部分代码省略.........
示例14:
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
# Check if dns-HOSTNAME account exists and create it if required
try:
dn = 'samAccountName=dns-%s,CN=Principals' % names.hostname
msg = secretsdb.search(expression='(dn=%s)' % dn, attrs=['secret'])
dnssecret = msg[0]['secret'][0]
except Exception:
print "Adding dns-%s account" % names.hostname
try:
msg = samdb.search(base=names.domaindn, scope=samba.ldb.SCOPE_DEFAULT,
expression='(sAMAccountName=dns-%s)' % (names.hostname),
attrs=['clearTextPassword'])
if msg:
print "removing sAMAccountName=dns-%s" % (names.hostname)
dn = msg[0].dn
samdb.delete(dn)
except Exception:
print "exception while removing sAMAccountName=dns-%s" % (names.hostname)
pass
setup_add_ldif(secretsdb, setup_path("secrets_dns.ldif"), {
"REALM": names.realm,
"DNSDOMAIN": names.dnsdomain,
"DNS_KEYTAB": dns_keytab_path,
"DNSPASS_B64": b64encode(dnspass),
"HOSTNAME": names.hostname,
"DNSNAME" : '%s.%s' % (
names.netbiosname.lower(), names.dnsdomain.lower())
})
account_created = False
示例15: RodcTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import delete [as 别名]
class RodcTests(samba.tests.TestCase):
def setUp(self):
super(RodcTests, self).setUp()
self.samdb = SamDB(HOST, credentials=CREDS,
session_info=system_session(LP), lp=LP)
self.base_dn = self.samdb.domain_dn()
root = self.samdb.search(base='', scope=ldb.SCOPE_BASE,
attrs=['dsServiceName'])
self.service = root[0]['dsServiceName'][0]
self.tag = uuid.uuid4().hex
def test_add_replicated_objects(self):
for o in (
{
'dn': "ou=%s1,%s" % (self.tag, self.base_dn),
"objectclass": "organizationalUnit"
},
{
'dn': "cn=%s2,%s" % (self.tag, self.base_dn),
"objectclass": "user"
},
{
'dn': "cn=%s3,%s" % (self.tag, self.base_dn),
"objectclass": "group"
},
{
'dn': "cn=%s4,%s" % (self.tag, self.service),
"objectclass": "NTDSConnection",
'enabledConnection': 'TRUE',
'fromServer': self.base_dn,
'options': '0'
},
):
try:
self.samdb.add(o)
self.fail("Failed to fail to add %s" % o['dn'])
except ldb.LdbError as e:
(ecode, emsg) = e.args
if ecode != ldb.ERR_REFERRAL:
print(emsg)
self.fail("Adding %s: ldb error: %s %s, wanted referral" %
(o['dn'], ecode, emsg))
else:
m = re.search(r'(ldap://[^>]+)>', emsg)
if m is None:
self.fail("referral seems not to refer to anything")
address = m.group(1)
try:
tmpdb = SamDB(address, credentials=CREDS,
session_info=system_session(LP), lp=LP)
tmpdb.add(o)
tmpdb.delete(o['dn'])
except ldb.LdbError as e:
self.fail("couldn't modify referred location %s" %
address)
if address.lower().startswith(self.samdb.domain_dns_name()):
self.fail("referral address did not give a specific DC")
def test_modify_replicated_attributes(self):
# some timestamp ones
dn = 'CN=Guest,CN=Users,' + self.base_dn
value = 'hallooo'
for attr in ['carLicense', 'middleName']:
msg = ldb.Message()
msg.dn = ldb.Dn(self.samdb, dn)
msg[attr] = ldb.MessageElement(value,
ldb.FLAG_MOD_REPLACE,
attr)
try:
self.samdb.modify(msg)
self.fail("Failed to fail to modify %s %s" % (dn, attr))
except ldb.LdbError as e1:
(ecode, emsg) = e1.args
if ecode != ldb.ERR_REFERRAL:
self.fail("Failed to REFER when trying to modify %s %s" %
(dn, attr))
else:
m = re.search(r'(ldap://[^>]+)>', emsg)
if m is None:
self.fail("referral seems not to refer to anything")
address = m.group(1)
try:
tmpdb = SamDB(address, credentials=CREDS,
session_info=system_session(LP), lp=LP)
tmpdb.modify(msg)
except ldb.LdbError as e:
self.fail("couldn't modify referred location %s" %
address)
if address.lower().startswith(self.samdb.domain_dns_name()):
self.fail("referral address did not give a specific DC")
def test_modify_nonreplicated_attributes(self):
# some timestamp ones
#.........这里部分代码省略.........