示例:向门户添加成员
本例将采用包含用户信息的输入文本文件,并将其中的用户批量地添加到门户中。您可以在门户中定义将授予每位用户的角色。
运行此脚本时,您需要输入以下信息:
- 包含用户信息的文本文件的路径,例如,/home/admin/documents/users.txt。
- 希望添加到门户的用户类型,例如内置或企业。有关用户类型的详细信息,请参阅管理对门户的访问。
- 托管门户的计算机的完全限定域名,例如 myportal.acme.com。此脚本将通过端口 7443 上的 HTTPS 访问门户,并绕过 ArcGIS Web Adaptor。采用这种方法时,如果已将门户配置为使用 Web 层身份验证,则脚本无需对其进行处理。
- 对门户具有管理权限的帐户的用户名和密码。如果您正在添加内置帐户,则可以提供任何具有管理权限的门户成员的凭据。如果正在添加企业帐户,则必须使用安装 Portal for ArcGIS 后创建的初始管理员帐户。
注:
本示例中不会演示如何使 Python 脚本处理 Web 层身份验证。
添加内置门户帐户
添加内置门户帐户时,文本文件中每个条目的格式如下:
<username>|<password>|<email address>|<name>|<role>|<description>
- 用户名 - 用于内置帐户的用户名。用户名必须是唯一的;不同成员不可以具有相同的用户名。
- 密码 - 分配给此帐户的密码。用户可在首次登录门户时使用此密码,之后可通过编辑个人资料修改密码。
- 电子邮件地址 - 为此帐户提供电子邮件地址。此参数是必填项,因此必须为电子邮件地址提供一个值,即使该地址无效。
- 名称 - 此名称是将在 ArcGIS 组织中使用的帐户的别名。当用户连接到门户网站时,此名称会出现在门户网站的顶部。
- 角色 - 这是帐户将在 ArcGIS 组织中拥有的角色。有效角色值为 org_user、org_publisher 或 org_admin。
- 描述 - 您也可以添加文本以描述帐户。描述的长度不能超过 250 个字符。
此示例将为 Barbara Williams 添加内置门户帐户,用户名为 pub1,电子邮件帐户为 bwilliams@domain.com。示例还会将 pub1 添加到发布者角色并将其描述为规划部门的成员:
pub1|changepasswordlater|bwilliams@domain.com|Barbara Williams|org_publisher|planning department
注册企业帐户
注册企业帐户时,文本文件中每个条目的格式如下:
<username>|<email address>|<name>|<role>|<description>
- 用户名 - 要注册的企业帐户的用户名。如果使用活动目录,则该用户名的形式应该为 sAMAccountName@DOMAIN。域名字母必须全大写。如果使用 LDAP,则登录名应该与配置标识存储时您指定的 userNameAttribute 的值相匹配。
- 电子邮件地址 - 电子邮件地址应该与帐户相关,并与标识存储中的值相匹配。如果用户帐户不具有电子邮件地址,则提供一个 false 或通用值。
- 名称 - 名称为登录的别名,将在 ArcGIS 组织中使用。大部分标识存储将用户的全名用作默认别名。当用户连接到门户网站时,此名称会出现在门户网站的顶部。
- 角色 - 这是帐户将在 ArcGIS 组织中拥有的角色。有效角色值为 org_user、org_publisher 或 org_admin。
- 描述 - 您也可以添加文本以描述帐户。该值与标识存储中的所有属性均不对应。描述的长度不能超过 250 个字符。
您需要为用户名、电子邮件地址、名称和角色提供一个值。描述为选填内容。对文件中列出的每个帐户,验证登录名、电子邮件和名称输入的值是否与标识存储中的值准确匹配。该门户不会连接到标识存储来验证这些值。
以下是注册企业帐户的条目示例,登录名为 jcho111,电子邮件地址是 jcho@domain.com,全名为 Jon Cho。此登录名被放置在用户角色 (org_user) 中,并且描述为部门 b 中的用户:
jcho111@DOMAIN|jcho@domain.com|Jon Cho|org_user|department b
#!/usr/bin/env python
# Requires Python 2.7+
# Demonstrates how to add users to Portal for ArcGIS in bulk
# For Http calls
import httplib, urllib2, urllib, json
# For system tools
import sys, os
# For reading passwords without echoing
import getpass
# Other utilities
import Queue
# Defines the entry point into the script
def main(argv):
print "This script adds users in bulk into a portal. \n"
#Get parameters
parameters = getParametersFromUser ()
portalURL = parameters['portalURL']
provider = parameters['provider']
userName = parameters['userName']
password = parameters['password']
inUserFile = parameters['inUserFile']
#Get user data from file
usersData = getUserDataFromFile(inUserFile,provider)
#Create users
createUsers (userName,password, portalURL,provider, usersData)
print '\n ...Script ended. '
return
# This function loads all the user data in the input text file into a Python Queue.
# This usersQueue can be later passed to the createUsers function
def getUserDataFromFile(inUserFile,provider):
usersQ = Queue.Queue()
keyParams = ['username', 'password', 'email', 'fullname','role','description']
inFileHandle = open(inUserFile, 'r')
userCount = 0
print '...Processing input users file at: ' + inUserFile
entryCount = 1;
for line in inFileHandle.readlines():
userParams = line.split('|')
userParamDict = {}
if provider=="webadaptor":
if len(userParams) == 5:
for i in range (0,5):
userParamDict[keyParams[0]] = userParams[0] # login
userParamDict[keyParams[1]] = ""
userParamDict[keyParams[2]] = userParams[1] # email address
userParamDict[keyParams[3]] = userParams[2] # name
userParamDict[keyParams[4]] = userParams[3] # role
userParamDict[keyParams[5]] = userParams[4].replace('\n','') # description
usersQ.put (userParamDict)
userCount = userCount + 1
else:
print ' The format for entry %s is invalid. The format for enterprise accounts should be <login>|<email address>|<name>|<role>|<description>. \n '% (entryCount)
#raise SystemExit( 'When registering enterprise accounts, the format for each entry is as follows: <login>|<email address>|<name>|<role>|<description>')
elif provider=="arcgis":
if len(userParams) == 6:
for i in range (0,6):
userParamDict[keyParams[0]] = userParams[0] # account
userParamDict[keyParams[1]] = userParams[1] # password
userParamDict[keyParams[2]] = userParams[2] # email address
userParamDict[keyParams[3]] = userParams[3] # name
userParamDict[keyParams[4]] = userParams[4] # role
userParamDict[keyParams[5]] = userParams[5].replace('\n','') # description
usersQ.put (userParamDict)
userCount = userCount + 1
else:
print ' The format for entry %s is invalid. The format for built-in portal accounts should be <account>|<password>|<email address>|<name>|<role>|<description>. \n '% (entryCount)
#raise SystemExit( 'When registering built-in portal accounts, the format for each entry is as follows: <account>|<password>|<email address>|<name>|<role>|<description>')
else:
#print ' The provider is incorrect. Script ended. \n'
raise SystemExit( 'The value for the user type is invalid. ')
entryCount = entryCount +1
if not ((userParamDict[keyParams[4]].lower()== "org_user") or (userParamDict[keyParams[4]].lower()=="org_publisher") or (userParamDict[keyParams[4]].lower()== "org_admin")):
raise SystemExit( 'The value for the user role %s in users text file is invalid. Accepted values are org_user or org_publisher or org_admin. ' % (userParamDict[keyParams[4]]))
inFileHandle.close()
# Create users and report results
print '...Total members to be added: ' + str(userCount)
return usersQ
# This function connects to the portal and adds members to it from a collection
def createUsers(username,password, portalUrl, provider,userParamsQ):
print '...Connecting to ' + portalUrl
token = generateToken(username,password, portalUrl)
print '...Adding users '
usersLeftInQueue = True
while usersLeftInQueue:
try:
userDict = userParamsQ.get(False)
userDict['f'] = 'json'
userDict['token'] = token
userDict['provider'] = provider
params = urllib.urlencode(userDict)
request = urllib2.Request(portalUrl + '/portaladmin/security/users/createUser?',params)
# POST the create request
response = urllib2.urlopen(request).read()
responseJSON = json.loads(response)
# Log results
if responseJSON.has_key('error'):
errDict = responseJSON['error']
if int(errDict['code'])==498:
message = 'Token Expired. Getting new token... Username: ' + userDict['username'] + ' will be added later'
token = generateToken(username,password, portalUrl)
userParamsQ.put(userDict)
else:
message = 'Error Code: %s \n Message: %s' % (errDict['code'],
errDict['message'])
print '\n' + message
else:
# Success
if responseJSON.has_key('status'):
resultStatus = responseJSON['status']
#print '\n' + 'User: %s account created' % (userDict['username'])
print 'User: %s account created' % (userDict['username'])
except Queue.Empty:
usersLeftInQueue = False
# This function gets a token from the portal
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'})
try:
response = urllib.urlopen(portalUrl + '/sharing/rest/generateToken?',
parameters).read()
except Exception as e:
raise SystemExit( 'Unable to open the url %s/sharing/rest/generateToken' % (portalUrl))
responseJSON = json.loads(response.strip(' \t\n\r'))
# Log results
if responseJSON.has_key('error'):
errDict = responseJSON['error']
if int(errDict['code'])==498:
message = 'Token Expired. Getting new token... '
token = generateToken(username,password, portalUrl)
else:
message = 'Error Code: %s \n Message: %s' % (errDict['code'],
errDict['message'])
raise SystemExit(message)
token = responseJSON.get('token')
return token
# This function gets gets parameters from the user in interactive mode
def getParametersFromUser():
parameters = {}
# Get Location of users file
inUserFile = raw_input ("Enter path to users text file: ")
if not os.path.exists(inUserFile):
print ' File does not exist. Script ended. \n'
raise SystemExit( 'Input file: %s does not exist' % (inUserFile))
parameters['inUserFile'] = inUserFile
# Enteprise logins or built-in accounts?
userInput = raw_input ("What type of users do you want to add to the portal? Accepted values are built-in or enterprise: ")
if userInput.lower()=="built-in":
parameters['provider'] = 'arcgis'
print ' Built-in accounts will be added to the portal. \n'
elif userInput.lower()=="enterprise":
parameters['provider'] = 'webadaptor'
print ' Enterprise accounts will be added to the portal. \n'
else:
#print ' The type of users is incorrect. Script ended. \n'
raise SystemExit( 'The value entered for the user type %s is invalid. Accepted values are built-in or enterprise. ' % (userInput))
# Get Portal URL
hostname = raw_input("Enter the fully qualified portal hostname (for example myportal.acme.com): ")
parameters['portalURL'] = 'https://' + hostname + ':7443/arcgis'
print ' Users will be added to portal at: ' + parameters['portalURL'] + '\n'
# Get a username and password with portal administrative privileges
parameters['userName'] = raw_input("Enter a built-in user name with portal administrative privileges:")
parameters['password'] = raw_input("Enter password: ")
print '\n'
return parameters
# Script start
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
5/10/2014