The function getToken() (near the bottom) can be called by itself. Check that you are receiving a token from ArcGIS Server given your input arguments.
You can create a new script which contains only the getToken() function code block and execute with your desired python environment or paste the function into your python interpreter.
Something like the below should work given your input arguments.
If you are looking at Portal items and urls specifically, I would suggest looking into the arcgis.gis module which searches on Portal rather than the ArcGIS Server REST Admin API.
def getToken(username, password, serverName, serverPort):
# Token URL is typically http://server[:port]/arcgis/admin/generateToken
tokenURL = "/arcgis/admin/generateToken"
params = urllib.urlencode({'username': username, 'password': password, 'client': 'requestip', 'f': 'json'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
# Connect to URL and post parameters
httpConn = httplib.HTTPConnection(serverName, serverPort)
httpConn.request("POST", tokenURL, params, headers)
# Read response
response = httpConn.getresponse()
if (response.status != 200):
httpConn.close()
print "Error while fetching tokens from admin URL. Please check the URL and try again."
return
else:
data = response.read()
httpConn.close()
# Check that data returned is not an error object
if not assertJsonSuccess(data):
return
# Extract the token from it
token = json.loads(data)
return token['token']
# Insert your args here
username = 'abc'
password = '***'
serverName = 'https://...com'
serverPort = 1234
token = getToken(username, password, serverName, serverPort)
print (token)