2010-10-27

导出Google Apps里所有的用户组和组员

Google Apps的管理功能很不错,但用户组多了不好管理,时常要拿出来晒晒,调整一下结构。这就经常需要把所有组和组员列出来,幸亏Google提供了API,懒人的办法就是用脚本搞定。下面是python示例,输出比较简单。知道了如何做,你可以自己改成输出csv或者任何其他格式,都会容易。多说无益,上代码。

#!/usr/bin/env python
# Author: xieyanbo@gmail.com
# dump_google_apps_mail_groups.py
# export mail groups and group members from Google Apps service

import gdata.apps.groups.service

def print_all_members(email, domain, password):
group_service = gdata.apps.groups.service.GroupsService(email=email,
domain=domain, password=password)
group_service.ProgrammaticLogin()

def print_members(group_id):
for user in group_service.RetrieveAllMembers(group_id):
print user['memberId']

def shrink(str, max=20):
if not str:
return ''
str = str.replace('\n', ' ').strip().decode('utf8')
if len(str) > max:
short = str[:max-3] + '...'
else:
short = str
return str.encode('utf8')

def print_groups(groups):
for group in groups:
gid = group['groupId']
print '%s, %s, %s' % (gid, group['groupName'],
shrink(group['description']))
print '='*60
print_members(gid)
print

groups = group_service.RetrieveAllGroups()
print_groups(groups)

def main():
from optparse import OptionParser
parser = OptionParser()

parser.add_option('-e', '--email')
parser.add_option('-d', '--domain')
parser.add_option('-p', '--password')
options, args = parser.parse_args()

if not options.email:
parser.error('need email address to login')
if not options.domain:
parser.error('need domain to login')
if not options.password:
import getpass
password = getpass.getpass('Password: ')
else:
password = options.password or login
print_all_members(options.email, options.domain, password)

if __name__ == '__main__':
main()