-
Notifications
You must be signed in to change notification settings - Fork 12
/
createCsvOfUsers.py
162 lines (146 loc) · 5.47 KB
/
createCsvOfUsers.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
#!/usr/bin/env python
# Requires Python 2.7+
# Sample Usage:
# python createCsvOfUsers.py -u <portal> -o <username> -s <password>
# -f <filename>
import urllib
import json
import argparse
import csv
def generateToken(username, password, portalUrl):
'''Retrieves a token to be used with API requests.'''
parameters = urllib.urlencode(
{'username' : username, 'password' : password, 'client' : 'referer',
'referer': portalUrl, 'expiration': 60, 'f' : 'json'}
)
response = urllib.urlopen(portalUrl + '/sharing/rest/generateToken?',
parameters).read()
try:
jsonResponse = json.loads(response)
if 'token' in jsonResponse:
return jsonResponse['token']
elif 'error' in jsonResponse:
print(jsonResponse['error']['message'])
for detail in jsonResponse['error']['details']:
print(detail)
except ValueError, e:
print('An unspecified error occurred.')
print(e)
def getRoles(token, portalUrl):
'''Get the custom roles available in the portal.'''
## Does not handle more than 100 roles.
parameters = urllib.urlencode({
'token': token, 'f': 'json', 'num': 100
})
request = '{}/sharing/rest/portals/self/roles?{}'.format(
portalUrl, parameters
)
roles = json.loads(urllib.urlopen(request).read())
return roles
def getUsers(token, portalUrl):
'''
Returns a list of all users in the organization (requires admin access).
'''
def __portalId__(token, portalUrl):
'''
Return the id of the portal. If null, then this is the
default portal for anonymous and non-organizational users.
'''
parameters = urllib.urlencode(
{'token': token, 'f': 'json'}
)
request = '{}/sharing/rest/portals/self?{}'.format(
portalUrl, parameters
)
response = json.loads(urllib.urlopen(request).read())
return response['id']
def __users__(portalId, start=0):
'''Retrieve a single page of users.'''
parameters = urllib.urlencode(
{'token': token, 'f': 'json', 'start': start, 'num': 100}
)
request = '{}/sharing/rest/portals/{}/users?{}'.format(
portalUrl, portalId, parameters
)
users = json.loads(urllib.urlopen(request).read())
return users
portalId = __portalId__(token, portalUrl)
allUsers = []
users = __users__(portalId)
for user in users['users']:
allUsers.append(user)
while users['nextStart'] > 0:
users = __users__(portalId, users['nextStart'])
for user in users['users']:
allUsers.append(user)
return allUsers
def getUser(username, token, portalUrl):
'''A user resource representing a registered user of the portal.'''
parameters = urllib.urlencode({'token': token, 'f': 'json'})
request = '{}/sharing/rest/community/users/{}?{}'.format(
portalUrl, username, parameters
)
user = json.loads(urllib.urlopen(request).read())
return user
# Run the script.
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--portal', required=True,
help=('url of the portal '
'(e.g. https://portal.domain.com:7443/arcgis)'))
parser.add_argument('-o', '--username', required=True, help='username')
parser.add_argument('-s', '--password', required=True, help='password')
parser.add_argument('-f', '--filename', required=False,
default='portal_users.csv',
help=('the path to the file to create '
'(default: portal_users.csv'))
# Read the command line arguments.
args = parser.parse_args()
portal = args.portal[:-1] if args.portal[-1:] == '/' else args.portal
username = args.username
password = args.password
filename = args.filename
token = generateToken(username, password, portal)
# Create a dictionary of the portal's roles.
customRoles = getRoles(token, portal)
roles = {}
for role in customRoles['roles']:
roles[role['id']] = role['name']
# Add the built-in roles to the list.
roles.update({
'account_user': 'User (built-in)',
'account_publisher': 'Publisher (built-in)',
'account_admin': 'Admin (built-in)',
'org_user': 'User (built-in)',
'org_publisher': 'Publisher (built-in)',
'org_admin': 'Admin (built-in)'
})
users = getUsers(token, portal)
outputFile = filename
with open(outputFile, 'wb') as output:
dataWriter = csv.writer(
output,
delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL
)
# Write header row.
dataWriter.writerow(
['Full Name', 'Username', 'Email', 'Role']
)
print('Found {} users.'.format(len(users)))
for user in users:
userData = {}
for attr in ['fullName', 'username', 'email', 'role']:
try:
userData[attr] = user[attr].encode('utf-8')
except:
pass
userData['role'] = roles[user['role']]
dataWriter.writerow([
userData['fullName'],
userData['username'],
userData['email'],
userData['role']
])
print('\nFinished creating {}'.format(filename))