尝试在AD中创建用户列表

时间:2012-10-12 14:34:03

标签: python windows active-directory python-2.7

因此,我创建了一个脚本,在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以放入可以按位置或按字母顺序排序的列,那将是非常好的。我有一段时间只是搞清楚文本文件。

1 个答案:

答案 0 :(得分: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()

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