Forum Discussion

HyunSim's avatar
HyunSim
Comet
2 months ago

Question regarding EntityID

Hi Team, 

We are working with a customer who needs to retrieve a list of users whose last connection exceeds one month.

As advised by our Cato regional Sales Engineer, we are attempting to achieve this using the API in two steps:

Use query entityLookup to obtain the EntityID (userID)
Use query accountSnapshot to retrieve each user's last connection timestamp

However, we're encountering a challenge due to API rate limits. The entityLookup query is limited to 30 requests per minute (or 1500 over 5 hours), which makes it impractical to retrieve EntityIDs for all 2600+ users in a reasonable timeframe.

Below is the Python code we are currently using in our attempt:

import requests
import json
from datetime import datetime, timedelta

# Cato GraphQL endpoint URL
url = "https://api.catonetworks.com/api/v1/graphql2"

# HTTP headers와 API key
headers = {
    "Content-Type": "application/json",
    "x-api-key": "Our client API key"
}

# Query 1: EntityID(UserID) API 명령문
query1 = """
query AllMyRemoteUsers {
  entityLookup(accountID:4265, type: vpnUser) {
    items {
      entity {
        id
        name
      }
      description
    }
    total
  }
}
"""

# Query 1 실행
payload = { "query": query1 }
response = requests.post(url, json=payload, headers=headers)
data = response.json()

# EntityID 추출
userIDs = []
try:
    items = data['data']['entityLookup']['items']
    for item in items:
        user_id = int(item['entity']['id'])
        userIDs.append(user_id)

except KeyError as e:
    print(f"Error parsing response: {e}")
    print(json.dumps(data, indent=2))

print(userIDs)

# GraphQL EntityID list string으로 생성 
user_id_list_str = ",".join(str(uid) for uid in userIDs)
print("EntityID 추출 완료")

# Query 2: accountSnapshot API 명령문
query2 = f"""
query accountSnapshot {{
  accountSnapshot(accountID: 4265) {{
    users(userIDs:[{user_id_list_str}]) {{
      info {{
        name
        email
        phoneNumber
        status
        authMethod
        origin
      }}
      lastConnected
      version
    }}
  }}
}}
"""

# Query 2 실행
payload = { "query": query2 }
response = requests.post(url, json=payload, headers=headers)

from datetime import datetime, timedelta

# query2 Json reponse 파싱
result = response.json()

# 한달간 접속이력이 없었던 사용자 정보 출력
cutoff_date = datetime.utcnow() - timedelta(days=30)

import csv

# Prepare list to hold all rows to be saved
csv_rows = []

try:
    users = result['data']['accountSnapshot']['users']
    for user in users:
        last_connected_str = user.get('lastConnected')
        if last_connected_str:
            last_connected = datetime.strptime(last_connected_str, "%Y-%m-%dT%H:%M:%SZ")
            if last_connected > cutoff_date:
                name = user['info']['name']
                email = user['info']['email']
                csv_rows.append([name, email, last_connected.strftime("%Y-%m-%d %H:%M:%S")])
except KeyError as e:
    print(f"Error extracting user data: {e}")

# Save to CSV
csv_file_path = "한달간 접속이력 없는 사용자.csv"
with open(csv_file_path, mode='w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Email", "Last Connected"])
    writer.writerows(csv_rows)

print(f"\nCSV file이 저장되었습니다: {csv_file_path}")

On line 57, you can see that we need to put all the EntityID(UserID) to check each Users Last connection info. But because of entityLookup's limit, it only put 30 SDP user's EntityID.

Could you please provide us if there is any other way to get all the EntityID(userID) by using API so we can list the users according to the Last connection?

 

Best regards,

2 Replies

  • Hi HyunSim

    Can I check if you have an existing RFE or Support ticket regarding this matter?
    Alternatively, would you consider exporting the list of "last connected users" in CMA > Access > Users to filter and identify the list of "users that connected connected more than one month agao"?

    Cheers

    • HyunSim's avatar
      HyunSim
      Comet

      We do not have existing RFE but have support ticket #761632.
      Since, we cannot use API to query the users, currently we are exporting users in CMA > Access > Users as you mentioned.