Skip to main content

PTSandbox Python Client

PTSandbox Logo

Full-featured async Python client for PT Sandbox instances

PyPI Version Python Versions License


Documentation: https://security-experts-community.github.io/py-ptsandbox

Source Code: https://github.com/Security-Experts-Community/py-ptsandbox


📖 Overview

PTSandbox Python Client is a modern async library for interacting with PT Sandbox through API. The library provides a convenient interface for submitting files and URLs for analysis, retrieving scan results, system management, and much more.

✨ Key Features

  • Fully Asynchronous — all operations are performed in a non-blocking manner
  • Fully Typed — complete type hints support for better development experience
  • Dual API Support — both Public API and UI API for administrative tasks
  • Flexible File Upload — support for various input data formats
  • High Performance — optimized HTTP requests with connection pooling
  • Error Resilience — built-in error handling and retry logic
  • Modern Python — requires Python 3.11+

📦 Installation

PyPI

python3 -m pip install ptsandbox
uv add ptsandbox

Nix

# Coming soon

🔧 Requirements

  • python 3.11+
  • aiohttp 3.14.1+
  • pydantic 2.13.4+
  • orjson 3.11.9+
  • aiohttp-socks 0.11.0+

🚀 Quick Start

Basic File Scanning

import asyncio
from pathlib import Path
from ptsandbox import Sandbox, SandboxKey

async def main():
    # Create connection key
    key = SandboxKey(
        name="test-key-1",
        key="<TOKEN_FROM_SANDBOX>",
        host="10.10.10.10",
    )

    # The async context manager closes HTTP sessions automatically
    async with Sandbox(key) as sandbox:
        # Submit file for analysis
        task = await sandbox.create_scan(Path("suspicious_file.exe"))

        # Wait for analysis completion
        result = await sandbox.wait_for_report(task)

        if (report := result.get_long_report()) is not None:
            print(report.result.verdict)

asyncio.run(main())

URL Scanning

import asyncio
from ptsandbox import Sandbox, SandboxKey

async def main():
    key = SandboxKey(
        name="test-key-1",
        key="<TOKEN_FROM_SANDBOX>",
        host="10.10.10.10"
    )

    # Scan suspicious URL
    async with Sandbox(key) as sandbox:
        task = await sandbox.create_url_scan("http://malware.com/malicious-file")
        result = await sandbox.wait_for_report(task)

        if (report := result.get_long_report()) is not None:
            print(report.result.verdict)

asyncio.run(main())

Working with UI API (Administrative Functions)

import asyncio
from ptsandbox import Sandbox, SandboxKey

async def main():
    key = SandboxKey(
        name="test-key-1",
        key="<TOKEN_FROM_SANDBOX>",
        host="10.10.10.10",
        ui=SandboxKey.UI(
            login="login",
            password="password"
        )
    )

    # The UI API requires authorization before use
    async with Sandbox(key) as sandbox:
        await sandbox.ui.authorize()

        # Get system information
        system_info = await sandbox.ui.get_system_settings()
        print(f"System version: {system_info.data}")

        # Get tasks status
        tasks = await sandbox.ui.get_tasks()
        print(f"Active tasks: {len(tasks.tasks)}")

asyncio.run(main())

🛠️ Core Features

Public API

UI API (Administrative)

🔄 Advanced Usage

Batch Scanning

import asyncio
from pathlib import Path
from ptsandbox import Sandbox, SandboxKey

async def scan_multiple_files(files: list[Path]):
    async with Sandbox(SandboxKey(...)) as sandbox:
        # Submit all files in parallel
        tasks = []
        for file in files:
            task = await sandbox.create_scan(file, async_result=True)
            tasks.append(task)

        # Wait for all tasks to complete
        results = []
        for task in tasks:
            result = await sandbox.wait_for_report(task)
            results.append(result)

        return results

Custom Scan Configuration

from ptsandbox.models import SandboxBaseScanTaskRequest, SandboxOptions

# Configure scan options
options = SandboxBaseScanTaskRequest.Options(
    sandbox=SandboxOptions(
        image_id="ubuntu-jammy-x64",     # VM image selection
        analysis_duration=300,           # Analysis time in seconds
        custom_command="python3 {file}", # Custom execution command
        save_video=True,                 # Save process video
    )
)

task = await sandbox.create_scan(file, options=options)

