本文整理汇总了Python中samba.generate_random_password函数的典型用法代码示例。如果您正苦于以下问题:Python generate_random_password函数的具体用法?Python generate_random_password怎么用?Python generate_random_password使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了generate_random_password函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self, username=None, filter=None, credopts=None, sambaopts=None,
versionopts=None, H=None, newpassword=None,
must_change_at_next_login=False, random_password=False):
if filter is None and username is None:
raise CommandError("Either the username or '--filter' must be specified!")
if random_password:
password = generate_random_password(128, 255)
else:
password = newpassword
while 1:
if password is not None and password is not '':
break
password = getpass("New Password: ")
if filter is None:
filter = "(&(objectClass=user)(sAMAccountName={0!s}))".format((ldb.binary_encode(username)))
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
try:
samdb.setpassword(filter, password,
force_change_at_next_login=must_change_at_next_login,
username=username)
except Exception, msg:
# FIXME: catch more specific exception
raise CommandError("Failed to set password for user '{0!s}': {1!s}".format(username or filter, msg))
示例2: run
def run(self, username=None, filter=None, credopts=None, sambaopts=None,
versionopts=None, H=None, newpassword=None,
must_change_at_next_login=False, random_password=False,
smartcard_required=False, clear_smartcard_required=False):
if filter is None and username is None:
raise CommandError("Either the username or '--filter' must be specified!")
password = newpassword
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 clear_smartcard_required:
raise CommandError('It is not allowed to specifiy '
'--clear-smartcard-required '
'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 filter is None:
filter = "(&(objectClass=user)(sAMAccountName=%s))" % (ldb.binary_encode(username))
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp)
if smartcard_required:
command = ""
try:
command = "Failed to set UF_SMARTCARD_REQUIRED for user '%s'" % (username or filter)
flags = dsdb.UF_SMARTCARD_REQUIRED
samdb.toggle_userAccountFlags(filter, flags, on=True)
command = "Failed to enable account for user '%s'" % (username or filter)
samdb.enable_account(filter)
except Exception, msg:
# FIXME: catch more specific exception
raise CommandError("%s: %s" % (command, msg))
self.outf.write("Added UF_SMARTCARD_REQUIRED OK\n")
示例3: run
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)
示例4: test_ldap_change_password
def test_ldap_change_password(self):
def isLastExpectedMessage(msg):
return (msg["type"] == "Authentication" and
msg["Authentication"]["status"]
== "NT_STATUS_OK" and
msg["Authentication"]["serviceDescription"]
== "LDAP Password Change" and
msg["Authentication"]["authDescription"]
== "LDAP Modify")
new_password = samba.generate_random_password(32,32)
self.ldb.modify_ldif(
"dn: cn=" + USER_NAME + ",cn=users," + self.base_dn + "\n" +
"changetype: modify\n" +
"delete: userPassword\n" +
"userPassword: " + USER_PASS + "\n" +
"add: userPassword\n" +
"userPassword: " + new_password + "\n"
)
messages = self.waitForMessages(isLastExpectedMessage)
print "Received %d messages" % len(messages)
self.assertEquals(4,
len(messages),
"Did not receive the expected number of messages")
示例5: test_ldap_change_password_bad_original_password
def test_ldap_change_password_bad_original_password(self):
def isLastExpectedMessage(msg):
return ((msg["type"] == "Authentication") and
(msg["Authentication"]["status"] ==
"NT_STATUS_WRONG_PASSWORD") and
(msg["Authentication"]["serviceDescription"] ==
"LDAP Password Change") and
(msg["Authentication"]["authDescription"] ==
"LDAP Modify"))
new_password = samba.generate_random_password(32, 32)
try:
self.ldb.modify_ldif(
"dn: cn=" + USER_NAME + ",cn=users," + self.base_dn + "\n" +
"changetype: modify\n" +
"delete: userPassword\n" +
"userPassword: " + "badPassword" + "\n" +
"add: userPassword\n" +
"userPassword: " + new_password + "\n")
self.fail()
except LdbError as e1:
(num, msg) = e1.args
pass
messages = self.waitForMessages(isLastExpectedMessage)
print("Received %d messages" % len(messages))
self.assertEquals(4,
len(messages),
"Did not receive the expected number of messages")
示例6: update_dns_account_password
def update_dns_account_password(samdb, secrets_ldb, names):
"""Update (change) the password of the dns both in the SAM db and in
secret one
:param samdb: An LDB object related to the sam.ldb file of a given provision
:param secrets_ldb: An LDB object related to the secrets.ldb file of a given
provision
:param names: List of key provision parameters"""
expression = "samAccountName=dns-%s" % names.netbiosname
secrets_msg = secrets_ldb.search(expression=expression)
if len(secrets_msg) == 1:
res = samdb.search(expression=expression, attrs=[])
assert len(res) == 1
msg = ldb.Message(res[0].dn)
machinepass = samba.generate_random_password(128, 255)
mputf16 = machinepass.encode("utf-16-le")
msg["clearTextPassword"] = ldb.MessageElement(mputf16, ldb.FLAG_MOD_REPLACE, "clearTextPassword")
samdb.modify(msg)
res = samdb.search(expression=expression, attrs=["msDs-keyVersionNumber"])
assert len(res) == 1
kvno = str(res[0]["msDs-keyVersionNumber"])
msg = ldb.Message(secrets_msg[0].dn)
msg["secret"] = ldb.MessageElement(machinepass, ldb.FLAG_MOD_REPLACE, "secret")
msg["msDS-KeyVersionNumber"] = ldb.MessageElement(kvno, ldb.FLAG_MOD_REPLACE, "msDS-KeyVersionNumber")
secrets_ldb.modify(msg)
示例7: SetPassword
def SetPassword(self):
if not self._check_session():
return json.dumps(self.AuthErr);
try:
rid = request.params.get("rid",self.rid)
username = request.params.get("account","")
password = request.params.get("password",samba.generate_random_password(7,15))
#response.write(password);
if(self.model.isAuthenticate()):
if(not self.model.SetPassword(username,password)):
raise Exception(self.model.LastErrorNumber,self.model.LastErrorStr)
UnlockUserAccount = request.params.get("UnlockUserAccount",False)
if(UnlockUserAccount != False):
if(not self.model.EnableAccount(rid,username,True)):
raise Exception(self.model.LastErrorNumber,self.model.LastErrorStr)
ForcePasswordChange = request.params.get("ForcePasswordChange","off").strip();
if(ForcePasswordChange == "on"):
if(not self.model.ForcePasswordChangeAtNextLogin(rid,username)):
raise Exception(self.model.LastErrorNumber,self.model.LastErrorStr)
else:
if(not self.model.ForcePasswordChangeAtNextLogin(rid,username,False)):
raise Exception(self.model.LastErrorNumber,self.model.LastErrorStr)
except Exception,e:
if(len(e.args)>1):
return json.dumps({'success': False, 'msg': e.args[1],'num':e.args[0]})
else:
return json.dumps({'success': False, 'msg': e.args,'num':-1})
示例8: test_ldap_change_password_bad_user
def test_ldap_change_password_bad_user(self):
def isLastExpectedMessage(msg):
return (msg["type"] == "Authorization" and
msg["Authorization"]["serviceDescription"] == "LDAP" and
msg["Authorization"]["authType"] == "krb5")
new_password = samba.generate_random_password(32, 32)
try:
self.ldb.modify_ldif(
"dn: cn=" + "badUser" + ",cn=users," + self.base_dn + "\n" +
"changetype: modify\n" +
"delete: userPassword\n" +
"userPassword: " + USER_PASS + "\n" +
"add: userPassword\n" +
"userPassword: " + new_password + "\n")
self.fail()
except LdbError as e:
(num, msg) = e.args
pass
messages = self.waitForMessages(isLastExpectedMessage)
print("Received %d messages" % len(messages))
self.assertEquals(3,
len(messages),
"Did not receive the expected number of messages")
示例9: create_user_account
def create_user_account(self):
self.user_pass = samba.generate_random_password(32, 32)
self.user_name = USER_NAME
self.user_dn = "cn=%s,%s" % (self.user_name, self.ldb.domain_dn())
# remove the account if it exists, this will happen if a previous test
# run failed
delete_force(self.ldb, self.user_dn)
utf16pw = unicode(
'"' + self.user_pass.encode('utf-8') + '"', 'utf-8'
).encode('utf-16-le')
self.ldb.add({
"dn": self.user_dn,
"objectclass": "user",
"sAMAccountName": "%s" % self.user_name,
"userAccountControl": str(UF_NORMAL_ACCOUNT),
"unicodePwd": utf16pw})
self.user_creds = Credentials()
self.user_creds.guess(self.get_loadparm())
self.user_creds.set_password(self.user_pass)
self.user_creds.set_username(self.user_name)
self.user_creds.set_workstation(self.machine_name)
pass
示例10: create_machine_account
def create_machine_account(self):
self.machine_pass = samba.generate_random_password(32, 32)
self.machine_name = MACHINE_NAME
self.machine_dn = "cn=%s,%s" % (self.machine_name, self.ldb.domain_dn())
# remove the account if it exists, this will happen if a previous test
# run failed
delete_force(self.ldb, self.machine_dn)
utf16pw = unicode(
'"' + self.machine_pass.encode('utf-8') + '"', 'utf-8'
).encode('utf-16-le')
self.ldb.add({
"dn": self.machine_dn,
"objectclass": "computer",
"sAMAccountName": "%s$" % self.machine_name,
"userAccountControl":
str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
"unicodePwd": utf16pw})
self.machine_creds = Credentials()
self.machine_creds.guess(self.get_loadparm())
self.machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
self.machine_creds.set_kerberos_state(DONT_USE_KERBEROS)
self.machine_creds.set_password(self.machine_pass)
self.machine_creds.set_username(self.machine_name + "$")
self.machine_creds.set_workstation(self.machine_name)
示例11: test_supplementalCredentials_cleartext_pso
def test_supplementalCredentials_cleartext_pso(self):
"""Checks that a PSO's cleartext setting can override the domain's"""
# create a user that stores plain-text passwords
self.add_user(clear_text=True)
# check that clear-text is present in the supplementary-credentials
self.assert_cleartext(expect_cleartext=True, password=USER_PASS)
# create a PSO overriding the plain-text setting & apply it to the user
no_plaintext_pso = PasswordSettings("no-plaintext-PSO", self.ldb,
precedence=200,
store_plaintext=False)
self.addCleanup(self.ldb.delete, no_plaintext_pso.dn)
userdn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
no_plaintext_pso.apply_to(userdn)
# set the password to update the cleartext password stored
new_password = samba.generate_random_password(32, 32)
self.ldb.setpassword("(sAMAccountName=%s)" % USER_NAME, new_password)
# this time cleartext shouldn't be in the supplementary creds
self.assert_cleartext(expect_cleartext=False)
# unapply PSO, update password, and check we get the cleartext again
no_plaintext_pso.unapply(userdn)
new_password = samba.generate_random_password(32, 32)
self.ldb.setpassword("(sAMAccountName=%s)" % USER_NAME, new_password)
self.assert_cleartext(expect_cleartext=True, password=new_password)
# Now update the domain setting and check we no longer get cleartext
self.set_store_cleartext(False)
new_password = samba.generate_random_password(32, 32)
self.ldb.setpassword("(sAMAccountName=%s)" % USER_NAME, new_password)
self.assert_cleartext(expect_cleartext=False)
# create a PSO overriding the domain setting & apply it to the user
plaintext_pso = PasswordSettings("plaintext-PSO", self.ldb,
precedence=100, store_plaintext=True)
self.addCleanup(self.ldb.delete, plaintext_pso.dn)
plaintext_pso.apply_to(userdn)
new_password = samba.generate_random_password(32, 32)
self.ldb.setpassword("(sAMAccountName=%s)" % USER_NAME, new_password)
self.assert_cleartext(expect_cleartext=True, password=new_password)
示例12: setUp
def setUp(self):
super(DirsyncBaseTests, self).setUp()
self.ldb_admin = SamDB(ldapshost, credentials=creds, session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb_admin.domain_dn()
self.domain_sid = security.dom_sid(self.ldb_admin.get_domain_sid())
self.user_pass = samba.generate_random_password(12, 16)
self.configuration_dn = self.ldb_admin.get_config_basedn().get_linearized()
self.sd_utils = sd_utils.SDUtils(self.ldb_admin)
#used for anonymous login
print("baseDN: %s" % self.base_dn)
示例13: run
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)
示例14: join_ad_full_credentials
def join_ad_full_credentials(self, realm, realm_server, realm_admin, realm_passwd):
if not self.configured:
return None
self.__populate_remote_domain(realm, realm_server, realm_admin, realm_passwd)
if not self.remote_domain.read_only:
trustdom_pass = samba.generate_random_password(128, 128)
self.remote_domain.establish_trust(self.local_domain, trustdom_pass)
self.local_domain.establish_trust(self.remote_domain, trustdom_pass)
result = self.remote_domain.verify_trust(self.local_domain)
return dict(local=self.local_domain, remote=self.remote_domain, verified=result)
return None
示例15: update_krbtgt_account_password
def update_krbtgt_account_password(samdb, names):
"""Update (change) the password of the krbtgt account
:param samdb: An LDB object related to the sam.ldb file of a given provision
:param names: List of key provision parameters"""
expression = "samAccountName=krbtgt"
res = samdb.search(expression=expression, attrs=[])
assert len(res) == 1
msg = ldb.Message(res[0].dn)
machinepass = samba.generate_random_password(128, 255)
mputf16 = machinepass.encode("utf-16-le")
msg["clearTextPassword"] = ldb.MessageElement(mputf16, ldb.FLAG_MOD_REPLACE, "clearTextPassword")
samdb.modify(msg)