python ldap,ldap

來源:互聯網
上載者:User

python ldap,ldap

# -*- coding: UTF-8 -*-
import ldap,os
from ldap import modlist
LDAP_HOST = "aodun.com"
USER = "cn=admin,dc=aodun,dc=com"
PASSWORD = "aodun"
BASE_DN = "dc=aodun,dc=com"


class LdapOpt(object):
def __init__(self, server_port=389):
self.server_uri = LDAP_HOST
self.server_port = server_port
self.ldap_obj = None
self.bind_name = USER
self.bind_passwd = PASSWORD
self.ldap_connect()

def ldap_connect(self):
"""
:param bind_name:
:param bind_passwd:
:return:
"""
url = self.server_uri
conn = ldap.open(url)
try:
rest = conn.simple_bind_s(self.bind_name, self.bind_passwd)
except ldap.SERVER_DOWN:
print(u"無法串連到LDAP")
except ldap.INVALID_CREDENTIALS:
print (u"LDAP帳號錯誤")
except Exception, ex:
print (type(ex))
if rest[0] != 97: # 97 表示success
print (rest[1])
self.ldap_obj = conn

def add_user(self, base_dn, password):
"""
base_dn: uid=test, ou=magicstack,dc=test,dc=com NOT NONE
"""
import random
ldap_newuid = str(random.randint(100000,999999))
ldap_getgid = str(random.randint(100000,999999))
if not base_dn:
print (u"DN不可為空")
dn_list = base_dn.split(',')
user_info = dict()
for item in dn_list:
attr, value = item.split('=')
user_info[attr] = value
attrs = {}
attrs['objectclass'] = ['person', 'inetOrgPerson', 'posixAccount', 'organizationalPerson']
attrs['cn'] = str(user_info['uid'])
attrs['homeDirectory'] = '/home/%s' % str(user_info['uid'])
attrs['loginShell'] = '/bin/bash'
attrs['sn'] = str(user_info['uid'])
attrs['uid'] = str(user_info['uid'])
attrs['uidNumber'] = ldap_newuid
attrs['gidNumber'] = ldap_getgid
attrs['userPassword'] = str(password)
ldif = modlist.addModlist(attrs)
try:
result = self.ldap_obj.add_s(base_dn, ldif)
except ldap.LDAPError, error_message:
print (error_message)
return False, error_message
else:
if result[0] == 105:
return True, []
else:
return False, result[1]

def delete_user(self, dn):
"""
dn: cn=test, ou=magicstack,dc=test, dc=com
"""
try:
result = self.ldap_obj.delete_s(dn)
except ldap.LDAPError, error_message:
print (error_message)
return False, error_message
else:
if result[0] == 107:
return True, []
else:
return False, result[1]


if __name__ == "__main__":
d = LdapOpt()
print d.add_user("uid=chen,ou=People,dc=aodun,dc=com","123456")
print d.delete_user("uid=chen,ou=People,dc=aodun,dc=com")

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.