-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoogleAnalyticsAccountsAudit.py
143 lines (128 loc) · 6.54 KB
/
GoogleAnalyticsAccountsAudit.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
"""A script to manage the Google Analytics Account Users."""
import json
import yaml
from googleapiclient.errors import HttpError
from googleapiclient.http import BatchHttpRequest
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from ServiceUtil import get_service
import AccountSummaries
from email.mime.text import MIMEText
import smtplib
from HpeLdapSearch import get_user_info
from WebPropertiesUsersUtility import get_webproperty_UserLinks,delete_prop_users
from ProfileUserLinksUtility import get_profile_user_links
def google_analytics_audit(analytics,cfg):
counter = 0
account_owner=""
emailMessage = str(cfg['DisclaimerMsg']+cfg['GARemoveMsg'] +cfg['GAcreate'])
try:
accounts = AccountSummaries.main()
myEmail = ['[email protected]']
for account in accounts.get('items', []):
print ('\n%s (%s) has (%d) properties\n' % (account.get('name'), account.get('id'), len(account.get('webProperties', []))))
if account.get('name') == "design@hpe":
account_owner=cfg['HPEDesignAccountOwner']
elif account.get('name') == "developer portal":
account_owner=cfg['HPEDEVAccountOwner']
elif account.get('name') == "Grommet":
account_owner=cfg['GrommetAccountOwner']
elif account.get('name') == "HPE GreenLake":
account_owner=cfg['HPEGreenLakeccountOwner']
elif account.get('name') == "HPE OneSphere":
account_owner=cfg['HPEOneSphereAccountOwner']
elif account.get('name') == "HPE OneView":
account_owner=cfg['OneViewAccountOwner']
elif account.get('name') == "hpe.global.dashboard":
account_owner=cfg['HPEGlobalDashccountOwner']
else:
account_owner="[email protected]"
for property in account.get('webProperties', []):
print (' %s (%s) [%s | %s]\n' % (property.get('name'), property.get('id'),property.get('websiteUrl'), property.get('level')))
print(' account owner %s\n' % account_owner)
try:
property_links = get_webproperty_UserLinks(analytics, account.get('id'), property.get('id'))
except HttpError as error:
# Handle API errors.
if error.resp.status == 403:
hpeEmailList = []
nonHpeEmailList = []
counter = 0
for view in property.get('profiles', []):
# Construct the Profile User Link.
links = get_profile_user_links(analytics, account.get('id'), property.get('id'), view.get('id'))
for property in links.get('items', []):
userRef = property.get('userRef')
domain = userRef.get('email').split('@')[1]
if domain == "hpe.com":
counter += 1
employee_details = get_user_info(userRef.get('email'),['cn'])
if not employee_details:
hpeEmailList.append(userRef.get('email'))
else:
#if userRef.get('email') and userRef.get('email') in myEmail and "gserviceaccount" not in userRef.get('email'):
if userRef.get('email') and "gserviceaccount" not in userRef.get('email'):
counter += 1
#delete_prop_users(analytics, account.get('id'), property.get('id'), propertyUserLink.get('id'))
#send_email(userRef.get('email'), emailMessage.format(property.get('name'), userRef.get('email'), account_owner ))
nonHpeEmailList.append(userRef.get('email'))
if counter == 0:
hpeEmailList = []
nonHpeEmailList = []
for propertyUserLink in property_links.get('items', []):
userRef = propertyUserLink.get('userRef', {})
domain = userRef.get('email').split('@')[1]
if domain == "hpe.com":
employee_details = get_user_info(userRef.get('email'),['cn'])
if not employee_details:
hpeEmailList.append(userRef.get('email'))
else:
#if userRef.get('email') and userRef.get('email') in myEmail and "gserviceaccount" not in userRef.get('email'):
if userRef.get('email') and "gserviceaccount" not in userRef.get('email'):
#delete_prop_users(analytics, account.get('id'), property.get('id'), propertyUserLink.get('id'))
#send_email(userRef.get('email'), emailMessage.format(property.get('name'), userRef.get('email'), account_owner ))
nonHpeEmailList.append(userRef.get('email'))
print(" HPE User(s) count to be removed is '{0}' and their email address are '{1}'\n" .format(len(hpeEmailList), hpeEmailList))
print(" Non HPE User(s) count to be removed is '{0}' and their email address are '{1}'\n" .format(len(nonHpeEmailList), nonHpeEmailList))
except TypeError as error:
# Handle errors in constructing a query.
print ('There was an error in constructing your query : %s' % error)
except HttpError as error:
# Handle API errors.
print ('There was an API error : %s : %s' % (error.resp.status, error.resp.reason))
return None
#
# Send email message of results to specified address
#
def send_email(address, output):
msg = MIMEText(output)
msg['Subject'] = "Google Analytics Account user audit"
msg['From'] = "[email protected]"
msg['To'] = address
# print("message",msg)
s = smtplib.SMTP('smtp3.hpe.com')
s.sendmail('[email protected]', address, msg.as_string())
s.quit()
def main():
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/analytics.manage.users'
with open('config.yaml', 'r') as ymlfile:
print("yaml", ymlfile)
try:
cfg = yaml.load(ymlfile, Loader=yaml.SafeLoader)
print(cfg['SecretKeyFile'])
except yaml.YAMLError as exc:
print(exc)
print ("inside Google Account Audit main")
# Authenticate and construct service.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=cfg['SecretKeyFile'])
# call the list_account_summaries function to Requests a list of all account summaries for the authorized user.
return google_analytics_audit(service,cfg)
if __name__ == '__main__':
main()