本文整理汇总了Python中samba.samdb.SamDB.newuser方法的典型用法代码示例。如果您正苦于以下问题:Python SamDB.newuser方法的具体用法?Python SamDB.newuser怎么用?Python SamDB.newuser使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类samba.samdb.SamDB
的用法示例。
在下文中一共展示了SamDB.newuser方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
def run(self, username, password=None, credopts=None, sambaopts=None,
versionopts=None, H=None, must_change_at_next_login=False, random_password=False,
use_username_as_cn=False, userou=None, surname=None, given_name=None, initials=None,
profile_path=None, script_path=None, home_drive=None, home_directory=None,
job_title=None, department=None, company=None, description=None,
mail_address=None, internet_address=None, telephone_number=None, physical_delivery_office=None):
if random_password:
password = generate_random_password(128, 255)
while 1:
if password is not None and password is not '':
break
password = getpass("New Password: ")
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
try:
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
samdb.newuser(username, password,
force_password_change_at_next_login_req=must_change_at_next_login,
useusernameascn=use_username_as_cn, userou=userou, surname=surname, givenname=given_name, initials=initials,
profilepath=profile_path, homedrive=home_drive, scriptpath=script_path, homedirectory=home_directory,
jobtitle=job_title, department=department, company=company, description=description,
mailaddress=mail_address, internetaddress=internet_address,
telephonenumber=telephone_number, physicaldeliveryoffice=physical_delivery_office)
except Exception, e:
raise CommandError("Failed to add user '%s': " % username, e)
示例2: run
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
def run(self, username, password=None, credopts=None, sambaopts=None,
versionopts=None, H=None, must_change_at_next_login=False,
random_password=False, use_username_as_cn=False, userou=None,
surname=None, given_name=None, initials=None, profile_path=None,
script_path=None, home_drive=None, home_directory=None,
job_title=None, department=None, company=None, description=None,
mail_address=None, internet_address=None, telephone_number=None,
physical_delivery_office=None, rfc2307_from_nss=False,
uid=None, uid_number=None, gid_number=None, gecos=None, login_shell=None):
if random_password:
password = generate_random_password(128, 255)
while True:
if password is not None and password is not '':
break
password = getpass("New Password: ")
passwordverify = getpass("Retype Password: ")
if not password == passwordverify:
password = None
self.outf.write("Sorry, passwords do not match.\n")
if rfc2307_from_nss:
pwent = pwd.getpwnam(username)
if uid is None:
uid = username
if uid_number is None:
uid_number = pwent[2]
if gid_number is None:
gid_number = pwent[3]
if gecos is None:
gecos = pwent[4]
if login_shell is None:
login_shell = pwent[6]
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
if uid_number or gid_number:
if not lp.get("idmap_ldb:use rfc2307"):
self.outf.write("You are setting a Unix/RFC2307 UID or GID. You may want to set 'idmap_ldb:use rfc2307 = Yes' to use those attributes for XID/SID-mapping.\n")
try:
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
samdb.newuser(username, password, force_password_change_at_next_login_req=must_change_at_next_login,
useusernameascn=use_username_as_cn, userou=userou, surname=surname, givenname=given_name, initials=initials,
profilepath=profile_path, homedrive=home_drive, scriptpath=script_path, homedirectory=home_directory,
jobtitle=job_title, department=department, company=company, description=description,
mailaddress=mail_address, internetaddress=internet_address,
telephonenumber=telephone_number, physicaldeliveryoffice=physical_delivery_office,
uid=uid, uidnumber=uid_number, gidnumber=gid_number, gecos=gecos, loginshell=login_shell)
except Exception, e:
raise CommandError("Failed to add user '%s': " % username, e)
示例3: test_offline_manual_seized_ridalloc_add_user_as_admin
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
def test_offline_manual_seized_ridalloc_add_user_as_admin(self):
"""Peform the same actions as test_offline_samba_tool_seized_ridalloc,
but do not create the RID set. Confirm that user-add correctly creates
the RID Set."""
fsmo_dn = ldb.Dn(self.ldb_dc1, "CN=RID Manager$,CN=System," + self.ldb_dc1.domain_dn())
(fsmo_owner, fsmo_not_owner) = self._determine_fSMORoleOwner(fsmo_dn)
targetdir = self._test_join(fsmo_not_owner['dns_name'], "RIDALLOCTEST4")
try:
# Connect to the database
ldb_url = "tdb://%s" % os.path.join(targetdir, "private/sam.ldb")
lp = self.get_loadparm()
new_ldb = SamDB(ldb_url, credentials=self.get_credentials(),
session_info=admin_session(lp, self.ldb_dc1.get_domain_sid()), lp=lp)
serviceName = new_ldb.get_dsServiceName()
m = ldb.Message()
m.dn = fsmo_dn
m["fSMORoleOwner"] = ldb.MessageElement(serviceName,
ldb.FLAG_MOD_REPLACE,
"fSMORoleOwner")
new_ldb.modify(m)
# 1. Get server name
res = new_ldb.search(base=ldb.Dn(new_ldb, new_ldb.get_serverName()),
scope=ldb.SCOPE_BASE, attrs=["serverReference"])
# 2. Get server reference
server_ref_dn = ldb.Dn(new_ldb, res[0]['serverReference'][0])
# Assert that no RID Set has been set
res = new_ldb.search(base=server_ref_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])
self.assertFalse("rIDSetReferences" in res[0])
smbconf = os.path.join(targetdir, "etc/smb.conf")
# Create a user to allocate a RID Set for itself (the RID master)
new_ldb.newuser("ridalloctestuser", "[email protected]!")
# 3. Assert we get the RID Set
res = new_ldb.search(base=server_ref_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])
self.assertTrue("rIDSetReferences" in res[0])
finally:
self._test_force_demote(fsmo_not_owner['dns_name'], "RIDALLOCTEST4")
shutil.rmtree(targetdir, ignore_errors=True)
示例4: run
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
def run(self, username, password=None, credopts=None, sambaopts=None,
versionopts=None, H=None, unixname=None,
must_change_at_next_login=None):
if password is None:
password = getpass("New Password: ")
if unixname is None:
unixname = username
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
if H is not None:
url = H
else:
url = lp.get("sam database")
samdb = SamDB(url=url, session_info=system_session(), credentials=creds,
lp=lp)
samdb.newuser(username, unixname, password,
force_password_change_at_next_login_req=must_change_at_next_login)
示例5: RodcCmdTestCase
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
class RodcCmdTestCase(SambaToolCmdTest):
def setUp(self):
super(RodcCmdTestCase, self).setUp()
self.lp = samba.param.LoadParm()
self.lp.load(os.environ["SMB_CONF_PATH"])
self.creds = Credentials()
self.creds.set_username(os.environ["DC_USERNAME"])
self.creds.set_password(os.environ["DC_PASSWORD"])
self.creds.guess(self.lp)
self.session = system_session()
self.ldb = SamDB("ldap://" + os.environ["DC_SERVER"],
session_info=self.session, credentials=self.creds,lp=self.lp)
self.base_dn = self.ldb.domain_dn()
self.ldb.newuser("sambatool1", "[email protected]")
self.ldb.newuser("sambatool2", "2wsxCDE#")
self.ldb.newuser("sambatool3", "3edcVFR$")
self.ldb.newuser("sambatool4", "4rfvBGT%")
self.ldb.newuser("sambatool5", "5tjbNHY*")
self.ldb.newuser("sambatool6", "6yknMJU*")
self.ldb.add_remove_group_members("Allowed RODC Password Replication Group",
["sambatool1", "sambatool2", "sambatool3",
"sambatool4", "sambatool5"],
add_members_operation=True)
def tearDown(self):
super(RodcCmdTestCase, self).tearDown()
self.ldb.deleteuser("sambatool1")
self.ldb.deleteuser("sambatool2")
self.ldb.deleteuser("sambatool3")
self.ldb.deleteuser("sambatool4")
self.ldb.deleteuser("sambatool5")
self.ldb.deleteuser("sambatool6")
(result, out, err) = self.runsubcmd("drs", "replicate", "--local", "unused",
os.environ["DC_SERVER"], self.base_dn)
def test_single_by_account_name(self):
(result, out, err) = self.runsubcmd("rodc", "preload", "sambatool1",
"--server", os.environ["DC_SERVER"])
self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
self.assertEqual(out, "Replicating DN CN=sambatool1,CN=Users,%s\n" % self.base_dn)
self.assertEqual(err, "")
def test_single_by_dn(self):
(result, out, err) = self.runsubcmd("rodc", "preload", "cn=sambatool2,cn=users,%s" % self.base_dn,
"--server", os.environ["DC_SERVER"])
self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
self.assertEqual(out, "Replicating DN CN=sambatool2,CN=Users,%s\n" % self.base_dn)
def test_multi_by_account_name(self):
(result, out, err) = self.runsubcmd("rodc", "preload", "sambatool1", "sambatool2",
"--server", os.environ["DC_SERVER"])
self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
self.assertEqual(out, "Replicating DN CN=sambatool1,CN=Users,%s\nReplicating DN CN=sambatool2,CN=Users,%s\n" % (self.base_dn, self.base_dn))
def test_multi_by_dn(self):
(result, out, err) = self.runsubcmd("rodc", "preload", "cn=sambatool3,cn=users,%s" % self.base_dn, "cn=sambatool4,cn=users,%s" % self.base_dn,
"--server", os.environ["DC_SERVER"])
self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
self.assertEqual(out, "Replicating DN CN=sambatool3,CN=Users,%s\nReplicating DN CN=sambatool4,CN=Users,%s\n" % (self.base_dn, self.base_dn))
def test_multi_in_file(self):
tempf = os.path.join(self.tempdir, "accountlist")
open(tempf, 'w').write("sambatool1\nsambatool2")
(result, out, err) = self.runsubcmd("rodc", "preload", "--file", tempf,
"--server", os.environ["DC_SERVER"])
self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
self.assertEqual(out, "Replicating DN CN=sambatool1,CN=Users,%s\nReplicating DN CN=sambatool2,CN=Users,%s\n" % (self.base_dn, self.base_dn))
os.unlink(tempf)
def test_multi_with_missing_name_success(self):
(result, out, err) = self.runsubcmd("rodc", "preload",
"nonexistentuser1", "sambatool5",
"nonexistentuser2",
"--server", os.environ["DC_SERVER"],
"--ignore-errors")
self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
self.assertTrue(out.startswith("Replicating DN CN=sambatool5,CN=Users,%s\n"
% self.base_dn))
def test_multi_with_missing_name_failure(self):
(result, out, err) = self.runsubcmd("rodc", "preload",
"nonexistentuser1", "sambatool5",
"nonexistentuser2",
"--server", os.environ["DC_SERVER"])
self.assertCmdFail(result, "ensuring rodc prefetch quit on missing user")
def test_multi_without_group_success(self):
(result, out, err) = self.runsubcmd("rodc", "preload",
"sambatool6", "sambatool5",
"--server", os.environ["DC_SERVER"],
"--ignore-errors")
self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
self.assertTrue(out.startswith("Replicating DN CN=sambatool6,CN=Users,%s\n"
"Replicating DN CN=sambatool5,CN=Users,%s\n"
% (self.base_dn, self.base_dn)))
#.........这里部分代码省略.........
示例6: DynamicTokenTest
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
class DynamicTokenTest(samba.tests.TestCase):
def get_creds(self, target_username, target_password):
creds_tmp = Credentials()
creds_tmp.set_username(target_username)
creds_tmp.set_password(target_password)
creds_tmp.set_domain(creds.get_domain())
creds_tmp.set_realm(creds.get_realm())
creds_tmp.set_workstation(creds.get_workstation())
creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
| gensec.FEATURE_SEAL)
return creds_tmp
def get_ldb_connection(self, target_username, target_password):
creds_tmp = self.get_creds(target_username, target_password)
ldb_target = SamDB(url=url, credentials=creds_tmp, lp=lp)
return ldb_target
def setUp(self):
super(DynamicTokenTest, self).setUp()
self.admin_ldb = SamDB(url, credentials=creds, session_info=system_session(lp), lp=lp)
self.base_dn = self.admin_ldb.domain_dn()
self.test_user = "tokengroups_user1"
self.test_user_pass = "[email protected]"
self.admin_ldb.newuser(self.test_user, self.test_user_pass)
self.test_group0 = "tokengroups_group0"
self.admin_ldb.newgroup(self.test_group0, grouptype=dsdb.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP)
res = self.admin_ldb.search(base="cn=%s,cn=users,%s" % (self.test_group0, self.base_dn),
attrs=["objectSid"], scope=ldb.SCOPE_BASE)
self.test_group0_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group0, [self.test_user],
add_members_operation=True)
self.test_group1 = "tokengroups_group1"
self.admin_ldb.newgroup(self.test_group1, grouptype=dsdb.GTYPE_SECURITY_GLOBAL_GROUP)
res = self.admin_ldb.search(base="cn=%s,cn=users,%s" % (self.test_group1, self.base_dn),
attrs=["objectSid"], scope=ldb.SCOPE_BASE)
self.test_group1_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group1, [self.test_user],
add_members_operation=True)
self.test_group2 = "tokengroups_group2"
self.admin_ldb.newgroup(self.test_group2, grouptype=dsdb.GTYPE_SECURITY_UNIVERSAL_GROUP)
res = self.admin_ldb.search(base="cn=%s,cn=users,%s" % (self.test_group2, self.base_dn),
attrs=["objectSid"], scope=ldb.SCOPE_BASE)
self.test_group2_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group2, [self.test_user],
add_members_operation=True)
self.test_group3 = "tokengroups_group3"
self.admin_ldb.newgroup(self.test_group3, grouptype=dsdb.GTYPE_SECURITY_UNIVERSAL_GROUP)
res = self.admin_ldb.search(base="cn=%s,cn=users,%s" % (self.test_group3, self.base_dn),
attrs=["objectSid"], scope=ldb.SCOPE_BASE)
self.test_group3_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group3, [self.test_group1],
add_members_operation=True)
self.test_group4 = "tokengroups_group4"
self.admin_ldb.newgroup(self.test_group4, grouptype=dsdb.GTYPE_SECURITY_UNIVERSAL_GROUP)
res = self.admin_ldb.search(base="cn=%s,cn=users,%s" % (self.test_group4, self.base_dn),
attrs=["objectSid"], scope=ldb.SCOPE_BASE)
self.test_group4_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group4, [self.test_group3],
add_members_operation=True)
self.test_group5 = "tokengroups_group5"
self.admin_ldb.newgroup(self.test_group5, grouptype=dsdb.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP)
res = self.admin_ldb.search(base="cn=%s,cn=users,%s" % (self.test_group5, self.base_dn),
attrs=["objectSid"], scope=ldb.SCOPE_BASE)
self.test_group5_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group5, [self.test_group4],
add_members_operation=True)
self.test_group6 = "tokengroups_group6"
self.admin_ldb.newgroup(self.test_group6, grouptype=dsdb.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP)
res = self.admin_ldb.search(base="cn=%s,cn=users,%s" % (self.test_group6, self.base_dn),
attrs=["objectSid"], scope=ldb.SCOPE_BASE)
self.test_group6_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group6, [self.test_user],
add_members_operation=True)
self.ldb = self.get_ldb_connection(self.test_user, self.test_user_pass)
res = self.ldb.search("", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
self.assertEquals(len(res), 1)
#.........这里部分代码省略.........
示例7: str
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
#.........这里部分代码省略.........
auth_success = False
_isLastErrorAvailable = False
LastErrorStr = ""
LastErrorNumber = 0
RootDSE = ""
DnsDomain = Realm
schemaNamingContext = ""
server_address = "127.0.0.1"
SambaVersion = version
def __init__(self, username, password):
self.creds = credentials.Credentials()
self.creds.set_username(username)
self.creds.set_password(password)
self.creds.set_domain(self.WorkGroup)
self.creds.set_workstation("")
self.samdb = SamDB(
url="ldap://%s" % self.server_address, session_info=system_session(), credentials=self.creds, lp=self.lp
)
self.samrpipe = samr.samr("ncalrpc:%s" % self.server_address, self.lp, credentials=self.creds)
self.connect_handle = self.samrpipe.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED)
self._GetDomainNames()
self._SetCurrentDomain(0)
def _SetCurrentDomain(self, domain_index):
self.domain = self.sam_domains[domain_index]
self.domain_sid = self.samrpipe.LookupDomain(self.connect_handle, self.domain[1])
self.domain_handle = self.samrpipe.OpenDomain(
self.connect_handle, security.SEC_FLAG_MAXIMUM_ALLOWED, self.domain_sid
)
self.creds.set_domain(self.domain_name_list[domain_index])
def _GetDomainNames(self):
if self.samrpipe == None:
return None # not connected
self.domain_name_list = []
self.sam_domains = self.toArray(self.samrpipe.EnumDomains(self.connect_handle, 0, -1))
for (rid, domain_name) in self.sam_domains:
self.domain_name_list.append(self.GetLsaString(domain_name))
return self.domain_name_list
def GetUser(self, rid=None, user=None):
all_users = self.ListUsers()
for user in all_users:
if rid:
if user[0]["rid"] == int(rid):
return user
if user:
if user[0]["samaccountname"] == user:
return user
def ListUsers(self, to_json=False, get_user="All"):
attrs = ["samaccountname", "mail", "description", "displayname"]
lista = []
rest0 = ""
expression = "(&(objectClass=user)(userAccountControl:%s:=%u))" % (
ldb.OID_COMPARATOR_AND,
dsdb.UF_NORMAL_ACCOUNT,
)
if get_user != "All":
expression = "samAccountName=%s" % (get_user)
res = self.samdb.search(self.samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE, expression=expression, attrs=attrs)
for i in attrs:
rest0 += '"%s": msg.get("%s",idx=0),' % (i, i)
rids = self.GetRid()
for msg in res:
user = msg.get("samaccountname", idx=0)
param = rids[user][0]
if (user != "krbtgt") & (user[:4] != "dns-"):
lista.append(
eval(
'{ "%s": [{ "rid": %s, "account_disabled": %s, %s }] }'
% (user, param["rid"], param["account_disabled"], rest0)
)
)
if to_json:
return json.dumps(lista, indent=3)
simples = []
for i in range(len(lista)):
for user in lista[i]:
simples.append(lista[i][user])
return simples
def AddUser(self, user, passw, mailaddress=None):
self.user = str(user)
self.passw = str(passw)
self.mail = str(mailaddress)
try:
res = self.samdb.newuser(self.user, self.passw, mailaddress=self.mail)
except Exception, e:
print("Failed to add user '%s': %s" % (self.user, e))
return False
return True
示例8: test_rid_set_dbcheck_after_seize
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
def test_rid_set_dbcheck_after_seize(self):
"""Perform a join against the RID manager and assert we have a RID Set.
We seize the RID master role, then using dbcheck, we assert that we can
detect out of range users (and then bump the RID set as required)."""
fsmo_dn = ldb.Dn(self.ldb_dc1, "CN=RID Manager$,CN=System," + self.ldb_dc1.domain_dn())
(fsmo_owner, fsmo_not_owner) = self._determine_fSMORoleOwner(fsmo_dn)
targetdir = self._test_join(fsmo_owner['dns_name'], "RIDALLOCTEST7")
try:
# Connect to the database
ldb_url = "tdb://%s" % os.path.join(targetdir, "private/sam.ldb")
smbconf = os.path.join(targetdir, "etc/smb.conf")
lp = self.get_loadparm()
new_ldb = SamDB(ldb_url, credentials=self.get_credentials(),
session_info=system_session(lp), lp=lp)
# 1. Get server name
res = new_ldb.search(base=ldb.Dn(new_ldb, new_ldb.get_serverName()),
scope=ldb.SCOPE_BASE, attrs=["serverReference"])
# 2. Get server reference
server_ref_dn = ldb.Dn(new_ldb, res[0]['serverReference'][0])
# 3. Assert we get the RID Set
res = new_ldb.search(base=server_ref_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])
self.assertTrue("rIDSetReferences" in res[0])
rid_set_dn = ldb.Dn(new_ldb, res[0]["rIDSetReferences"][0])
# 4. Seize the RID Manager role
(result, out, err) = self.runsubcmd("fsmo", "seize", "--role", "rid", "-H", ldb_url, "-s", smbconf, "--force")
self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages")
# 5. Add a new user (triggers RID set work)
new_ldb.newuser("ridalloctestuser", "[email protected]!")
# 6. Now fetch the RID SET
rid_set_res = new_ldb.search(base=rid_set_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDNextRid',
'rIDAllocationPool'])
next_pool = int(rid_set_res[0]["rIDAllocationPool"][0])
last_rid = (0xFFFFFFFF00000000 & next_pool) >> 32
# 7. Add user above the ridNextRid and at almost the end of the range.
#
m = ldb.Message()
m.dn = ldb.Dn(new_ldb, "CN=ridsettestuser2,CN=Users")
m.dn.add_base(new_ldb.get_default_basedn())
m['objectClass'] = ldb.MessageElement('user', ldb.FLAG_MOD_ADD, 'objectClass')
m['objectSid'] = ldb.MessageElement(ndr_pack(security.dom_sid(str(new_ldb.get_domain_sid()) + "-%d" % (last_rid - 3))),
ldb.FLAG_MOD_ADD,
'objectSid')
new_ldb.add(m, controls=["relax:0"])
# 8. Add user above the ridNextRid and at the end of the range
m = ldb.Message()
m.dn = ldb.Dn(new_ldb, "CN=ridsettestuser3,CN=Users")
m.dn.add_base(new_ldb.get_default_basedn())
m['objectClass'] = ldb.MessageElement('user', ldb.FLAG_MOD_ADD, 'objectClass')
m['objectSid'] = ldb.MessageElement(ndr_pack(security.dom_sid(str(new_ldb.get_domain_sid()) + "-%d" % last_rid)),
ldb.FLAG_MOD_ADD,
'objectSid')
new_ldb.add(m, controls=["relax:0"])
chk = dbcheck(new_ldb, verbose=False, fix=True, yes=True, quiet=True)
# Should have fixed two errors (wrong ridNextRid)
self.assertEqual(chk.check_database(DN=rid_set_dn, scope=ldb.SCOPE_BASE), 2)
# 9. Assert we get didn't show any other errors
chk = dbcheck(new_ldb, verbose=False, fix=False, quiet=True)
# 10. Add another user (checks RID rollover)
# We have seized the role, so we can do that.
new_ldb.newuser("ridalloctestuser3", "[email protected]!")
rid_set_res = new_ldb.search(base=rid_set_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDNextRid',
'rIDAllocationPool'])
next_pool = int(rid_set_res[0]["rIDAllocationPool"][0])
self.assertNotEqual(last_rid, (0xFFFFFFFF00000000 & next_pool) >> 32, "rid pool should have changed")
finally:
self._test_force_demote(fsmo_owner['dns_name'], "RIDALLOCTEST7")
shutil.rmtree(targetdir, ignore_errors=True)
示例9: test_rid_set_dbcheck
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
def test_rid_set_dbcheck(self):
"""Perform a join against the RID manager and assert we have a RID Set.
Using dbcheck, we assert that we can detect out of range users."""
fsmo_dn = ldb.Dn(self.ldb_dc1, "CN=RID Manager$,CN=System," + self.ldb_dc1.domain_dn())
(fsmo_owner, fsmo_not_owner) = self._determine_fSMORoleOwner(fsmo_dn)
targetdir = self._test_join(fsmo_owner['dns_name'], "RIDALLOCTEST6")
try:
# Connect to the database
ldb_url = "tdb://%s" % os.path.join(targetdir, "private/sam.ldb")
smbconf = os.path.join(targetdir, "etc/smb.conf")
lp = self.get_loadparm()
new_ldb = SamDB(ldb_url, credentials=self.get_credentials(),
session_info=system_session(lp), lp=lp)
# 1. Get server name
res = new_ldb.search(base=ldb.Dn(new_ldb, new_ldb.get_serverName()),
scope=ldb.SCOPE_BASE, attrs=["serverReference"])
# 2. Get server reference
server_ref_dn = ldb.Dn(new_ldb, res[0]['serverReference'][0])
# 3. Assert we get the RID Set
res = new_ldb.search(base=server_ref_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])
self.assertTrue("rIDSetReferences" in res[0])
rid_set_dn = ldb.Dn(new_ldb, res[0]["rIDSetReferences"][0])
# 4. Add a new user (triggers RID set work)
new_ldb.newuser("ridalloctestuser", "[email protected]!")
# 5. Now fetch the RID SET
rid_set_res = new_ldb.search(base=rid_set_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDNextRid',
'rIDAllocationPool'])
next_pool = int(rid_set_res[0]["rIDAllocationPool"][0])
last_rid = (0xFFFFFFFF00000000 & next_pool) >> 32
# 6. Add user above the ridNextRid and at mid-range.
#
# We can do this with safety because this is an offline DB that will be
# destroyed.
m = ldb.Message()
m.dn = ldb.Dn(new_ldb, "CN=ridsettestuser1,CN=Users")
m.dn.add_base(new_ldb.get_default_basedn())
m['objectClass'] = ldb.MessageElement('user', ldb.FLAG_MOD_ADD, 'objectClass')
m['objectSid'] = ldb.MessageElement(ndr_pack(security.dom_sid(str(new_ldb.get_domain_sid()) + "-%d" % (last_rid - 10))),
ldb.FLAG_MOD_ADD,
'objectSid')
new_ldb.add(m, controls=["relax:0"])
# 7. Check the RID Set
chk = dbcheck(new_ldb, verbose=False, fix=True, yes=True, quiet=True)
# Should have one error (wrong rIDNextRID)
self.assertEqual(chk.check_database(DN=rid_set_dn, scope=ldb.SCOPE_BASE), 1)
# 8. Assert we get didn't show any other errors
chk = dbcheck(new_ldb, verbose=False, fix=False, quiet=True)
rid_set_res = new_ldb.search(base=rid_set_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDNextRid',
'rIDAllocationPool'])
last_allocated_rid = int(rid_set_res[0]["rIDNextRid"][0])
self.assertEquals(last_allocated_rid, last_rid - 10)
# 9. Assert that the range wasn't thrown away
next_pool = int(rid_set_res[0]["rIDAllocationPool"][0])
self.assertEqual(last_rid, (0xFFFFFFFF00000000 & next_pool) >> 32, "rid pool should have changed")
finally:
self._test_force_demote(fsmo_owner['dns_name'], "RIDALLOCTEST6")
shutil.rmtree(targetdir, ignore_errors=True)
示例10: run
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
def run(self, username, password=None, credopts=None, sambaopts=None,
versionopts=None, H=None, must_change_at_next_login=False,
random_password=False, use_username_as_cn=False, userou=None,
surname=None, given_name=None, initials=None, profile_path=None,
script_path=None, home_drive=None, home_directory=None,
job_title=None, department=None, company=None, description=None,
mail_address=None, internet_address=None, telephone_number=None,
physical_delivery_office=None, rfc2307_from_nss=False,
nis_domain=None, unix_home=None, uid=None, uid_number=None,
gid_number=None, gecos=None, login_shell=None,
smartcard_required=False):
if smartcard_required:
if password is not None and password is not '':
raise CommandError('It is not allowed to specifiy '
'--newpassword '
'together with --smartcard-required.')
if must_change_at_next_login:
raise CommandError('It is not allowed to specifiy '
'--must-change-at-next-login '
'together with --smartcard-required.')
if random_password and not smartcard_required:
password = generate_random_password(128, 255)
while True:
if smartcard_required:
break
if password is not None and password is not '':
break
password = getpass("New Password: ")
passwordverify = getpass("Retype Password: ")
if not password == passwordverify:
password = None
self.outf.write("Sorry, passwords do not match.\n")
if rfc2307_from_nss:
pwent = pwd.getpwnam(username)
if uid is None:
uid = username
if uid_number is None:
uid_number = pwent[2]
if gid_number is None:
gid_number = pwent[3]
if gecos is None:
gecos = pwent[4]
if login_shell is None:
login_shell = pwent[6]
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
if uid_number or gid_number:
if not lp.get("idmap_ldb:use rfc2307"):
self.outf.write("You are setting a Unix/RFC2307 UID or GID. You may want to set 'idmap_ldb:use rfc2307 = Yes' to use those attributes for XID/SID-mapping.\n")
if nis_domain is not None:
if None in (uid_number, login_shell, unix_home, gid_number):
raise CommandError('Missing parameters. To enable NIS features, '
'the following options have to be given: '
'--nis-domain=, --uidNumber=, --login-shell='
', --unix-home=, --gid-number= Operation '
'cancelled.')
try:
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
samdb.newuser(username, password, force_password_change_at_next_login_req=must_change_at_next_login,
useusernameascn=use_username_as_cn, userou=userou, surname=surname, givenname=given_name, initials=initials,
profilepath=profile_path, homedrive=home_drive, scriptpath=script_path, homedirectory=home_directory,
jobtitle=job_title, department=department, company=company, description=description,
mailaddress=mail_address, internetaddress=internet_address,
telephonenumber=telephone_number, physicaldeliveryoffice=physical_delivery_office,
nisdomain=nis_domain, unixhome=unix_home, uid=uid,
uidnumber=uid_number, gidnumber=gid_number,
gecos=gecos, loginshell=login_shell,
smartcard_required=smartcard_required)
except Exception, e:
raise CommandError("Failed to add user '%s': " % username, e)
示例11: UserAccountControlTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
class UserAccountControlTests(samba.tests.TestCase):
def add_computer_ldap(self, computername, others=None, samdb=None):
if samdb is None:
samdb = self.samdb
dn = "CN=%s,OU=test_computer_ou1,%s" % (computername, self.base_dn)
domainname = ldb.Dn(self.samdb, self.samdb.domain_dn()).canonical_str().replace("/", "")
samaccountname = "%s$" % computername
dnshostname = "%s.%s" % (computername, domainname)
msg_dict = {
"dn": dn,
"objectclass": "computer"}
if others is not None:
msg_dict = dict(msg_dict.items() + others.items())
msg = ldb.Message.from_dict(self.samdb, msg_dict )
msg["sAMAccountName"] = samaccountname
print "Adding computer account %s" % computername
samdb.add(msg)
def get_creds(self, target_username, target_password):
creds_tmp = Credentials()
creds_tmp.set_username(target_username)
creds_tmp.set_password(target_password)
creds_tmp.set_domain(creds.get_domain())
creds_tmp.set_realm(creds.get_realm())
creds_tmp.set_workstation(creds.get_workstation())
creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
| gensec.FEATURE_SEAL)
creds_tmp.set_kerberos_state(DONT_USE_KERBEROS) # kinit is too expensive to use in a tight loop
return creds_tmp
def setUp(self):
super(UserAccountControlTests, self).setUp()
self.admin_creds = creds
self.admin_samdb = SamDB(url=ldaphost,
session_info=system_session(),
credentials=self.admin_creds, lp=lp)
self.unpriv_user = "testuser1"
self.unpriv_user_pw = "[email protected]"
self.unpriv_creds = self.get_creds(self.unpriv_user, self.unpriv_user_pw)
self.admin_samdb.newuser(self.unpriv_user, self.unpriv_user_pw)
res = self.admin_samdb.search("CN=%s,CN=Users,%s" % (self.unpriv_user, self.admin_samdb.domain_dn()),
scope=SCOPE_BASE,
attrs=["objectSid"])
self.assertEqual(1, len(res))
self.unpriv_user_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
self.unpriv_user_dn = res[0].dn
self.samdb = SamDB(url=ldaphost, credentials=self.unpriv_creds, lp=lp)
self.domain_sid = security.dom_sid(self.samdb.get_domain_sid())
self.base_dn = self.samdb.domain_dn()
self.samr = samr.samr("ncacn_ip_tcp:%s[sign]" % host, lp, self.unpriv_creds)
self.samr_handle = self.samr.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED)
self.samr_domain = self.samr.OpenDomain(self.samr_handle, security.SEC_FLAG_MAXIMUM_ALLOWED, self.domain_sid)
self.sd_utils = sd_utils.SDUtils(self.admin_samdb)
self.admin_samdb.create_ou("OU=test_computer_ou1," + self.base_dn)
self.unpriv_user_sid = self.sd_utils.get_object_sid(self.unpriv_user_dn)
mod = "(OA;;CC;bf967a86-0de6-11d0-a285-00aa003049e2;;%s)" % str(self.unpriv_user_sid)
old_sd = self.sd_utils.read_sd_on_dn("OU=test_computer_ou1," + self.base_dn)
self.sd_utils.dacl_add_ace("OU=test_computer_ou1," + self.base_dn, mod)
self.add_computer_ldap("testcomputer-t")
self.sd_utils.modify_sd_on_dn("OU=test_computer_ou1," + self.base_dn, old_sd)
self.computernames = ["testcomputer-0"]
# Get the SD of the template account, then force it to match
# what we expect for SeMachineAccountPrivilege accounts, so we
# can confirm we created the accounts correctly
self.sd_reference_cc = self.sd_utils.read_sd_on_dn("CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
self.sd_reference_modify = self.sd_utils.read_sd_on_dn("CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
for ace in self.sd_reference_modify.dacl.aces:
if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED and ace.trustee == self.unpriv_user_sid:
ace.access_mask = ace.access_mask | security.SEC_ADS_SELF_WRITE | security.SEC_ADS_WRITE_PROP
# Now reconnect without domain admin rights
self.samdb = SamDB(url=ldaphost, credentials=self.unpriv_creds, lp=lp)
def tearDown(self):
super(UserAccountControlTests, self).tearDown()
for computername in self.computernames:
delete_force(self.admin_samdb, "CN=%s,OU=test_computer_ou1,%s" % (computername, self.base_dn))
delete_force(self.admin_samdb, "CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
delete_force(self.admin_samdb, "OU=test_computer_ou1,%s" % (self.base_dn))
delete_force(self.admin_samdb, "CN=%s,CN=Users,%s" % (self.unpriv_user, self.base_dn))
def test_add_computer_sd_cc(self):
user_sid = self.sd_utils.get_object_sid(self.unpriv_user_dn)
#.........这里部分代码省略.........
示例12: UserAccountControlTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
class UserAccountControlTests(samba.tests.TestCase):
def add_computer_ldap(self, computername, others=None, samdb=None):
if samdb is None:
samdb = self.samdb
dn = "CN=%s,OU=test_computer_ou1,%s" % (computername, self.base_dn)
domainname = ldb.Dn(self.samdb, self.samdb.domain_dn()).canonical_str().replace("/", "")
samaccountname = "%s$" % computername
dnshostname = "%s.%s" % (computername, domainname)
msg_dict = {
"dn": dn,
"objectclass": "computer"}
if others is not None:
msg_dict = dict(msg_dict.items() + others.items())
msg = ldb.Message.from_dict(self.samdb, msg_dict )
msg["sAMAccountName"] = samaccountname
print("Adding computer account %s" % computername)
samdb.add(msg)
def get_creds(self, target_username, target_password):
creds_tmp = Credentials()
creds_tmp.set_username(target_username)
creds_tmp.set_password(target_password)
creds_tmp.set_domain(creds.get_domain())
creds_tmp.set_realm(creds.get_realm())
creds_tmp.set_workstation(creds.get_workstation())
creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
| gensec.FEATURE_SEAL)
creds_tmp.set_kerberos_state(DONT_USE_KERBEROS) # kinit is too expensive to use in a tight loop
return creds_tmp
def setUp(self):
super(UserAccountControlTests, self).setUp()
self.admin_creds = creds
self.admin_samdb = SamDB(url=ldaphost,
session_info=system_session(),
credentials=self.admin_creds, lp=lp)
self.domain_sid = security.dom_sid(self.admin_samdb.get_domain_sid())
self.base_dn = self.admin_samdb.domain_dn()
self.unpriv_user = "testuser1"
self.unpriv_user_pw = "[email protected]"
self.unpriv_creds = self.get_creds(self.unpriv_user, self.unpriv_user_pw)
delete_force(self.admin_samdb, "CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
delete_force(self.admin_samdb, "OU=test_computer_ou1,%s" % (self.base_dn))
delete_force(self.admin_samdb, "CN=%s,CN=Users,%s" % (self.unpriv_user, self.base_dn))
self.admin_samdb.newuser(self.unpriv_user, self.unpriv_user_pw)
res = self.admin_samdb.search("CN=%s,CN=Users,%s" % (self.unpriv_user, self.admin_samdb.domain_dn()),
scope=SCOPE_BASE,
attrs=["objectSid"])
self.assertEqual(1, len(res))
self.unpriv_user_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
self.unpriv_user_dn = res[0].dn
self.samdb = SamDB(url=ldaphost, credentials=self.unpriv_creds, lp=lp)
self.samr = samr.samr("ncacn_ip_tcp:%s[seal]" % host, lp, self.unpriv_creds)
self.samr_handle = self.samr.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED)
self.samr_domain = self.samr.OpenDomain(self.samr_handle, security.SEC_FLAG_MAXIMUM_ALLOWED, self.domain_sid)
self.sd_utils = sd_utils.SDUtils(self.admin_samdb)
self.admin_samdb.create_ou("OU=test_computer_ou1," + self.base_dn)
self.unpriv_user_sid = self.sd_utils.get_object_sid(self.unpriv_user_dn)
mod = "(OA;;CC;bf967a86-0de6-11d0-a285-00aa003049e2;;%s)" % str(self.unpriv_user_sid)
old_sd = self.sd_utils.read_sd_on_dn("OU=test_computer_ou1," + self.base_dn)
self.sd_utils.dacl_add_ace("OU=test_computer_ou1," + self.base_dn, mod)
self.add_computer_ldap("testcomputer-t")
self.sd_utils.modify_sd_on_dn("OU=test_computer_ou1," + self.base_dn, old_sd)
self.computernames = ["testcomputer-0"]
# Get the SD of the template account, then force it to match
# what we expect for SeMachineAccountPrivilege accounts, so we
# can confirm we created the accounts correctly
self.sd_reference_cc = self.sd_utils.read_sd_on_dn("CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
self.sd_reference_modify = self.sd_utils.read_sd_on_dn("CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
for ace in self.sd_reference_modify.dacl.aces:
if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED and ace.trustee == self.unpriv_user_sid:
ace.access_mask = ace.access_mask | security.SEC_ADS_SELF_WRITE | security.SEC_ADS_WRITE_PROP
# Now reconnect without domain admin rights
self.samdb = SamDB(url=ldaphost, credentials=self.unpriv_creds, lp=lp)
def tearDown(self):
super(UserAccountControlTests, self).tearDown()
for computername in self.computernames:
delete_force(self.admin_samdb, "CN=%s,OU=test_computer_ou1,%s" % (computername, self.base_dn))
delete_force(self.admin_samdb, "CN=testcomputer-t,OU=test_computer_ou1,%s" % (self.base_dn))
delete_force(self.admin_samdb, "OU=test_computer_ou1,%s" % (self.base_dn))
#.........这里部分代码省略.........
示例13: DynamicTokenTest
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [as 别名]
class DynamicTokenTest(samba.tests.TestCase):
def get_creds(self, target_username, target_password):
creds_tmp = Credentials()
creds_tmp.set_username(target_username)
creds_tmp.set_password(target_password)
creds_tmp.set_domain(creds.get_domain())
creds_tmp.set_realm(creds.get_realm())
creds_tmp.set_workstation(creds.get_workstation())
creds_tmp.set_gensec_features(creds_tmp.get_gensec_features() | gensec.FEATURE_SEAL)
return creds_tmp
def get_ldb_connection(self, target_username, target_password):
creds_tmp = self.get_creds(target_username, target_password)
ldb_target = SamDB(url=url, credentials=creds_tmp, lp=lp)
return ldb_target
def setUp(self):
super(DynamicTokenTest, self).setUp()
self.admin_ldb = SamDB(url, credentials=creds, session_info=system_session(lp), lp=lp)
self.base_dn = self.admin_ldb.domain_dn()
self.test_user = "tokengroups_user1"
self.test_user_pass = "[email protected]"
self.admin_ldb.newuser(self.test_user, self.test_user_pass)
self.test_group0 = "tokengroups_group0"
self.admin_ldb.newgroup(self.test_group0, grouptype=dsdb.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP)
res = self.admin_ldb.search(
base="cn={0!s},cn=users,{1!s}".format(self.test_group0, self.base_dn),
attrs=["objectSid"],
scope=ldb.SCOPE_BASE,
)
self.test_group0_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group0, [self.test_user], add_members_operation=True)
self.test_group1 = "tokengroups_group1"
self.admin_ldb.newgroup(self.test_group1, grouptype=dsdb.GTYPE_SECURITY_GLOBAL_GROUP)
res = self.admin_ldb.search(
base="cn={0!s},cn=users,{1!s}".format(self.test_group1, self.base_dn),
attrs=["objectSid"],
scope=ldb.SCOPE_BASE,
)
self.test_group1_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group1, [self.test_user], add_members_operation=True)
self.test_group2 = "tokengroups_group2"
self.admin_ldb.newgroup(self.test_group2, grouptype=dsdb.GTYPE_SECURITY_UNIVERSAL_GROUP)
res = self.admin_ldb.search(
base="cn={0!s},cn=users,{1!s}".format(self.test_group2, self.base_dn),
attrs=["objectSid"],
scope=ldb.SCOPE_BASE,
)
self.test_group2_sid = ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["objectSid"][0])
self.admin_ldb.add_remove_group_members(self.test_group2, [self.test_user], add_members_operation=True)
self.ldb = self.get_ldb_connection(self.test_user, self.test_user_pass)
res = self.ldb.search("", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
self.assertEquals(len(res), 1)
self.user_sid_dn = "<SID={0!s}>".format(
str(ndr_unpack(samba.dcerpc.security.dom_sid, res[0]["tokenGroups"][0]))
)
res = self.ldb.search(self.user_sid_dn, scope=ldb.SCOPE_BASE, attrs=[])
self.assertEquals(len(res), 1)
self.test_user_dn = res[0].dn
session_info_flags = (
AUTH_SESSION_INFO_DEFAULT_GROUPS | AUTH_SESSION_INFO_AUTHENTICATED | AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
)
session = samba.auth.user_session(
self.ldb, lp_ctx=lp, dn=self.user_sid_dn, session_info_flags=session_info_flags
)
token = session.security_token
self.user_sids = []
for s in token.sids:
self.user_sids.append(str(s))
def tearDown(self):
super(DynamicTokenTest, self).tearDown()
delete_force(self.admin_ldb, "CN={0!s},{1!s},{2!s}".format(self.test_user, "cn=users", self.base_dn))
delete_force(self.admin_ldb, "CN={0!s},{1!s},{2!s}".format(self.test_group0, "cn=users", self.base_dn))
delete_force(self.admin_ldb, "CN={0!s},{1!s},{2!s}".format(self.test_group1, "cn=users", self.base_dn))
delete_force(self.admin_ldb, "CN={0!s},{1!s},{2!s}".format(self.test_group2, "cn=users", self.base_dn))
def test_rootDSE_tokenGroups(self):
"""Testing rootDSE tokengroups against internal calculation"""
if not url.startswith("ldap"):
self.fail(msg="This test is only valid on ldap")
res = self.ldb.search("", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
self.assertEquals(len(res), 1)
#.........这里部分代码省略.........
示例14: DsdbTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import newuser [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:
#.........这里部分代码省略.........