Skip to content

Instantly share code, notes, and snippets.

@asuna
Last active October 26, 2023 10:21
Show Gist options
  • Save asuna/5c485f1f0e534face1c71c0be8a01469 to your computer and use it in GitHub Desktop.
Save asuna/5c485f1f0e534face1c71c0be8a01469 to your computer and use it in GitHub Desktop.
update pritunl user info, Reference: https://github.com/fmgervasoni/pritunl-api-client
import os, json
import requests, time, uuid, hmac, hashlib, base64
import logging
from datetime import datetime
# Setup logging
logFormatter = logging.Formatter('%(asctime)s - %(message)s')
rootLogger = logging.getLogger()
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
fileHandler = logging.FileHandler("/tmp/pritunl_auth_update.log")
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.INFO)
BASE_URL = 'https://pritunl_url' # Your Pritunl Server URL
API_TOKEN = 'api_token' # Your Pritunl User api token
API_SECRET = 'api_secret' # Your Pritunl User api secret
ORG_NAME = 'org_name' # Pritunl ORG
def auth_request(method, path):
auth_timestamp = str(int(time.time()))
auth_nonce = uuid.uuid4().hex
auth_string = '&'.join([API_TOKEN, auth_timestamp, auth_nonce, method.upper(), path])
auth_signature = base64.b64encode(hmac.new(
API_SECRET.encode('utf-8'), auth_string.encode('utf-8'), hashlib.sha256).digest())
auth_headers = {
'Auth-Token': API_TOKEN,
'Auth-Timestamp': auth_timestamp,
'Auth-Nonce': auth_nonce,
'Auth-Signature': auth_signature,
'Content-Type': 'application/json'
}
return auth_headers
# Function to call the API, template is optional
def request(method, path, template=None):
try:
return requests.request(method, BASE_URL + path,
headers=auth_request(method, path),
verify=True, data=json.dumps(template)
)
except Exception as e:
logging.error(e)
return None
response = request('get', '/organization')
orgs = response.json()
org = next((x for x in orgs if x['name'] == ORG_NAME), None)
org_id = org['id'] if org else None
if org_id is None:
logging.info(f"No organization found with name {ORG_NAME}")
exit(1)
response = request('GET', '/user/%s' % org_id)
assert(response.status_code == 200)
users = response.json()
# Query and update all user's auth_type to local
for user in users:
old_auth_type = user['auth_type']
if old_auth_type != 'local':
user['auth_type'] = 'local'
response = request('PUT', f'/user/{org_id}/{user["id"]}', template=user)
success = response.status_code == 200
logging.info(f"Org: {ORG_NAME}, Org ID: {org_id}, User: {user['name']}, User ID: {user['id']}, Old auth type: {old_auth_type}, New auth type: {user['auth_type']}, Success: {success}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment