Skip to main content

Async API connector for PT Sandbox instances

Project description

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 (recommended)

uv add ptsandbox

Nix

# Coming soon

🔧 Requirements

  • Python 3.11+
  • aiohttp 3.11.15+
  • pydantic 2.11.1+
  • loguru 0.7.3+

🚀 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",
    )
    
    # Initialize client
    sandbox = Sandbox(key)
    
    # 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"
    )
    
    sandbox = Sandbox(key)
    
    # Scan suspicious URL
    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"
        )
    )
    
    sandbox = Sandbox(key)
    
    # Authorize in UI API
    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]):
    sandbox = Sandbox(SandboxKey(...))
    
    # 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.models 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

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

Custom Timeouts

from aiohttp import ClientTimeout

sandbox = Sandbox(
    key,
    default_timeout=ClientTimeout(
        total=600,
        connect=60,
        sock_read=300
    )
)

Upload Semaphore Control

# Limit concurrent uploads
sandbox = Sandbox(
    key,
    upload_semaphore_size=3  # Max 3 concurrent uploads
)

🤝 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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ptsandbox-5.0.11.tar.gz (51.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ptsandbox-5.0.11-py3-none-any.whl (64.8 kB view details)

Uploaded Python 3

File details

Details for the file ptsandbox-5.0.11.tar.gz.

File metadata

  • Download URL: ptsandbox-5.0.11.tar.gz
  • Upload date:
  • Size: 51.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.4

File hashes

Hashes for ptsandbox-5.0.11.tar.gz
Algorithm Hash digest
SHA256 d1dfd581733409b251895e2b954174cdd43e44349f66dfdeba70f15f4252f426
MD5 857833f6e19487ad88c5e115452c6bc6
BLAKE2b-256 303f8396fb5272b7ee406b0b97d28c81e57a86f3e4afc76d9fbe527d28d0ef8d

See more details on using hashes here.

File details

Details for the file ptsandbox-5.0.11-py3-none-any.whl.

File metadata

  • Download URL: ptsandbox-5.0.11-py3-none-any.whl
  • Upload date:
  • Size: 64.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.4

File hashes

Hashes for ptsandbox-5.0.11-py3-none-any.whl
Algorithm Hash digest
SHA256 fd748e1379e95312dc8ed8c6a13bbf16b12ebf827f2bd9587c88e9a027795039
MD5 c753d15bb81a74cbd3f995e00770dedf
BLAKE2b-256 ef67c98aa93e1ec437a2db4f5f28b958d9ee1465b4cbd529767d4f980214679a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page