0

我正在尝试获取存储在 LDAP 数据库中的所有电子邮件地址的列表,以逗号分隔。

通过简化这个脚本,我有:

#!/usr/bin/env python
# encoding: utf-8

# Author:   Zhang Huangbin <zhb _at_ iredmail.org>
# Purpose:  Add enabledService=lib-storage for all mail users.
#           Required by IMAP folder sharing in Dovecot-2.0.
# Date:     2012-05-18

import sys
import ldap

# Note:
#   * bind_dn must have write privilege on LDAP server.
uri = 'ldap://127.0.0.1:389'
basedn = 'o=domains,dc=example,dc=com'
bind_dn = 'cn=Manager,dc=example,dc=com'
bind_pw = 'password'

# Initialize LDAP connection.
print >> sys.stderr, "* Connecting to LDAP server: %s" % uri
conn = ldap.initialize(uri=uri, trace_level=0,)
conn.bind_s(bind_dn, bind_pw)

# Get all mail users.
print >> sys.stderr, "* Get all mail accounts..."
allUsers = conn.search_s(
        basedn,
        ldap.SCOPE_SUBTREE,
        "(objectClass=mailUser)",
        ['mail', 'enabledService'],
        )

total = len(allUsers)
print >> sys.stderr, "* Total %d user(s)." % (total)

# Counter.
count = 1

for user in allUsers:
    (dn, entry) = user
    mail = entry['mail'][0]

    print >> "%s, " % (mail)

    count += 1

# Unbind connection.
conn.unbind()

当我运行这个我得到错误:

  • 连接 LDAP 服务器:ldap://127.0.0.1:389
  • 获取所有邮件帐户...
  • 共有 64 个用户。回溯(最近一次调用最后一次):文件“list_mail_users.py”,第 43 行,打印 >>“%s”,%(邮件)AttributeError:'str'对象没有属性'write'

我在支持论坛上问了这个问题,他们建议我使用:ldapsearch 代替?

4

1 回答 1

1

这是你的问题

for user in allUsers:
  (dn, entry) = user
  mail = entry['mail'][0]

  print >> "%s, " % (mail)

  count += 1

您正在尝试打印到“%s”,它是一个字符串,打印只能接受具有写入属性的对象。我不完全确定您要对此做什么,但我会期待类似print >> sys.stdout, "%s, " %(mail)或可能的事情print >> File "%s, "%mail

于 2013-01-02T10:50:25.803 回答