Skip to content

Instantly share code, notes, and snippets.

@rca
Created August 5, 2013 19:12
Show Gist options
  • Save rca/6158559 to your computer and use it in GitHub Desktop.
Save rca/6158559 to your computer and use it in GitHub Desktop.
Dump addresses from a google group
#!/usr/bin/env python
"""python dump_google_group [options] [[email protected] [filename]]
Dump addresses from a Google Group
==================================
This script allows you to easily retrieve the addresses in a Google Group. You
will need to have an administrator account for the Google Apps domain.
First, store your credentials to a file. Create the credentials file with the
command:
python dump_google_group credentials > credentials.txt
You will be prompted for your username and password and the credentials file
will be written. NOTE: the file will be written as a base64-encoded string.
This is simply to prevent an innocent peek at the file and is in no way meant
to secure your password in any way. Set the permissions on this file so only
you can read it:
chmod 0600 credentials.txt
Listing groups
--------------
You can list all the groups in a Google Apps account with the following:
python dump_google_group -d mydomain.tld
Dump addresses in group
-----------------------
python dump_google_group -d mydomain.tld [email protected]
Compare addresses in group with addresses in file
-------------------------------------------------
This script can also compare addresses in a file with addresses in a group and
showing you the changes that need to be made for them to match:
python dump_google_group -d mydomain.tld [email protected] filename
"""
import fileinput
import getpass
import os
import sys
from cStringIO import StringIO
from optparse import OptionParser
import gdata.apps.groups.client
from gdata.apps.groups import data
CREDENTIALS = os.environ.get('CREDENTIALS', 'credentials.txt')
def dump_credentials():
sys.stderr.write('username: ')
sys.stderr.flush()
username = sys.stdin.readline().strip()
password = getpass.getpass('password: ')
print ('{},{}'.format(username, password)).encode('base64')
def get_credentials(path):
f = open(path)
return f.readline().strip().decode('base64').split(',')
class DumpGroup(object):
def __init__(self):
self.parser = OptionParser(__doc__)
self._fill_parser()
self.options, self.args = self.parser.parse_args()
def _fill_parser(self):
self.parser.add_option('-c', '--credentials', default=CREDENTIALS)
self.parser.add_option('-d', '--domain')
def run(self):
if self.args and self.args[0] == 'credentials':
return dump_credentials()
credentials = self.options.credentials
try:
user, password = get_credentials(credentials)
except TypeError:
self.parser.print_help()
print 'Error: Credentials not found at {}'.format(credentials)
return -1
if not self.options.domain:
self.parser.print_help()
print 'Error: No domain'
return -1
domain = self.options.domain
group_client = (gdata.apps.groups.client
.GroupsProvisioningClient(domain=domain))
group_client.ClientLogin(email=user, password=password, source='apps')
if not self.args:
print 'Run the command with a group:'
response = group_client.RetrieveAllGroups()
groups = filter(
lambda x: isinstance(x, data.GroupEntry),
response.get_elements())
print 'Domain groups (%d):' % len(groups)
for group in groups:
print group.group_id
return -1
group_email_address = self.args.pop(0)
close = False
new_emails = []
# if there are additional arguments process them as files or else
# get emails from stdin
f = None
if len(self.args) > 1:
f = fileinput.input(self.args)
elif len(self.args) == 1:
f = fileinput.input(self.args[0])
if f:
# get all input email addresses
for line in f:
line = line.strip().lower()
if line == '':
continue
new_emails.append(line)
# get all email addresses in group
response = group_client.RetrieveAllMembers(group_email_address)
members = filter(
lambda x: isinstance(x, data.GroupMemberEntry),
response.get_elements())
emails = [member.member_id for member in members]
# print out current email addresses
print "Email addresses currently on Google (%d):" % len(emails)
for email in sorted(emails):
print email
print ''
if new_emails:
print "Updated addresses (%d):" % len(new_emails)
for email in sorted(new_emails):
print email
print ''
removed_emails = set(emails) - set(new_emails)
print "Addresses to remove (%d):" % len(removed_emails)
for email in sorted(removed_emails):
print email
print ''
added_emails = set(new_emails) - set(emails)
print "Addresses to add (%d):" % len(added_emails)
for email in sorted(added_emails):
print email
print ''
if __name__ == '__main__':
update_group = DumpGroup()
try:
sys.exit(update_group.run() or 0)
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment