2013-01-02 83 views
0

我試圖獲取以逗號分隔的LDAP數據庫中存儲的所有電子郵件地址的列表。將數組轉換爲連接字符串的逗號分隔的腳本

通過簡化這個script我:

#!/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() 

當我運行此我得到錯誤:

  • Connecting to LDAP server: ldap://127.0.0.1:389
  • Get all mail accounts...
  • Total 64 user(s). Traceback (most recent call last): File "list_mail_users.py", line 43, in print >> "%s, " % (mail) AttributeError: 'str' object has no attribute 'write'

我問這個問題上的支持論壇和他們建議我使用:ldapsearch的呢?

回答

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

+0

此外,我希望你可能想'''.join(郵件)作爲打印什麼,而不是「%s」, – Perkins

相關問題