Forget it.. after a break, I found the problem. In my python script, I was passing the dict itself, not a string. I used json.dump() to convert the dict to a string and all works fine now.
In case anyone ever needs to add users via API, here's a very basic example to add one user and folder at least:
Code: Select all
#!/usr/bin/env python3
### Script to test API based user admin
import requests
import sys
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("host", help="EVE hostname or IP", type=str)
args = parser.parse_args()
### Declare variables
eve_host = args.host
username = "username"
password = "password"
### Open http session, authenticate and get cookie from EVE-ng
resp = requests.session()
base_url = "https://" + eve_host + "/api"
creds = '{"username":"'+username+'","password":"'+password+'","html5":"-1"}'
resp.post(base_url + '/auth/login', data=creds, verify=False)
auth_cookie = dict(resp.cookies)
### Function to place API call
def call_api(command):
print("Getting "+base_url+command)
resp = requests.get(base_url + "/" + command, headers={'Content-Type':'application/json'}, cookies=auth_cookie, verify = False)
if resp.status_code != 200: # at least give the HTTP error code if something went wrong.
print("HTTP %i - %s, Message %s" % (resp.status_code, resp.reason, resp.text))
sys.exit(1)
return(resp.json())
def post_to_api(function, data_dict, expect_status_code = 200):
resp = requests.post(base_url + '/' + function, data=json.dumps(data_dict), headers={'Content-Type':'application/json'}, cookies=auth_cookie, verify = False)
if (resp.status_code != expect_status_code): # at least give the HTTP error code if something went wrong.
print("HTTP %i - %s, Message %s" % (resp.status_code, resp.reason, resp.text))
sys.exit(1)
return(resp.json())
folder_data = {
'path': '/Users',
'name': 'testuser1'}
user_data = {
'username': 'testuser1',
'password': 'notneeded-extauthused',
'email': 'test.user@email.local',
'extauth': 'radius',
# 'ram': '-1',
# 'cpu': '-1',
# 'expiration': '-1',
# 'datestart': '-1',
'name': 'Test User',
'role': 'admin',
# 'pod': '-1',
# 'pexpiration': '-1',
# 'session': '-1'
}
#print(call_api("users/admin"))
print(post_to_api("users", user_data, expect_status_code = 201))
print(post_to_api("folders", folder_data))