How to Get API tokens from all Managed Accounts using REST API

お困りですか?

アトラシアン コミュニティをご利用ください。

コミュニティに質問


 

プラットフォームについて: Cloud のみ - この記事は、 クラウド プラットフォームのアトラシアン製品にのみ適用されます。

   


免責事項

Atlassian does not support this code below, which is provided "AS IS". The goal of this article is to provide a piece of code that illustrates one way to achieve the desired goal.

Feedback provided at the bottom of the page is appreciated, but won't be handled as support.

This can be achieved through the UI by using API token controls.

要約

The Python script on this page was created to extract a report with all Managed Accounts having API tokens using the Get API tokens endpoint. This example can be used as is but might be a nice place to start and be built upon.


環境

Jira Cloud

This script requires Python 3 to be installed.


用途

  1. Export your managed accounts:

    1. Access http://admin.atlassian.com

    2. Go to "Directory" → “Managed accounts

    3. Select “Export Accounts

    4. Download the CSV file from your mail

  2. Manipulate the CSV file:

    1. Open the CSV file

    2. Delete all columns except the “Atlassian ID

    3. Rename the CSV file as “managed_accounts.csv

  3. Set up and execute the script:

    1. The only thing you need to update is the organization authorization token “<yourOrgToken>“ under the “headers” variable. You can find how to create an organization token here

    2. Make sure the script and the managed_accounts.csv are under the same folder

    3. Now you can execute the script with “python3 script.py”, it may take some time if you have a significant number of accounts

    4. Once it's finished, it will create an “output.csv” with only the managed accounts that have API tokens

スクリプト
# Script to search managed accounts that have API tokens
import requests
import csv

# Variables
headers = {
  "Accept": "application/json",
  "Authorization": "Bearer <yourOrgToken>"
}
accounts_checked = 0

def get_account_tokens(account_id):
    global accounts_checked
    url = f"https://api.atlassian.com/users/{account_id}/manage/api-tokens"
    print(f"Getting tokens for account ID: {account_id}")
    response = requests.get(url, headers=headers)

    # Response example (if the account has API tokens):
    # [
    # {
    #     "id": "00000000",
    #     "label": "xxxx",
    #     "createdAt": "2023-10-27T16:17:45.125421997Z",
    #     "disabledStatus": false
    # }
    # ]

    if response.status_code != 200:
        print(f"Failed to get tokens for account ID: {account_id}. Status code: {response.status_code}, Error message: {response.text}")
        return []
    
    accounts_checked += 1
    tokens = []

    for entry in response.json():
        if all(key in entry for key in ['id', 'label', 'createdAt', 'disabledStatus']):
            tokens.append({
                'id': entry['id'],
                'label': entry['label'],
                'createdAt': entry['createdAt'],
                'disabledStatus': entry['disabledStatus']
            })
    return tokens

def check_accounts():
    print("Started")
    with open('managed_accounts.csv', 'r') as csvfile, open('output.csv', 'w', newline='') as outfile:
        datareader = csv.reader(csvfile)
        # Skip the header
        next(datareader, None)
        datawriter = csv.writer(outfile)
        datawriter.writerow(["Account ID", "ID", "Label", "Created At", "Disabled Status"])

        for row in datareader:
            account_id = row[0]
            tokens = get_account_tokens(account_id)

            for token in tokens:
                datawriter.writerow([account_id, token['id'], token['label'], token['createdAt'], token['disabledStatus']])

        print(f"Accounts checked: {accounts_checked}")
    print("output.csv file was created! Check the results.")

check_accounts()
 



最終更新日 2023 年 11 月 8 日

この内容はお役に立ちましたか?

はい
いいえ
この記事についてのフィードバックを送信する
Powered by Confluence and Scroll Viewport.