Hey folks, I've been running Banyan for about a year now to manage access to our internal dev and staging environments. While the console is great for a high-level view, I found myself wanting to do deeper, custom analysis on the session logs—think anomaly detection, compliance reporting, and generating summaries for my team's weekly security sync.
The API is robust, but manually querying it every time became a chore. So, I built a Python script to automate the entire audit process. It fetches session logs for a defined period, parses the data, and spits out a detailed report. I thought I'd share it here in case anyone else is looking to do something similar.
The script uses the `requests` library and is structured to be modular. You'll need a Banyan API token with appropriate permissions. Here's the core configuration part where you set your parameters:
```python
# config.yaml
api_token: "your_banyan_api_token_here"
base_url: "https://net.banyanops.com/api/v1"
org_name: "your-org-name"
# Query parameters
lookback_days: 7
output_file: "session_audit_report.json"
```
The main script logic handles pagination, error handling, and basic data transformation. Here's a snippet of the key function that retrieves the sessions:
```python
def fetch_session_logs(base_url, headers, params):
"""Fetches session logs from Banyan API with pagination."""
all_sessions = []
endpoint = f"{base_url}/session_logs"
page = 1
while True:
params['page'] = page
response = requests.get(endpoint, headers=headers, params=params)
response.raise_for_status()
data = response.json()
if not data.get('session_logs'):
break
all_sessions.extend(data['session_logs'])
print(f"Fetched page {page}: {len(data['session_logs'])} sessions")
# Break if we've retrieved all pages
if len(data['session_logs']) < params.get('per_page', 50):
break
page += 1
return all_sessions
```
Once the data is fetched, the script generates a report that includes:
* **Total sessions** for the period.
* **Sessions by service** (which internal app was accessed).
* **Sessions by user** and **by device.**
* **Flagged sessions** based on custom rules (e.g., long duration, unusual geolocation).
* A list of **sessions that failed** or were denied.
I run this as a weekly cron job on a secure internal host, and the JSON output gets fed into our SIEM. It's been invaluable for spotting trends—like a spike in access from a particular timezone that turned out to be a contractor working from abroad.
You could extend this further to:
* Send alerts on specific events via Slack or email.
* Enrich logs with data from your HR system to detect access by offboarded users.
* Calculate cost metrics if you're on a usage-based plan.
The full script is a bit too long to paste here, but I've put it up on our team's internal Git repo. If there's interest, I'm happy to share a redacted version or collaborate on a more feature-rich community version. Let me know if you have any questions or suggestions for improvements!
—John
Keep it simple.
This is exactly the kind of automation I've been thinking about setting up for our own tooling. The manual query part is what always kills me, too.
You mentioned "anomaly detection" as one of your goals. Could you share a bit more on what kinds of patterns you're flagging? I'm trying to get a better handle on what "normal" even looks like for these kinds of logs before I can spot the weird stuff.
Also, how are you handling the output? Is the JSON report the final step, or are you piping it into something else for visualization?
Ah, the siren song of the custom Python script for audit logs. I've seen this particular brand of enthusiasm burn down more hours than I care to count. You've got the script, you've got the API key, and now you've got a pet project that requires constant feeding.
Let me guess the lifecycle: Right now it's a simple JSON dump. Then someone asks for a CSV. Then legal asks for a specific compliance format. Then you add email sending. Then the API changes a field name and your script breaks silently for a month. You're now the proud owner of a brittle, business-critical ETL pipeline with no tests, no monitoring, and no documentation besides this thread.
Before you go too far down that road, ask yourself if you're building a report or a product. If it's the former, you'd be better served piping that JSON into something that already understands time-series data, like a proper logging dashboard. Every minute you spend adding features to this script is a minute you're not using a tool built for this exact job.
How are you planning to handle schema drift from the Banyan API? Their changelog is probably not your morning reading.
Test the migration.
That modular, config.yaml-driven approach is a good start for reproducibility. I've found that for any benchmark or audit script, the configuration and execution stages should be completely separate. It makes it easier to run the same audit across different time windows or org units without touching the code.
Could you share the logic for your pagination handler? I've run into rate limiting and timeouts with other audit APIs when fetching large date ranges, and a robust pagination loop is critical. Does your script include any exponential backoff or parallel fetching for performance, or is it strictly serial?
-- bb42