Advanced File Analysis

from ptsandbox.models import SandboxOptionsAdvanced

# Advanced scanning with custom rules and extra files
task = await sandbox.create_advanced_scan(
    Path("malware.exe"),
    extra_files=[Path("config.ini"), Path("data.txt")],  # Additional files
    sandbox=SandboxOptionsAdvanced(
        image_id="win10-x64",
        analysis_duration=600,
        custom_command="python3 {file}",  # Custom execution command
        save_video=True,                  # Save process video
        mitm_enabled=True,                # Enable traffic decryption
        bootkitmon=False                  # Disable bootkitmon analysis
    )
)

Error Handling

from ptsandbox.exceptions import (
    SandboxUploadException,
    SandboxWaitTimeoutException,
    SandboxTooManyErrorsException
)

try:
    task = await sandbox.create_scan(large_file, upload_timeout=600)
    result = await sandbox.wait_for_report(task, wait_time=300)
except SandboxUploadException as e:
    print(f"Upload error: {e}")
except SandboxWaitTimeoutException as e:
    print(f"Timeout waiting for result: {e}")
except SandboxTooManyErrorsException as e:
    print(f"Too many errors occurred: {e}")

Stream File Downloads

# Download large files as stream
async for chunk in sandbox.get_file_stream("sha256_hash"):
    # Process chunk by chunk
    process_chunk(chunk)

# Get email headers
async for header_chunk in sandbox.get_email_headers(email_file):
    print(header_chunk.decode())

🔧 Configuration

Proxy Support

async with Sandbox(
    key,
    proxy="http://proxy.company.com:8080",
) as sandbox:
    ...

Custom Timeouts

from aiohttp import ClientTimeout

async with Sandbox(
    key,
    default_timeout=ClientTimeout(
        total=600,
        connect=60,
        sock_read=300,
    ),
) as sandbox:
    ...

Upload Semaphore Control

# Limit concurrent uploads
async with Sandbox(
    key,
    upload_semaphore_size=3,  # Max 3 concurrent uploads
) as sandbox:
    ...

🤝 Contributing

We welcome contributions to the project! Whether you're fixing bugs, adding features, improving documentation, or helping other users, every contribution is valuable.

Please read our Contributing Guide for detailed information.

📋 License

This project is licensed under the MIT License. See the LICENSE file for details.

📞 Support

🙏 Acknowledgments

  • PT ESC Malware Detection — PT Sandbox development team
  • Security Experts Community — information security experts community
  • All project contributors

Metadata

Release files for ptsandbox 5.1.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ptsandbox 5.1.6
File Size Uploaded
ptsandbox-5.1.6.tar.gz 58.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for ptsandbox 5.1.6
File Interpreter ABI Platform
ptsandbox-5.1.6-py3-none-any.whl Python 3 none any Details

Total release size: 137.2 kB

Release files / ptsandbox-5.1.6.tar.gz

Download URL ptsandbox-5.1.6.tar.gz
Size 58.4 kB
Tags Source
SHA-256 checksum
How to use checksums
9f518eb9bb5329f3e8712fd4fd043dafc1764c5ff94853c5b0980520e37d3329
BLAKE2b-256 checksum
How to use checksums
8cf765c8a3c4ccf8eab2f38200a2d78eaa90fe500bf382620dfc985be01f5848
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / ptsandbox-5.1.6-py3-none-any.whl

Download URL ptsandbox-5.1.6-py3-none-any.whl
Size 78.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2519c54d15632fd87ea939a8a08223dcdd28078a7857e0566639f9a9255724f1
BLAKE2b-256 checksum
How to use checksums
5ad4442b8dcc6a3b91392e82cd469341cd0e36a2e00c36c327692805ba119699
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release history Release notifications | RSS feed

This release

5.1.6 This release

2 release files

5.1.5

2 release files

5.1.4

2 release files

5.1.3

2 release files

5.1.2

2 release files

5.1.1

2 release files

5.1.0

2 release files

5.0.14

2 release files

5.0.13

2 release files

5.0.11

2 release files

5.0.10

2 release files

5.0.9

2 release files

5.0.8

2 release files

5.0.7

2 release files

5.0.6

2 release files

5.0.5

2 release files

5.0.4

2 release files

5.0.3

2 release files

5.0.2

2 release files

5.0.1

2 release files

5.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page