-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgam.py
executable file
·3666 lines (3539 loc) · 137 KB
/
gam.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# Google Apps Manager
#
# Copyright 2012 Dito, LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Google Apps Manager (GAM) is a command line tool which allows Administrators to control their Google Apps domain and accounts.
With GAM you can programatically create users, turn on/off services for users like POP and Forwarding and much more.
For more information, see http://code.google.com/p/google-apps-manager
"""
__author__ = '[email protected] (Jay Lee)'
__version__ = '2.3'
__license__ = 'Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)'
import sys, os, time, datetime, random, cgi, socket, urllib, csv, getpass, platform, re, webbrowser, pickle
import xml.dom.minidom
from sys import exit
import gdata.apps.service
import gdata.apps.emailsettings.service
import gdata.apps.adminsettings.service
import gdata.apps.groups.service
import gdata.apps.audit.service
try:
import gdata.apps.adminaudit.service
except ImportError:
pass
import gdata.apps.multidomain.service
import gdata.apps.orgs.service
import gdata.apps.res_cal.service
import gdata.calendar
import gdata.calendar.service
import gdata.apps.groupsettings.service
import gdata.apps.reporting.service
import gdata.auth
import atom
import gdata.contacts
import gdata.contacts.service
from hashlib import sha1
def showUsage():
doGAMVersion()
print '''
Usage: gam [OPTIONS]...
Google Apps Manager. Retrieve or set Google Apps domain,
user, group and alias settings. Exhaustive list of commands
can be found at: http://code.google.com/p/google-apps-manager/wiki
Examples:
gam info domain
gam create user jsmith firstname John lastname Smith password secretpass
gam update user jsmith suspended on
gam.exe update group announcements add member jsmith
...
'''
def getGamPath():
if os.name == 'windows':
divider = '\\'
else:
divider = '/'
return os.path.dirname(os.path.realpath(sys.argv[0]))+divider
def doGAMVersion():
print 'Google Apps Manager %s\r\n%s\r\nPython %s.%s.%s %s\r\n%s %s' % (__version__, __author__,
sys.version_info[0], sys.version_info[1], sys.version_info[2],
sys.version_info[3], platform.platform(), platform.machine())
def commonAppsObjInit(appsObj):
#Identify GAM to Google's Servers
appsObj.source = 'Google Apps Manager %s / %s / Python %s.%s.%s %s / %s %s /' % (__version__, __author__,
sys.version_info[0], sys.version_info[1], sys.version_info[2],
sys.version_info[3], platform.platform(), platform.machine())
#Show debugging output if debug.gam exists
if os.path.isfile(getGamPath()+'debug.gam'):
appsObj.debug = True
return appsObj
def tryOAuth(gdataObject):
global domain
oauth_filename = 'oauth.txt'
try:
oauth_filename = os.environ['OAUTHFILE']
except KeyError:
pass
if os.path.isfile(getGamPath()+oauth_filename):
oauthfile = open(getGamPath()+oauth_filename, 'rb')
domain = oauthfile.readline()[0:-1]
try:
token = pickle.load(oauthfile)
oauthfile.close()
except ImportError: # Deals with tokens created by windows on old GAM versions. Rewrites them with binary mode set
oauthfile = open(getGamPath()+oauth_filename, 'r')
domain = oauthfile.readline()[0:-1]
token = pickle.load(oauthfile)
oauthfile.close()
f = open(getGamPath()+oauth_filename, 'wb')
f.write('%s\n' % (domain,))
pickle.dump(token, f)
f.close()
gdataObject.domain = domain
gdataObject.SetOAuthInputParameters(gdata.auth.OAuthSignatureMethod.HMAC_SHA1, consumer_key=token.oauth_input_params._consumer.key, consumer_secret=token.oauth_input_params._consumer.secret)
token.oauth_input_params = gdataObject._oauth_input_params
gdataObject.SetOAuthToken(token)
return True
else:
return False
def getAppsObject():
apps = gdata.apps.service.AppsService()
if not tryOAuth(apps):
doRequestOAuth()
tryOAuth(apps)
apps = commonAppsObjInit(apps)
return apps
def getProfilesObject():
profiles = gdata.contacts.service.ContactsService(contact_list='domain')
profiles.ssl = True
if not tryOAuth(profiles):
doRequestOAuth()
tryOAuth(profiles)
profiles = commonAppsObjInit(profiles)
return profiles
def getCalendarObject():
calendars = gdata.calendar.service.CalendarService()
calendars.ssl = True
if not tryOAuth(calendars):
doRequestOAuth()
tryOAuth(calendars)
calendars = commonAppsObjInit(calendars)
return calendars
def getGroupSettingsObject():
groupsettings = gdata.apps.groupsettings.service.GroupSettingsService()
if not tryOAuth(groupsettings):
doRequestOAuth()
tryOAuth(groupsettings)
groupsettings = commonAppsObjInit(groupsettings)
return groupsettings
def getEmailSettingsObject():
emailsettings = gdata.apps.emailsettings.service.EmailSettingsService()
if not tryOAuth(emailsettings):
doRequestOAuth()
tryOAuth(emailsettings)
emailsettings = emailsettings = commonAppsObjInit(emailsettings)
return emailsettings
def getAdminSettingsObject():
global domain
adminsettings = gdata.apps.adminsettings.service.AdminSettingsService()
if not tryOAuth(adminsettings):
doRequestOAuth()
tryOAuth(adminsettings)
adminsettings = commonAppsObjInit(adminsettings)
return adminsettings
def getGroupsObject():
global domain
groupsObj = gdata.apps.groups.service.GroupsService()
if not tryOAuth(groupsObj):
doRequestOAuth()
tryOAuth(groupsObj)
groupsObj = commonAppsObjInit(groupsObj)
return groupsObj
def getAuditObject():
auditObj = gdata.apps.audit.service.AuditService()
if not tryOAuth(auditObj):
doRequestOAuth()
tryOAuth(auditObj)
auditObj = commonAppsObjInit(auditObj)
return auditObj
def getAdminAuditObject():
try:
adminAuditObj = gdata.apps.adminaudit.service.AdminAuditService()
except AttributeError:
print "gam audit admin commands require Python 2.6 or 2.7"
sys.exit(3)
if not tryOAuth(adminAuditObj):
doRequestOAuth()
tryOAuth(adminAuditObj)
adminAuditObj = commonAppsObjInit(adminAuditObj)
return adminAuditObj
def getMultiDomainObject():
multidomainObj = gdata.apps.multidomain.service.MultiDomainService()
if not tryOAuth(multidomainObj):
doRequestOAuth()
tryOAuth(multidomainObj)
multidomainObj = commonAppsObjInit(multidomainObj)
return multidomainObj
def getOrgObject():
orgObj = gdata.apps.orgs.service.OrganizationService()
if not tryOAuth(orgObj):
doRequestOAuth()
tryOAuth(orgObj)
orgObj = commonAppsObjInit(orgObj)
return orgObj
def getResCalObject():
resCalObj = gdata.apps.res_cal.service.ResCalService()
if not tryOAuth(resCalObj):
doRequestOAuth()
tryOAuth(resCalObj)
resCalObj = commonAppsObjInit(resCalObj)
return resCalObj
def getRepObject():
repObj = gdata.apps.reporting.service.ReportService()
if not tryOAuth(repObj):
doRequestOAuth()
tryOAuth(repObj)
repObj = commonAppsObjInit(repObj)
return repObj
def _reporthook(numblocks, blocksize, filesize, url=None):
#print "reporthook(%s, %s, %s)" % (numblocks, blocksize, filesize)
base = os.path.basename(url)
#XXX Should handle possible filesize=-1.
try:
percent = min((numblocks*blocksize*100)/filesize, 100)
except:
percent = 100
if numblocks != 0:
sys.stdout.write("\b"*70)
sys.stdout.write(str(percent)+'% ')
#print str(percent)+"%\b\b"
def geturl(url, dst):
if sys.stdout.isatty():
urllib.urlretrieve(url, dst,
lambda nb, bs, fs, url=url: _reporthook(nb,bs,fs,url))
sys.stdout.write('\n')
else:
urllib.urlretrieve(url, dst)
def showReport():
report = sys.argv[2].lower()
date = page = None
if len(sys.argv) > 3:
date = sys.argv[3]
rep = getRepObject()
report_data = rep.retrieve_report(report=report, date=date)
sys.stdout.write(report_data)
def doDelegates(users):
emailsettings = getEmailSettingsObject()
if sys.argv[4].lower() == 'to':
delegate = sys.argv[5].lower()
#delegate needs to be a full email address, tack
#on domain of 1st user if there isn't one
if not delegate.find('@') > 0:
delegate_domain = domain.lower()
delegate_email = '%s@%s' % (delegate, delegate_domain)
else:
delegate_domain = delegate[delegate.find('@')+1:].lower()
delegate_email = delegate
else:
showUsage()
exit(6)
count = len(users)
i = 1
for delegator in users:
if delegator.find('@') > 0:
delegator_domain = delegator[delegator.find('@')+1:].lower()
delegator_email = delegator
delegator = delegator[:delegator.find('@')]
else:
delegator_domain = domain.lower()
delegator_email = '%s@%s' % (delegator, delegator_domain)
emailsettings.domain = delegator_domain
print "Giving %s delegate access to %s (%s of %s)" % (delegate_email, delegator_email, i, count)
delete_alias = False
if delegate_domain == delegator_domain:
use_delegate_address = delegate_email
else:
# Need to use an alias in delegator domain, first check to see if delegate already has one...
multi = getMultiDomainObject()
aliases = multi.GetUserAliases(delegate_email)
found_alias_in_delegator_domain = False
for alias in aliases:
alias_domain = alias['aliasEmail'][alias['aliasEmail'].find('@')+1:].lower()
if alias_domain == delegator_domain:
use_delegate_address = alias['aliasEmail']
print ' Using existing alias %s for delegation' % use_delegate_address
found_alias_in_delegator_domain = True
break
if not found_alias_in_delegator_domain:
delete_alias = True
use_delegate_address = '%s@%s' % (''.join(random.sample('abcdefghijklmnopqrstuvwxyz0123456789', 10)), delegator_domain)
print ' Giving %s temporary alias %s for delegation' % (delegate_email, use_delegate_address)
multi.CreateAlias(user_email=delegate_email, alias_email=use_delegate_address)
time.sleep(5)
try:
emailsettings.CreateDelegate(delegate=use_delegate_address, delegator=delegator)
except gdata.apps.service.AppsForYourDomainException, e:
print e
time.sleep(10)
sys.exit(5)
time.sleep(10)
if delete_alias:
print ' Deleting temporary alias...'
multi.DeleteAlias(use_delegate_address)
i = i + 1
def getDelegates(users):
emailsettings = getEmailSettingsObject()
csv_format = False
try:
if sys.argv[5].lower() == 'csv':
csv_format = True
except IndexError:
pass
for user in users:
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain
sys.stderr.write("Getting delegates for %s...\n" % (user + '@' + emailsettings.domain))
try:
delegates = emailsettings.GetDelegates(delegator=user)
except gdata.apps.service.AppsForYourDomainException, e:
sys.stderr.write(e)
for delegate in delegates:
if csv_format:
print '%s,%s,%s' % (user + '@' + emailsettings.domain, delegate['address'], delegate['status'])
else:
print "Delegator: %s\n Delegate: %s\n Status: %s\n Delegate Email: %s\n Delegate ID: %s\n" % (user, delegate['delegate'], delegate['status'], delegate['address'], delegate['delegationId'])
def deleteDelegate(users):
emailsettings = getEmailSettingsObject()
delegate = sys.argv[5]
if not delegate.find('@') > 0:
if users[0].find('@') > 0:
delegatedomain = users[0][users[0].find('@')+1:]
else:
delegatedomain = domain
delegate = delegate+'@'+delegatedomain
count = len(users)
i = 1
for user in users:
print "Deleting %s delegate access to %s (%s of %s)" % (delegate, user, i, count)
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.DeleteDelegate(delegate=delegate, delegator=user)
i = i + 1
def deleteCalendar(users):
del_cal = sys.argv[5]
cal = getCalendarObject()
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = 'https://www.google.com/calendar/feeds/%s/allcalendars/full/%s' % (user+'@'+user_domain, del_cal)
try:
calendar_entry = cal.GetCalendarListEntry(uri)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
continue
try:
edit_uri = calendar_entry.GetEditLink().href
cal.DeleteCalendarEntry(edit_uri)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
def addCalendar(users):
add_cal = sys.argv[5]
cal = getCalendarObject()
selected = hidden = color = None
i = 6
while i < len(sys.argv):
if sys.argv[i].lower() == 'selected':
if sys.argv[i+1].lower() == 'true':
selected = 'true'
elif sys.argv[i+1].lower() == 'false':
selected = 'false'
else:
showUsage()
print 'Value for selected must be true or false, not %s' % sys.argv[i+1]
exit(4)
i = i + 2
elif sys.argv[i].lower() == 'hidden':
if sys.argv[i+1].lower() == 'true':
hidden = 'true'
elif sys.argv[i+1].lower() == 'false':
calendar_entry.hidden = gdata.calendar.Hidden(value='false')
hidden = 'false'
else:
showUsage()
print 'Value for hidden must be true or false, not %s' % sys.argv[i+1]
exit(4)
i = i + 2
elif sys.argv[i].lower() == 'color':
color = sys.argv[i+1]
i = i + 2
else:
showUsage()
print '%s is not a valid argument for "gam add calendar"' % sys.argv[i]
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
calendar_entry = gdata.calendar.CalendarListEntry()
try:
insert_uri = 'https://www.google.com/calendar/feeds/%s/allcalendars/full' % (user+'@'+user_domain)
calendar_entry.id = atom.Id(text=add_cal)
calendar_entry.hidden = gdata.calendar.Hidden(value=hidden)
calendar_entry.selected = gdata.calendar.Selected(value=selected)
if color != None:
calendar_entry.color = gdata.calendar.Color(value=color)
cal.InsertCalendarSubscription(insert_uri=insert_uri, calendar=calendar_entry)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
continue
def updateCalendar(users):
update_cal = sys.argv[5]
cal = getCalendarObject()
selected = hidden = color = None
i = 6
while i < len(sys.argv):
if sys.argv[i].lower() == 'selected':
if sys.argv[i+1].lower() == 'true':
selected = 'true'
elif sys.argv[i+1].lower() == 'false':
selected = 'false'
else:
showUsage()
print 'Value for selected must be true or false, not %s' % sys.argv[i+1]
exit(4)
i = i + 2
elif sys.argv[i].lower() == 'hidden':
if sys.argv[i+1].lower() == 'true':
hidden = 'true'
elif sys.argv[i+1].lower() == 'false':
calendar_entry.hidden = gdata.calendar.Hidden(value='false')
hidden = 'false'
else:
showUsage()
print 'Value for hidden must be true or false, not %s' % sys.argv[i+1]
exit(4)
i = i + 2
elif sys.argv[i].lower() == 'color':
color = sys.argv[i+1]
i = i + 2
else:
showUsage()
print '%s is not a valid argument for "gam add calendar"' % sys.argv[i]
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = 'https://www.google.com/calendar/feeds/%s/allcalendars/full/%s' % (user+'@'+user_domain, update_cal)
try:
calendar_entry = cal.GetCalendarListEntry(uri)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
continue
if selected != None:
calendar_entry.selected = gdata.calendar.Selected(value=selected)
if hidden != None:
calendar_entry.hidden = gdata.calendar.Hidden(value=hidden)
if color != None:
calendar_entry.color = gdata.calendar.Color(value=color)
try:
edit_uri = calendar_entry.GetEditLink().href
cal.UpdateCalendar(calendar_entry)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
continue
def doCalendarShowACL():
show_cal = sys.argv[2]
cal = getCalendarObject()
uri = 'https://www.google.com/calendar/feeds/%s/acl/full' % (show_cal)
feed = cal.GetCalendarAclFeed(uri=uri)
print feed.title.text
for i, a_rule in enumerate(feed.entry):
print ' Scope %s - %s' % (a_rule.scope.type, a_rule.scope.value)
print ' Role: %s' % (a_rule.title.text)
print ''
def doCalendarAddACL():
use_cal = sys.argv[2]
role = sys.argv[4].lower()
if role != 'freebusy' and role != 'read' and role != 'editor' and role != 'owner':
print 'Error: Role must be freebusy, read, editor or owner. Not %s' % role
exit (33)
user_to_add = sys.argv[5]
cal = getCalendarObject()
rule = gdata.calendar.CalendarAclEntry()
rule.scope = gdata.calendar.Scope(value=user_to_add)
rule.scope.type = 'user'
roleValue = 'http://schemas.google.com/gCal/2005#%s' % (role)
rule.role = gdata.calendar.Role(value=roleValue)
aclUrl = '/calendar/feeds/%s/acl/full' % use_cal
try:
returned_rule = cal.InsertAclEntry(rule, aclUrl)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
def doCalendarUpdateACL():
use_cal = sys.argv[2]
role = sys.argv[4].lower()
if role != 'freebusy' and role != 'read' and role != 'editor' and role != 'owner':
print 'Error: Role must be freebusy, read, editor or owner. Not %s' % role
exit (33)
user_to_add = sys.argv[5]
cal = getCalendarObject()
rule = gdata.calendar.CalendarAclEntry()
if user_to_add.lower() == 'domain':
rule_value = cal.domain
rule_type = 'domain'
elif user_to_add.lower() == 'default':
rule_value = None
rule_type = 'default'
else:
rule_value = user_to_add
rule_type = 'user'
rule.scope = gdata.calendar.Scope(value=rule_value)
rule.scope.type = rule_type
roleValue = 'http://schemas.google.com/gCal/2005#%s' % (role)
rule.role = gdata.calendar.Role(value=roleValue)
if rule_type != 'default':
aclUrl = '/calendar/feeds/%s/acl/full/%s%%3A%s' % (use_cal, rule_type, rule_value)
else:
aclUrl = '/calendar/feeds/%s/acl/full/default' % (use_cal)
try:
returned_rule = cal.UpdateAclEntry(edit_uri=aclUrl, updated_rule=rule)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
def doCalendarDelACL():
use_cal = sys.argv[2]
if sys.argv[4].lower() != 'user':
print 'invalid syntax'
exit(9)
user_to_del = sys.argv[5].lower()
cal = getCalendarObject()
uri = 'https://www.google.com/calendar/feeds/%s/acl/full' % (use_cal)
feed = cal.GetCalendarAclFeed(uri=uri)
found_rule = False
for i, a_rule in enumerate(feed.entry):
if a_rule.scope.value.lower() == user_to_del:
found_rule = True
result = cal.DeleteAclEntry(a_rule.GetEditLink().href)
if not found_rule:
print 'Error: that object does not seem to have access to that calendar'
exit(34)
def doProfile(users):
if sys.argv[4].lower() == 'share' or sys.argv[4].lower() == 'shared':
indexed = 'true'
elif sys.argv[4].lower() == 'unshare' or sys.argv[4].lower() == 'unshared':
indexed = 'false'
profiles = getProfilesObject()
count = len(users)
i = 1
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
print 'Setting Profile Sharing to %s for %s@%s (%s of %s)' % (indexed, user, user_domain, i, count)
uri = '/m8/feeds/profiles/domain/%s/full/%s?v=3.0' % (user_domain, user)
try:
user_profile = profiles.GetProfile(uri)
user_profile.extension_elements[2].attributes['indexed'] = indexed
profiles.UpdateProfile(user_profile.GetEditLink().href, user_profile)
except gdata.service.RequestError, e:
print 'Error for %s@%s: %s - %s' % (user, user_domain, e[0]['body'], e[0]['reason'])
i += 1
def showProfile(users):
profiles = getProfilesObject()
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = '/m8/feeds/profiles/domain/%s/full/%s?v=3.0' % (user_domain, user)
try:
user_profile = profiles.GetProfile(uri)
except gdata.service.RequestError, e:
print 'Error for %s@%s: %s - %s' % (user, user_domain, e[0]['body'], e[0]['reason'])
continue
indexed = user_profile.extension_elements[2].attributes['indexed']
print '''User: %s@%s
Profile Shared: %s''' % (user, user_domain, indexed)
def doPhoto(users):
filename = sys.argv[5]
profiles = getProfilesObject()
i = 1
count = len(users)
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = '/m8/feeds/profiles/domain/%s/full/%s?v=3' % (user_domain, user)
try:
user_profile = profiles.GetProfile(uri)
photo_uri = user_profile.link[0].href
try:
if sys.argv[6].lower() == 'nooverwrite':
etag = user_profile.link[0].extension_attributes['{http://schemas.google.com/g/2005}etag']
print 'Not overwriting existing photo for %s@%s' % (user, user_domain)
continue
except IndexError:
pass
except KeyError:
pass
print "Updating photo for %s (%s of %s)" % (user+'@'+user_domain, i, count)
results = profiles.ChangePhoto(media=filename, content_type='image/jpeg', contact_entry_or_url=photo_uri)
except gdata.service.RequestError, e:
print 'Error for %s@%s: %s - %s' % (user, user_domain, e[0]['body'], e[0]['reason'])
i = i + 1
def getPhoto(users):
profiles = getProfilesObject()
i = 1
count = len(users)
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = '/m8/feeds/profiles/domain/%s/full/%s?v=3' % (user_domain, user)
try:
user_profile = profiles.GetProfile(uri)
try:
etag = user_profile.link[0].extension_attributes['{http://schemas.google.com/g/2005}etag']
except KeyError:
print ' No photo for %s@%s' % (user, user_domain)
i = i + 1
continue
photo_uri = user_profile.link[0].href
filename = '%s-%s.jpg' % (user, user_domain)
print "Saving photo for %s to %s (%s of %s)" % (user+'@'+user_domain, filename, i, count)
photo = profiles.GetPhoto(contact_entry_or_url=photo_uri)
except gdata.service.RequestError, e:
print ' Error for %s@%s: %s - %s' % (user, user_domain, e[0]['body'], e[0]['reason'])
i = i + 1
continue
photo_file = open(filename, 'wb')
photo_file.write(photo)
photo_file.close()
i = i + 1
def deletePhoto(users):
profiles = getProfilesObject()
i = 1
count = len(users)
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = '/m8/feeds/profiles/domain/%s/full/%s?v=3' % (user_domain, user)
try:
user_profile = profiles.GetProfile(uri)
photo_uri = user_profile.link[0].href
print "Deleting photo for %s (%s of %s)" % (user+'@'+user_domain, i, count)
results = profiles.DeletePhoto(photo_uri)
except gdata.service.RequestError, e:
print 'Error for %s@%s: %s - %s' % (user, user_domain, e[0]['body'], e[0]['reason'])
i = i + 1
def showCalendars(users):
cal = getCalendarObject()
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = '/calendar/feeds/%s/allcalendars/full' % (user+'@'+user_domain,)
feed = cal.GetAllCalendarsFeed(uri)
print '%s' % feed.title.text
for i, a_calendar in enumerate(feed.entry):
print ' Name: %s' % str(a_calendar.title.text)
print ' ID: %s' % urllib.unquote(str(a_calendar.id.text).rpartition('/')[2])
print ' Access Level: %s' % str(a_calendar.access_level.value)
print ' Timezone: %s' % str(a_calendar.timezone.value)
print ' Hidden: %s' % str(a_calendar.hidden.value)
print ' Selected: %s' % str(a_calendar.selected.value)
print ' Color: %s' % str(a_calendar.color.value)
print ''
def showCalSettings(users):
cal = getCalendarObject()
for user in users:
if user.find('@') > 0:
user_domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
user_domain = domain
uri = '/calendar/feeds/%s/settings' % (user+'@'+user_domain)
#uri = '/calendar/feeds/default/settings'
try:
feed = cal.GetCalendarSettingsFeed(uri)
except gdata.service.RequestError, e:
print 'Error: %s - %s' % (e[0]['reason'], e[0]['body'])
sys.exit(59)
print feed.title.text
for i, a_setting in enumerate(feed.entry):
print ' %s: %s' % (a_setting.extension_elements[0].attributes['name'], a_setting.extension_elements[0].attributes['value'])
def doImap(users):
checkTOS = True
if sys.argv[4].lower() == 'on':
enable = True
elif sys.argv[4].lower() == 'off':
enable = False
if len(sys.argv) > 5 and sys.argv[5] == 'noconfirm':
checkTOS = False
emailsettings = getEmailSettingsObject()
count = len(users)
i = 1
for user in users:
print "Setting IMAP Access to %s for %s (%s of %s)" % (str(enable), user, i, count)
if checkTOS:
if not hasAgreed2TOS(user):
print ' Warning: IMAP has been enabled but '+user+' has not logged into GMail to agree to the terms of service (captcha). IMAP will not work until they do.'
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.UpdateImap(username=user, enable=enable)
i = i + 1
def getImap(users):
emailsettings = getEmailSettingsObject()
for user in users:
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain
imapsettings = emailsettings.GetImap(username=user)
print 'User %s IMAP Enabled:%s' % (user, imapsettings['enable'])
def doPop(users):
checkTOS = True
if sys.argv[4].lower() == 'on':
enable = True
elif sys.argv[4].lower() == 'off':
enable = False
i = 5
while i < len(sys.argv):
if sys.argv[i].lower() == 'for':
if sys.argv[i+1].lower() == 'allmail':
enable_for = 'ALL_MAIL'
i = i + 2
elif sys.argv[i+1].lower() == 'newmail':
enable_for = 'MAIL_FROM_NOW_ON'
i = i + 2
elif sys.argv[i].lower() == 'action':
if sys.argv[i+1].lower() == 'keep':
action = 'KEEP'
i = i + 2
elif sys.argv[i+1].lower() == 'archive':
action = 'ARCHIVE'
i = i + 2
elif sys.argv[i+1].lower() == 'delete':
action = 'DELETE'
i = i + 2
elif sys.argv[i].lower() == 'noconfirm':
checkTOS = False
i = i + 1
else:
showUsage()
sys.exit(2)
emailsettings = getEmailSettingsObject()
count = len(users)
i = 1
for user in users:
print "Setting POP Access to %s for %s (%s of %s)" % (str(enable), user, i, count)
if checkTOS:
if not hasAgreed2TOS(user):
print ' Warning: POP has been enabled but '+user+' has not logged into GMail to agree to the terms of service (captcha). POP will not work until they do.'
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.UpdatePop(username=user, enable=enable, enable_for=enable_for, action=action)
i = i + 1
def getPop(users):
emailsettings = getEmailSettingsObject()
for user in users:
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain
popsettings = emailsettings.GetPop(username=user)
print 'User %s POP Enabled:%s Action:%s' % (user, popsettings['enable'], popsettings['action'])
def doSendAs(users):
sendas = sys.argv[4]
sendasName = sys.argv[5]
make_default = reply_to = None
i = 6
while i < len(sys.argv):
if sys.argv[i].lower() == 'default':
make_default = True
i = i + 1
elif sys.argv[i].lower() == 'replyto':
reply_to = sys.argv[i+1]
i = i + 2
else:
showUsage()
sys.exit(2)
emailsettings = getEmailSettingsObject()
if sendas.find('@') < 0:
sendas = sendas+'@'+domain
count = len(users)
i = 1
for user in users:
print "Allowing %s to send as %s (%s of %s)" % (user, sendas, i, count)
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.CreateSendAsAlias(username=user, name=sendasName, address=sendas, make_default=make_default, reply_to=reply_to)
i = i + 1
def showSendAs(users):
emailsettings = getEmailSettingsObject()
for user in users:
print '%s has the following send as aliases:' % user
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain
sendases = emailsettings.GetSendAsAlias(username=user)
for sendas in sendases:
if sendas['isDefault'] == 'true':
default = 'yes'
else:
default = 'no'
if sendas['replyTo']:
replyto = ' Reply To:<'+sendas['replyTo']+'>'
else:
replyto = ''
if sendas['verified'] == 'true':
verified = 'yes'
else:
verified = 'no'
print ' "%s" <%s>%s Default:%s Verified:%s' % (sendas['name'], sendas['address'], replyto, default, verified)
print ''
def doLanguage(users):
language = sys.argv[4].lower()
emailsettings = getEmailSettingsObject()
count = len(users)
i = 1
for user in users:
print "Setting the language for %s to %s (%s of %s)" % (user, language, i, count)
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.UpdateLanguage(username=user, language=language)
i = i + 1
def doUTF(users):
if sys.argv[4].lower() == 'on':
SetUTF = True
elif sys.argv[4].lower() == 'off':
SetUTF = False
emailsettings = getEmailSettingsObject()
count = len(users)
i = 1
for user in users:
print "Setting UTF-8 to %s for %s (%s of %s)" % (str(SetUTF), user, i, count)
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.UpdateGeneral(username=user, unicode=SetUTF)
i = i + 1
def doPageSize(users):
if sys.argv[4] == '25':
PageSize = '25'
elif sys.argv[4] == '50':
PageSize = '50'
elif sys.argv[4] == '100':
PageSize = '100'
else:
showUsage()
sys.exit(2)
emailsettings = getEmailSettingsObject()
count = len(users)
i = 1
for user in users:
print "Setting Page Size to %s for %s (%s of %s)" % (PageSize, user, i, count)
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.UpdateGeneral(username=user, page_size=PageSize)
i = i + 1
def doShortCuts(users):
if sys.argv[4].lower() == 'on':
SetShortCuts = True
elif sys.argv[4].lower() == 'off':
SetShortCuts = False
emailsettings = getEmailSettingsObject()
count = len(users)
i = 1
for user in users:
print "Setting Keyboard Short Cuts to %s for %s (%s of %s)" % (str(SetShortCuts), user, i, count)
if user.find('@') > 0:
emailsettings.domain = user[user.find('@')+1:]
user = user[:user.find('@')]
else:
emailsettings.domain = domain #make sure it's back at default domain
emailsettings.UpdateGeneral(username=user, shortcuts=SetShortCuts)
i = i + 1
def doAdminAudit():
i = 3
admin = event = start_date = end_date = None
while i < len(sys.argv):
if sys.argv[i].lower() == 'admin':
admin = sys.argv[i+1]
i = i + 2
elif sys.argv[i].lower() == 'event':
event = sys.argv[i+1]
i = i + 2
elif sys.argv[i].lower() == 'start_date':
start_date = sys.argv[i+1]
i = i + 2
elif sys.argv[i].lower() == 'end_date':
end_date = sys.argv[i+1]
i = i + 2
else:
showUsage()
sys.exit(2)
orgs = getOrgObject()
customer_id = orgs.RetrieveCustomerId()['customerId']
aa = getAdminAuditObject()
results = aa.retrieve_audit(customer_id=customer_id, admin=admin, event=event, start_date=start_date, end_date=end_date)
#for result in results['items']:
# pp.pprint(result)
# print ''
print results
sys.exit(0)
for result in results['items']:
#print result['events'][0]['name']