1 Reply Latest reply on Oct 26, 2017 11:48 PM by Glen Robinson

    REST API TableauServerClient Script

    Barbara Knowles

      Hi.

       

      Hopefully, this is my last question about this script.  It's my first python script.  I'm teaching myself.

       

      I've been trying to write a script which logs into the Tableau server, scrolls through a csv file containing user ids and deletes those that match off the server.

       

      The script deletes the users, but I can't get it to loop.  It's probably a python issue, instead of Tableau, and I'm exploring those avenues, too.  But I thought I'd post it here, as well.

       

      Here's my script:

       

      # The example runs in Python 2.7 and Python 3.3 code

      import requests, json, csv

      import tableauserverclient as TSC

       

      # outputFile=open('output.csv','w',newline='')
      # NOTE! Substitute your own values for the following variables
      server_name = "http://server" # Name or IP address of your installation of Tableau Server
      user_name = "user_id"  # User name to sign in as (e.g. admin)
      password = "password"
      site_url_id = "site_name"  # Site to sign in to. An empty string is used to specify the default site.

      # parser = argparse.ArgumentParser(description='Query View Image From Server')
      # + parser.add_argument('--server', '-s', required=True, help='server address')
      # + parser.add_argument('--site-id', '-si', required=False,
      # + help='content url for site the view is on')
      # + parser.add_argument('--username', '-u', required=True, help='username to sign into server')
      # + parser.add_argument('--view-name', '-v', required=True,
      # + help='name of view to download an image of')
      # + parser.add_argument('--filepath', '-f', required=True, help='filepath to save the image returned')
      # + parser.add_argument('--logging-level', '-l', choices=['debug', 'info', 'error'], default='error',
      # + help='desired logging level (set to error by default)')
      # +
      # + args = parser.parse_args()
      # +
      # + password = getpass.getpass("Password: ")

      signin_url = "https://tableau-xxxx".format(server=server_name)

       

      payload = { "credentials": { "name": user_name, "password": password, "site": {"contentUrl": site_url_id }}}

        

      headers = {

        'accept': 'application/json',

        'content-type': 'application/json'
      }

      # Send the request to the server
      req = requests.post(signin_url, json=payload, headers=headers)

      req.raise_for_status()

       

      # Get the response
      response = json.loads(req.content)

       

      # Get the authentication token from the <credentials> element 
      token = response["credentials"]["token"]

        

      # Get the site ID from the <site> element
      site_id = response["credentials"]["site"]["id"]

        

      print('Sign in successful!')

      print('\tToken: {token}'.format(token=token))

      print('\tSite ID: {site_id}'.format(site_id=site_id))

        

      # Set the authentication header using the token returned by the Sign In method.
      headers['X-tableau-auth']=token

       

      tableau_auth = TSC.TableauAuth(user_name, password, site_url_id)

      server = TSC.Server(server_name)

       

      with server.auth.sign_in(tableau_auth):

         # Identifies total users on the site
         request_option = TSC.RequestOptions(pagesize=1000)

        tab_users = []

         for i in TSC.Pager(server.users, request_option):

        tab_users.append(i.name)

         print('There are ' + str(len(tab_users)) + ' users.')

       

         # Identifies total users in csv files
         with open('TabAdminCsv.csv') as csvfile:

        reader = csv.reader(csvfile)

        csv_users = []

         for row in reader:

         if reader.line_num == 1:

         continue
         csv_users.append(row[1])

         print('There are ' + str(len(csv_users)) + ' users in csv file.')

       

         # Identifies matching users
         matching = []

       

         for u in csv_users:

         #for m in range(len(matching)):
         if u in tab_users:

        matching.append(u)

       

         # writer=csv.writer(outputFile)
        # writer.writerow(matching[0])

        # username = matching[1]
        # print(username)
        # request_option.filter.add(TSC.Filter(TSC.RequestOptions.Field.Name, TSC.RequestOptions.Operator.Equals, username))
        # matching_users, pagination_item = server.users.get(req_options=request_option)
        # server.users.remove(matching_users[0].id)

         print('There are ' + str(len(matching)) + ' csv users found in tableau user list, to be removed')

       

         # for m in range(len(matching)):

         username = matching[1]

         print(username)

       

        request_option.filter.add(TSC.Filter(TSC.RequestOptions.Field.Name,TSC.RequestOptions.Operator.Equals,username))

        matching_users, pagination_item = server.users.get(req_options=request_option)

       

         #for u in matching_users:

        server.users.remove(matching_users[0].id)

       

       

        csvfile.close()

       

         #server.users.remove(matching_users[0].id)
        #print(str(len(matching)) + ' users were removed from the '+site_url_id +' site.')

      signout_url = "https://tableau-xxxx".format(server=server_name)

        

      req = requests.post(signout_url, data=b'', headers=headers)

      req.raise_for_status()

      print('Sign out successful!')

       

      I keep moving the code in green around in hopes that I'll stumble on the correct location for it.

       

      I'd appreciate any advice.

       

      Thanks so much.

      Barbara

        • 1. Re: REST API TableauServerClient Script
          Glen Robinson

          Hi Barbara

           

          I have the following code, which does the same thing (but is written in Powershell)

          This is for REST API version 2.7. You would need to change the code if using an earlier version

          To use; save content to a *.ps1 file. On a windows machine open Powershell, and run script.

           

          Hope this helps

          Glen

           

          $server = "http://localhost"

          $username = "admin"

          $password = "password"

          $siteID =""

           

          $CSVFile = Get-Content "C:\temp\UserList.csv"

           

          # Login to Server

          # generate body for sign in

           

           

          $signin_body = (’<tsRequest>

            <credentials name=“’ + $username + ’” password=“’+ $password + ’” >

             <site contentUrl="’ + $siteID +’"/>

            </credentials>

          </tsRequest>’)

           

           

          $Uri = "$server/api/2.7/auth/signin"

          $response = Invoke-RestMethod -Uri $uri -Body $signin_body -Method Post 

           

           

          # get the auth token, site id and my user id

          $authToken = $response.tsResponse.credentials.token

          $siteID = $response.tsResponse.credentials.site.id

           

          $headers = New-Object “System.Collections.Generic.Dictionary[[String],[String]]”

          $headers.Add(“X-Tableau-Auth”, $authToken)

          $authToken

          $siteID

           

          ForEach ($UserName in $CSVFile)

          {

             $UserName

             $response = Invoke-RestMethod -Uri $server/api/$api_ver/sites/$siteID/users?filter=name:eq:$UserName -Headers $headers -Method Get

             $UserID = $response.tsResponse.Users.User.id

             $response = Invoke-RestMethod -Uri $server/api/$api_ver/sites/$siteID/users/$UserID -Headers $headers -Method DELETE

          }

           

          # Sign Out of Server

          $response = Invoke-RestMethod -Uri $server/api/2.7/auth/signout -Headers $headers -Method Post