import urllib import urllib2 import json def get_portal_security_token(portal_url, portal_admin_user, portal_admin_password, expiration=60): ''' Returns a security token for AGOL or an ArcGIS portal. Expiration period is specified in minutes and defaults to an hour. The portal URL needs to be something like this: https://www.arcgis.com/sharing/generateToken https://my.portal.com/portal/sharing/generateToken ''' def get_my_ip(): '''' https://api.ipify.org?format=json' returns {"ip":"12.34.5.678"} ''' return json.loads(urllib2.urlopen('https://api.ipify.org?format=json').read())['ip'] #the get_my_ip may not be necessary as a blank referer means "IP Address of this request's origin", but I wanted to include the ipify call because it's a cool service. payload = {'username' : portal_admin_user, 'password' : portal_admin_password, 'referer' : get_my_ip(), 'f' : 'json', 'expiration' : expiration } request = urllib2.Request(portal_url, urllib.urlencode(payload)) #post request response = urllib2.urlopen(request) return json.loads(response.read())['token']