【问题标题】:Trying to create a list of users in AD尝试在 AD 中创建用户列表
【发布时间】:2012-10-12 14:34:02
【问题描述】:

因此,我创建了一个脚本,用于在 AD 中搜索特定 OU 中的用户列表,并将其输出到文本文件。我需要格式化这个文本文件。我正在搜索的顶部 OU 中包含该公司每个位置的 OU,其中包含该位置的用户帐户。

这是我的脚本:

import active_directory
import sys

sys.stdout = open('output.txt', 'w')
users = active_directory.AD_object ("LDAP://ou=%company%,dc=%domain%,dc=%name%
for user in users.search (objectCategory='Person'):
 print user

sys.stdout.close()

这是我的输出的样子,每个不同的用户只有 20 多行:

LDAP://CN=%username%,OU=%location%,OU=%company%,dc=%domain%,dc=%name%

所以,我想做的只是用简单的英语来表达,让它更容易阅读,只需显示用户名和子集 OU。所以这个:

LDAP://CN=%username%,OU=%location%,OU=%company%,dc=%domain%,dc=%name%

变成这样:

%username%, %location%

如果有任何方法可以将其导出到 .csv 或 .xls 以放入可以按位置或仅按字母顺序排序的列中,那就太好了。我花了很长时间才弄清楚文本文件。

【问题讨论】:

    标签: python windows active-directory python-2.7


    【解决方案1】:

    如果你有这样的字符串

    LDAP://CN=%username%,OU=%location%,OU=%company%,dc=%domain%,dc=%name%
    

    那么操作就很容易了。如果格式是标准的并且没有改变,那么操作它的最快方法就是使用 string.split()

    >>> splitted = "LDAP://CN=%username%,OU=%location%,OU=%company%,dc=%domain%,dc=%name%".split('=')
    

    产生一个列表

    >>> splitted 
    ["LDAP://CN", 
     "%username%, OU",
     "%location%, OU",
     "%company%, dc",
     "%domain%, dc",
     "%name%"]
    

    现在我们可以访问列表中的项目了

    >>> splitted[1]
    "%username%, OU"
    

    要去掉“, OU”,我们需要再做一次拆分。

    >>> username = splitted[1].split(", OU")[0]
    >>> username
    %username%
    

    CSV 只是一个文本文件,因此您只需更改文件结尾即可。这是一个完整的例子。

    output = open("output.csv","w")
    users = active_directory.AD_object ("LDAP://ou=%company%,dc=%domain%,dc=%name%
    for user in users.search (objectCategory='Person'):
        # Because the AD_object.search() returns another AD_object
        # we cannot split it. We need the string representation
        # of this AD object, and thus have to wrap the user in str()
    
        splitteduser = str(user).split('=')
        username = splitteduser[1].split(", OU")[0]
        location = splitteduser[2].split(", OU")[0]
        output.write("%s, %s\n"%(username,location))
    
        % \n is a line ending
        % The above is the old way to format strings, but it looks simpler.
        % Correct way would be:
        % output.write("{0}, {1}\n".format(username,location))    
    
    output.close()
    

    这不是最漂亮的解决方案,但应该很容易理解。

    【讨论】:

    • 听起来不错。我应该可以使用这个。我实际上能够理解它,有点。
    • 你给我的答案是给我一个来自splitteduser = user.split('=')的active_directory模块的回溯错误。你能帮忙吗?
    • 如果没有实际的回溯错误(我猜是 AttributeError),我不得不猜测:显然 AD_object.search 函数返回的“用户”不是字符串。但是,由于在您自己的示例中使用 print user 时它可以很好地打印为字符串,我猜想这个问题可以通过使用 str()repr() a) splitteduser = str(user).split('=')b) splitteduser = repr(user).split('=')
    • 是的,我检查了 Tim Golden 的 active_directory 源代码。使用 str() 应该是正确的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多