需求:公司每次有新员工入职的时候,都需要手动的把这些人加入相应的所在部门的邮件组,以方便他们能接收到部门领导发的最新指示。两三个人还好说,但是人多了手动一个一个的添加就没意思了。所以为了不想再做这些无用功,也为了自动化运维。所以编写了下面的代码。欢迎各位大神提出宝贵意见。
提示:跟据HR数据提取的人员信息
1 #!/usr/bin/python 2 # coding:utf-8 3 4 import sys 5 sys.path.append('/sw/systems/shared/python') 6 from DB import DB 7 con,cur = DB().connect() 8 9 from Company import Company #导入公司员工模块 10 company = Company() 11 users = company.employees #获取所有人员 12 departments = company.departments #获取所有人员所在的部门 13 14 from AD import AD #导入AD模块 15 ad = AD() 16 ad_users = ad.get_users() #获取所有ad域用户 17 18 user_list = {} 19 for key in users: 20 city = users[key]['location_code'].lower() 21 dep = users[key]['department'].lower() 22 username = users[key]['username'].strip() 23 24 if dep and city: 25 user_list.setdefault(dep,[]) 26 user_list[dep].append(username) 27 user_list.setdefault(dep+city,[]) #以部门+城市命令形成新的邮件组 hrbj 28 user_list[dep+city].append(username) 29 user_list.setdefault('base%s' %city,[]) 30 user_list['base%s' % city].append(username) 31 if username not in ['cbremble','nkovalevich','nrich','isugarman']: #排除高管 32 user_list.setdefault('attendance%s' % city,[]) 33 user_list['attendance%s'% city].append(username) 34 35 36 user_list.setdefault('prod',[]) 37 user_list.setdefault('prod%s' % city,[]) 38 user_list['prod%s'% city].append(username) 39 user_list['prod'].append(username) 40
#获取目前正在使用的邮箱组信息 41 def mail_forward(): 42 query = """ SELECT name,forward_name from mail.forward """ 43 cur.execute(query) 44 results = cur.fetchall() 45 forwards = {} 46 for result in results: 47 name = result['name'] 48 forward_name = result['forward_name'].lower().strip() 49 forwards.setdefault(name,[]) 50 forwards[name].append(forward_name) 51 return forwards 52 53 forwards = mail_forward() 54 55 try: 56 for dep in user_list: 57 if dep in forwards.keys(): 58 if dep: 59 need_add_alias = set(user_list[dep]) - set(forwards[dep]) #用hr数据库所有部门的人员和邮件数据库所有以部门命名的邮件组做比较 60 else: 61 need_add_alias = user_list[dep] 62 if need_add_alias: 63 for user in need_add_alias: 64 if user not in ad_users: #判断用户是否在AD里 65 pass 66 else: 67 add_forward = """insert ignore into mail.forward(name,forward_name,status,description) values ('%s','%s','Enabled','script import') """ % (dep,user) 68 cur.execute(add_forward) 69 con.commit() 70 except Exception,e: 71 print type(e),e