【问题标题】:For Loop Not Executing Properly wrapped around Try/ExceptFor 循环未正确执行环绕 Try/Except
【发布时间】:2017-03-31 14:17:13
【问题描述】:

我有一个看起来像这样的函数:

def get_users(yaml_file="AD_Users.yml"):
with open(yaml_file, 'r') as stream:
    try:
        data = yaml.load(stream)
    except yaml.YAMLError as exc:
        print(exc)
return data.itervalues()

 def create_user_in_ad(new_users): #username, password, base_dn, fname, lname, domain):
    # LDAP connection
    for new_user in new_users:
        try:
            logging.info('Connecting to LDAP Server %s ' % LDAP_SERVER)
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, 0)
            ldap_connection = ldap.initialize(LDAP_SERVER)
            ldap_connection.simple_bind_s(BIND_DN, BIND_PASS)
            print "Connected to LDAP Server!"
        except ldap.LDAPError, error_message:
            print "Error connecting to LDAP server: %s" % error_message
            #logging.info('Unable to connect to LDAP Server %s ' % LDAP_SERVER)
            return False
#           sys.exit(1)

      # Check and see if user exists
        try:
            print new_user['username'] 
            logging.info('Querying AD for user: %s ' % new_user['username'])
            user_results = ldap_connection.search_s(BASE_DN, ldap.SCOPE_SUBTREE,
                                                  '(&(sAMAccountName=' +
                                                  new_user['username'] +
                                                  ')(objectClass=person))',
                                                  ['distinguishedName'])
            print user_results
        except ldap.LDAPError, error_message:
            print "Error finding username: %s" % error_message
            logging.info('Unable to query for user: %s ' % new_user['username'])
            return False

      # Check the results
        if len(user_results) != 0:
            print "User", new_user['username'], "already exists in AD:"
            return False
            sys.exit(1)

      # Lets build our user: Disabled to start (514)
        USER_DN = 'cn=' + new_user['fname'] + ' ' + new_user['lname'] + ',' + BASE_DN
        GROUP_DN = 'ou=' + new_user['group_dn'] + ',' + BASE_DN
        user_attrs = {}
        user_attrs['objectClass'] = \
                    ['top', 'person', 'organizationalPerson', 'user']
        user_attrs['cn'] = new_user['fname'] + ' ' + new_user['lname']
        user_attrs['userPrincipalName'] = new_user['username'] + '@' + new_user['domain']

      # Add the new user account
        try:
            ldap_connection.add_s(USER_DN, user_ldif)
            logging.info('Adding user into AD: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error adding new user: %s" % error_message
            return False

      # Add the password
        try:
            ldap_connection.modify_s(USER_DN, add_pass)
            logging.info('Password added for user: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error setting password: %s" % error_message
            return False

      # Change the account back to enabled
        try:
            ldap_connection.modify_s(USER_DN, mod_acct)
            logging.info('Enabling AD Account for user: %s ' % new_user['username'])
        except ldap.LDAPError, error_message:
            print "Error enabling user: %s" % error_message
            return False

      # Add user to their primary group
        try:
            ldap_connection.modify_s(GROUP_DN, add_member)
            logging.info('Adding user to group %s: ' % new_user['group_dn'])
        except ldap.LDAPError, error_message:
            print "Error adding user to group: %s" % error_message
        return
new_users = get_users()
if args.createusers is not "None": 
    create_user_in_ad(new_users)

它调用带有用户信息的 YAML 文件:

 User1:
    username: adtest2
    fname: adtest2
    lname: adtest2
    domain: test.com
    group_dn: test
#   group: 

  # User2:
  #    username: testing
  #    fname: testing
  #    lname: bbbbb
  #    domain: test.com
  #    group_dn: test
# #   group:

    ldap_connection.unbind_s()

    print "User %s has been created in AD!" % new_user['username']

    # All is good
    return True

现在的问题是它只在没有注释掉的情况下在第二个用户上执行,我想知道我的 for 循环是否做错了什么?它正在做我想让它正确地做的一切。我正在使用 Python 2.7.13 顺便说一句!

现在输出只显示第二个用户:

    Connected to LDAP Server!
adtest2

【问题讨论】:

  • 你得到什么输出表明它只在第二个用户上执行?如果添加print new_user.
  • 我正在打印查询的结果,您可以在其中看到我正在打印new_user 的用户名。我还添加了一个 print new_user['username'] 来将用户用户名打印到代码中,仍然只返回第二个人
  • 用输出更新了问题
  • 所有这些代码与 YAML 文件有什么关系?读取它发生在它之前(大概),因为您只是将似乎是字典列表的内容传递给函数。请创建一个minimal reproducible example
  • 很好的问题,添加了执行它的功能以及问题的执行

标签: python for-loop yaml


【解决方案1】:

问题是返回是在 for 循环内执行的。我只是将它移到了 for 循环之外。

【讨论】:

    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多