You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ubuntu部署的Tableau Server中用Python添加不同角色新用户

Absolutely! You can absolutely automate adding users with different roles to your Ubuntu-hosted Tableau Server using Python. The most reliable approaches leverage Tableau's official APIs and tools—here are two straightforward methods:

Method 1: Use the Official Tableau Server Client (TSC) Python Library

This is the recommended approach because it wraps Tableau's REST API into a clean, Pythonic interface, so you don't have to handle raw HTTP requests manually.

Step 1: Install the TSC Library

First, install the package via pip:

pip install tableauserverclient

Step 2: Write the Python Script

This example uses personal access tokens (the preferred authentication method for automation) to sign in, then adds users with different site roles:

import tableauserverclient as TSC

# Configure your server details
SERVER_URL = "https://your-tableau-server-domain"  # e.g., http://localhost:8000 for local testing
SITE_NAME = "your-site-content-url"  # Use "" for the default site
TOKEN_NAME = "your-token-name"  # Create this in Tableau Server's user settings
TOKEN_VALUE = "your-token-secret"

# Initialize server connection
server = TSC.Server(SERVER_URL, use_server_version=True)

# Authenticate with personal access token
with server.auth.sign_in(TSC.PersonalAccessTokenAuth(TOKEN_NAME, TOKEN_VALUE, site_id=SITE_NAME)):
    # Define users to add: username, email, and desired role
    users_to_add = [
        {
            "username": "jane.doe@example.com",
            "email": "jane.doe@example.com",
            "role": TSC.Role.SiteAdministratorExplorer
        },
        {
            "username": "john.smith@example.com",
            "email": "john.smith@example.com",
            "role": TSC.Role.Viewer
        },
        {
            "username": "emma.wong@example.com",
            "email": "emma.wong@example.com",
            "role": TSC.Role.Creator
        }
    ]

    for user in users_to_add:
        try:
            # Create a UserItem object
            new_user = TSC.UserItem(
                name=user["username"],
                email=user["email"],
                site_role=user["role"]
            )
            # Add the user to the site
            server.users.add(new_user)
            print(f"✅ Successfully added user: {user['username']} (Role: {user['role']})")
        except Exception as e:
            print(f"❌ Failed to add {user['username']}: {str(e)}")

# The `with` block automatically signs you out when finished
Method 2: Directly Call the Tableau Server REST API

If you prefer working with raw HTTP requests (e.g., without installing TSC), you can use Python's requests library to interact directly with Tableau's REST API.

Step 1: Install Requests

If you don't have it already:

pip install requests

Step 2: Write the Script

This script handles authentication, user creation, and cleanup:

import requests
import json

# Server configuration
SERVER_URL = "https://your-tableau-server-domain"
SITE_NAME = "your-site-content-url"
TOKEN_NAME = "your-token-name"
TOKEN_VALUE = "your-token-secret"
API_VERSION = "3.21"  # Match this to your Tableau Server version

# 1. Authenticate and get an auth token
auth_endpoint = f"{SERVER_URL}/api/{API_VERSION}/auth/signin"
auth_payload = {
    "credentials": {
        "personalAccessTokenName": TOKEN_NAME,
        "personalAccessTokenSecret": TOKEN_VALUE,
        "site": {"contentUrl": SITE_NAME}
    }
}

headers = {"Content-Type": "application/json"}
response = requests.post(auth_endpoint, json=auth_payload, headers=headers, verify=False)  # Disable verify only for self-signed certs
response.raise_for_status()

auth_data = response.json()
auth_token = auth_data["credentials"]["token"]
site_id = auth_data["credentials"]["site"]["id"]

# 2. Add users to the site
add_user_endpoint = f"{SERVER_URL}/api/{API_VERSION}/sites/{site_id}/users"
headers["X-Tableau-Auth"] = auth_token

users_to_add = [
    {
        "username": "bob.jones@example.com",
        "email": "bob.jones@example.com",
        "role": "SiteAdministratorExplorer"
    },
    {
        "username": "lisa.ray@example.com",
        "email": "lisa.ray@example.com",
        "role": "Viewer"
    }
]

for user in users_to_add:
    user_payload = {
        "user": {
            "name": user["username"],
            "email": user["email"],
            "siteRole": user["role"]
        }
    }
    try:
        response = requests.post(add_user_endpoint, json=user_payload, headers=headers, verify=False)
        response.raise_for_status()
        print(f"✅ Successfully added user: {user['username']} (Role: {user['role']})")
    except Exception as e:
        print(f"❌ Failed to add {user['username']}: {str(e)}")

# 3. Sign out to invalidate the token
signout_endpoint = f"{SERVER_URL}/api/{API_VERSION}/auth/signout"
requests.post(signout_endpoint, headers={"X-Tableau-Auth": auth_token}, verify=False)
Key Notes to Keep in Mind
  • API Version Compatibility: Make sure the API version you use matches your Tableau Server version. You can find your server's compatible API version by checking the Tableau Server UI's help section or version info page.
  • Permissions: The account used for authentication (the one linked to the personal access token) must have sufficient privileges—like Server Administrator or Site Administrator Creator—to add users to the server/site.
  • Certificate Validation: In production environments, avoid using verify=False for HTTPS requests. Instead, import your server's trusted certificate into Python's certificate store.
  • Valid Roles: Tableau has fixed site role values. Some common ones include:
    • Creator
    • Explorer
    • ExplorerCanPublish
    • Viewer
    • SiteAdministratorCreator
    • SiteAdministratorExplorer
    • ServerAdministrator

内容的提问来源于stack exchange,提问作者code.dev.world

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:16:00