Chinaunix首页 | 论坛 | 博客
  • 博客访问: 796985
  • 博文数量: 186
  • 博客积分: 4939
  • 博客等级: 上校
  • 技术积分: 2075
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-08 17:15
文章分类

全部博文(186)

文章存档

2018年(1)

2017年(3)

2016年(11)

2015年(42)

2014年(21)

2013年(9)

2012年(18)

2011年(46)

2010年(35)

分类: 系统运维

2015-09-21 14:26:12


  1. import ldap
  2. import ldap.modlist as modlist
  3. import test_Passwords
  4. class new:
  5.         def __init__(self,server='ad.xxx.com'):
  6.                 login = test_Passwords.new()
  7.                 username, password = login.credentials('ad')
  8.                 self.dn = {'base':'dc=ad,dc=xxx,dc=com'}
  9.                 self.dgattrs = {'user':{},'chat':{},'mail':{}}
  10.                 self.dgattrs['user']['dn'] = ','.join(['ou=Basers',self.dn['base']])
  11.                 self.dgattrs['user']['objectClass'] = ['top','group']
  12.                 self.dgattrs['user']['description'] = ['user_group']
  13.                 self.dgattrs['user']['member_field'] = 'member'
  14.                 self.dgattrs['user']['filter'] = '(objectClass=group)'
  15.                 self.dgattrs['all'] = self.dgattrs['user']
  16.                 self.dgattrs['chat']['dn'] = ','.join(['ou=Chat Groups',self.dn['base']])
  17.                 self.dgattrs['chat']['objectClass'] = ['top','groupOfUniqueNames']
  18.                 self.dgattrs['chat']['description'] = ['chat_group']
  19.                 self.dgattrs['chat']['member_field'] = 'uniqueMember'
  20.                 self.dgattrs['chat']['filter'] = '(&(objectClass=groupOfUniqueNames)(description=chat_group))'
  21.                 self.dgattrs['mail']['dn'] = ','.join(['ou=Email Aliases',self.dn['base']])
  22.                 self.dgattrs['mail']['objectClass'] = ['top','groupOfUniqueNames']
  23.                 self.dgattrs['mail']['description'] = ['mail_group']
  24.                 self.dgattrs['mail']['member_field'] = 'uniqueMember'
  25.                 self.dgattrs['mail']['filter'] = '(&(objectClass=groupOfUniqueNames)(description=mail_group))'
  26.                 host = 'ldap://%s' % server
  27.                 self.conn = ldap.initialize(host)
  28.                 self.conn.set_option(ldap.OPT_NETWORK_TIMEOUT,10)
  29.                 self.conn.set_option(ldap.OPT_TIMEOUT,10)
  30.                 self.conn.set_option(ldap.OPT_TIMELIMIT,10)
  31.                 self.conn.set_option(ldap.OPT_SIZELIMIT,0)
  32.                 self.conn.bind(username,password)
  33.                 self.conn.whoami_s()
  34.                 self.group_users = {}
  35.                 self.groups = []

  36.         def disconnect(self):
  37.                 self.conn.unbind()

  38.         def search(self,dn='dc=ad,dc=xxx,dc=com',search_filter='',attrs='cn',scope=ldap.SCOPE_SUBTREE):
  39.                 if isinstance(attrs,basestring): attrs=[attrs]
  40.                 results = []
  41.                 if not dn:
  42.                         dn = self.dn['base']

  43.                 try:
  44.                         s = self.conn.search_ext(dn, scope, search_filter, attrs, sizelimit=-1)
  45.                         while True:
  46.                                 stype,sresult = self.conn.result(s,0)
  47.                                 if stype == ldap.RES_SEARCH_ENTRY:
  48.                                         results.extend([sresult])
  49.                                 else:
  50.                                         break
  51.                 except ldap.NO_SUCH_OBJECT:
  52.                         return
  53.                 return results

  54.         def get_users(self,refresh=False):
  55.                 if refresh: del self.users
  56.                 try:
  57.                         return self.users
  58.                 except:
  59.                         self.users = []
  60.                         for userline in self.search(search_filter='(&(objectClass=user)(!(objectClass=computer))(!(userAccountControl=514))(!(userAccountControl=546))(!(userAccountControl=66050))(!(userAccountControl=66082))(!(userAccoun
  61. tControl=262658))(!(userAccountControl=262690))(!(userAccountControl=328194))(!(userAccountControl=328226)))'):
  62.                                 self.users.extend([userline[0][1]['cn'][0]])
  63.                         return self.users

  64.         def get_real_users(self,refresh=False):
  65.                 if refresh: del self.real_users
  66.                 try:
  67.                         return self.real_users
  68.                 except:
  69.                         self.real_users = []
  70.                         for userline in self.search(search_filter='(&(objectClass=user)(!(objectClass=computer))(!(userAccountControl=514))(!(userAccountControl=546))(!(userAccountControl=66050))(!(userAccountControl=66082))(!(userAccoun
  71. tControl=262658))(!(userAccountControl=262690))(!(userAccountControl=328194))(!(userAccountControl=328226))(!(UserAccountControl=66080)))'):
  72.                                 self.real_users.extend([userline[0][1]['cn'][0]])
  73.                         return self.real_users
  74.         def get_groups(self,gtype='all',refresh=False):
  75.                 if refresh and gtype in self.groups:
  76.                         del self.groups[gtype]
  77.                 try:
  78.                         return self.groups[gtype]
  79.                 except:
  80.                         self.groups = {'user':[],'chat':[],'mail':[],'all':[]}
  81.                         for g in self.groups:
  82.                                 if g == 'all': continue
  83.                                 dn = self.dgattrs[g]['dn']
  84.                                 search_filter = self.dgattrs[g]['filter']
  85.                                 #print g,dn,search_filter
  86.                                 for groupline in self.search(dn=dn,search_filter=search_filter):
  87.                                         self.groups[g].extend([groupline[0][1]['cn'][0]])
  88.                                         self.groups['all'].extend([groupline[0][1]['cn'][0]])
  89.                 return self.groups[gtype]

  90.         def create_group(self,group,users=[],gtype='user'):
  91.                 if isinstance(users,basestring): users=[users]
  92.                 if group in self.get_groups(gtype=gtype,refresh=True):
  93.                         print 'group exists skipping'
  94.                         return
  95.                 attrs = {}
  96.                 attrs['objectClass'] = self.dgattrs[gtype]['objectClass']
  97.                 attrs['description'] = self.dgattrs[gtype]['description']
  98.                 if users:
  99.                         for user in users:
  100.                                 if user in self.get_users():
  101.                                         if user not in self.get_groups(gtype=gtype):
  102.                                                 attrs.setdefault(self.dgattrs[gtype]['member_field'],[]).extend([self.get_user_attr(user,'distinguishedName')])
  103.                                         else:
  104.                                                 print user,'-> already in group skipping'
  105.                                 else:
  106.                                         print user,'-> not valid skipping'
  107.                         if self.dgattrs[gtype]['member_field'] not in attrs:
  108.                                 print 'all users invalid or already in group'
  109.                                 return
  110.                 elif gtype != 'user':
  111.                         print 'need users for that group type skipping'
  112.                         return

  113.                 attrs[self.dgattrs[gtype]['member_field']] = list(set(attrs[self.dgattrs[gtype]['member_field']]))

  114.                 dn = ','.join(['cn=%s'%group,self.dgattrs[gtype]['dn']])
  115.                 print dn,modlist.addModlist(attrs)
  116.                 self.conn.add_s(dn,modlist.addModlist(attrs))

  117.         def get_group_users(self,group,gtype='user',refresh=False):
  118.                 if group not in self.get_groups(gtype=gtype):
  119.                         print group,'-> not found skipping'
  120.                         return
  121.                 try:
  122.                         return self.group_users[gtype][group]
  123.                 except:
  124.                         pass
  125.                 self.group_users.setdefault(gtype,{})[group] = []
  126.                 attr = self.dgattrs[gtype]['member_field']
  127.                 users = self.get_group_attr(group=group,gtype=gtype,attr=attr)
  128.                 if isinstance(users,basestring): users = [users]
  129.                 for user in users:
  130.                         cn = user.split(',')[0].split('=')[1]
  131.                         self.group_users[gtype][group].extend([cn])
  132.                 return self.group_users[gtype][group]


  133.         def add_users_to_group(self,users,group,gtype='user'):
  134.                 dn = self.get_group_attr(group,gtype,'distinguishedName')
  135.                 if isinstance(users,basestring): users = [users]
  136.                 for user in users:
  137.                         if user in self.get_users():
  138.                                 if group in self.get_groups(gtype=gtype):
  139.                                         if user not in self.get_group_users(group,gtype=gtype):
  140.                                                 self.conn.modify_s(dn,[(ldap.MOD_ADD,self.dgattrs[gtype]['member_field'],self.get_user_attr(user,'distinguishedName'))])
  141.                                         else:
  142.                                                 print user,'-> already in group %s skipping'%group
  143.                                 else:
  144.                                         print group,'-> invalid group skipping'
  145.                         else:
  146.                                 print user,'-> invalid user skipping'

  147.         def remove_users_from_group(self,users,group,gtype='user'):
  148.                 dn = self.get_group_attr(group,gtype,'distinguishedName')
  149.                 if isinstance(users,basestring): users = [users]
  150.                 for user in users:
  151.                         if user in self.get_users():
  152.                                 if group in self.get_groups(gtype=gtype):
  153.                                         if user in self.get_group_users(group,gtype=gtype):
  154.                                                 self.conn.modify_s(dn,[(ldap.MOD_DELETE,self.dgattrs[gtype]['member_field'],self.get_user_attr(user,'distinguishedName'))])
  155.                                         else:
  156.                                                 print user,'-> already not in group %s skipping'%group
  157.                                 else:
  158.                                         print group,'-> invalid group skipping'
  159.                         else:
  160.                                 print user,'-> invalid user skipping'

  161.         def change_users_group(self,users,source_group,target_group,gtype='user'):
  162.                 self.remove_users_from_group(users,source_group,gtype=gtype)
  163.                 self.add_users_to_group(users,target_group,gtype=gtype)


  164.         def get_group_attr(self,group,gtype='user',attr='cn'):
  165.                 if group not in self.get_groups(gtype=gtype): return
  166.                 dn = ','.join(["cn=%s"%group,self.dgattrs[gtype]['dn']])
  167.                 search_filter = self.dgattrs[gtype]['filter']
  168.                 ret = self.search(dn=dn,search_filter=search_filter,attrs=attr)
  169.                 try:
  170.                         ret[0][0][1][attr]
  171.                 except KeyError:
  172.                         return

  173.                 val = ret[0][0][1][attr]
  174.                 if len(val) == 1:
  175.                         return val[0]
  176.                 else:
  177.                         return val


  178.         def get_user_attr(self,user,attr='cn',return_dn=False):
  179.                 if user not in self.get_users(): return
  180.                 dn = self.dgattrs['user']['dn']
  181.                 ret = self.search(dn=dn,search_filter="(&(objectClass=user)(!(objectClass=computer))(cn=%s))"%user,attrs=[attr])
  182.                 try:
  183.                         ret[0][0][1][attr]
  184.                 except:
  185.                         if return_dn:
  186.                                 return (ret[0][0][0],None)
  187.                         return
  188.                 val = ret[0][0][1][attr]
  189.                 if len(val) == 1:
  190.                         if return_dn:
  191.                                 return (ret[0][0][0],val[0])
  192.                         return val[0]
  193.                 else:
  194.                         if return_dn:
  195.                                 return (ret[0][0][0],val)
  196.                         return val

  197.         def set_user_attr(self,user,attr,val):
  198.                 if user not in self.get_users(): return
  199.                 dn,current_val = self.get_user_attr(user,attr,return_dn=True)

  200.                 if current_val:
  201.                         current_val = current_val[0]
  202.                 else:
  203.                         current_val = ''
  204.                 ldif = modlist.modifyModlist({attr:current_val},{attr:val})
  205.                 self.conn.modify_s(dn,ldif)

阅读(2313) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~