CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyarmor

A command-line tool for obfuscating Python scripts, binding obfuscated scripts to specific machines, and setting expiration dates

Pending
Overview
Eval results
Files

platform-support.mddocs/

Platform Support

PyArmor provides comprehensive cross-platform obfuscation with support for 40+ target platforms including Windows, Linux, macOS, FreeBSD, and Android. The platform system handles automatic detection, library management, and cross-compilation for diverse deployment environments.

Capabilities

Platform Detection and Information

Hardware Information Functions

Display and query hardware information for device binding and platform identification.

def show_hd_info(name: str = None) -> str:
    """
    Display hardware information for binding and platform identification.
    
    Args:
        name (str, optional): Specific hardware component to query
            - 'disk': Hard disk serial numbers
            - 'mac': Network MAC addresses
            - 'ipv4': IPv4 network addresses
            - 'domain': Domain name information
            - 'cpu': CPU identification
            - None: All available hardware information
    
    Returns:
        str: Formatted hardware information string
    
    Example output:
        Hardware information:
        Disk serial number: ABCD1234567890EFGH
        MAC address: 00:11:22:33:44:55, AA:BB:CC:DD:EE:FF
        IPv4 address: 192.168.1.100, 10.0.0.50
        Domain name: workstation.company.com
        CPU info: Intel64 Family 6 Model 142 Stepping 10
    """

def get_platform_name() -> str:
    """
    Get current system platform specification.
    
    Returns:
        str: Platform specification in format 'os.architecture'
    
    Examples:
        'linux.x86_64'    # Linux 64-bit Intel/AMD
        'windows.x86_64'  # Windows 64-bit Intel/AMD  
        'darwin.x86_64'   # macOS Intel
        'darwin.arm64'    # macOS Apple Silicon
        'linux.aarch64'   # Linux ARM64
    """

def format_platform(system: str = None, machine: str = None) -> str:
    """
    Format platform specification from system and machine info.
    
    Args:
        system (str, optional): Operating system name (auto-detected if None)
        machine (str, optional): Machine architecture (auto-detected if None)
    
    Returns:
        str: Formatted platform specification
        
    System mappings:
        'Linux' -> 'linux'
        'Windows' -> 'windows'  
        'Darwin' -> 'darwin'
        'FreeBSD' -> 'freebsd'
        'CYGWIN_NT-*' -> 'cygwin'
        
    Architecture mappings:
        'x86_64', 'AMD64' -> 'x86_64'
        'i386', 'i686' -> 'x86'
        'aarch64', 'arm64' -> 'aarch64' or 'arm64' (macOS)
        'armv7l' -> 'armv7'
    """

Platform Library Management

Library Download and Management

Download and manage platform-specific runtime libraries for cross-platform obfuscation.

def download_pytransform(platname: str, **kwargs) -> None:
    """
    Download platform-specific PyTransform runtime library.
    
    Args:
        platname (str): Target platform specification
        **kwargs: Download options
            - update (bool): Force update existing library (default: False)
            - timeout (float): Download timeout in seconds (default: 6.0)
            - url (str): Custom download URL base
            - output (str): Custom output directory
    
    Raises:
        DownloadError: If download fails or times out
        PlatformError: If platform is not supported
        NetworkError: If network connection fails
        
    Example platforms:
        'linux.x86_64', 'windows.x86_64', 'darwin.x86_64',
        'linux.aarch64', 'android.aarch64', 'freebsd.x86_64'
    """

def check_cross_platform(platforms: list, **kwargs) -> None:
    """
    Validate cross-platform obfuscation configuration and requirements.
    
    Args:
        platforms (list): List of target platform specifications
        **kwargs: Validation options
            - enable_bcc (bool): Check BCC mode compatibility
            - enable_themida (bool): Check Themida compatibility
            - download (bool): Auto-download missing libraries
    
    Raises:
        PlatformError: If platform combination is invalid
        CompatibilityError: If features are incompatible with platforms
        LibraryError: If required libraries are missing
        
    Validation checks:
        - Platform availability and support status
        - Feature compatibility (BCC, Themida, etc.)
        - Required library availability
        - Cross-platform restriction conflicts
    """

def list_available_platforms() -> list:
    """
    Get list of all supported platform specifications.
    
    Returns:
        list: All supported platform specifications
        
    Categories:
        - Windows: windows.x86_64, windows.x86
        - Linux: linux.x86_64, linux.x86, linux.aarch64, linux.armv7
        - macOS: darwin.x86_64, darwin.arm64  
        - FreeBSD: freebsd.x86_64
        - Android: android.x86_64, android.x86, android.aarch64, android.armv7
        - Alpine: alpine.x86_64, alpine.aarch64
        - Specialized: linux.mips32el, linux.mips64el, linux.ppc64le, linux.riscv64
    """

def get_library_path(platname: str) -> str:
    """
    Get local path to platform-specific runtime library.
    
    Args:
        platname (str): Platform specification
        
    Returns:
        str: Path to runtime library file
        
    Raises:
        LibraryError: If library not found or not downloaded
    """

Cross-Platform Obfuscation

Multi-Platform Generation

Generate obfuscated scripts compatible with multiple target platforms.

def generate_cross_platform_runtime(capsule, output: str, platforms: list, **kwargs) -> None:
    """
    Generate runtime package supporting multiple platforms.
    
    Args:
        capsule: Protection capsule
        output (str): Output directory
        platforms (list): Target platform specifications
        **kwargs: Runtime options
            - shared (bool): Generate shared runtime package
            - suffix (str): Runtime file suffix
            - bootstrap (int): Bootstrap generation mode
    
    Generated structure:
        runtime/
        ├── __init__.py
        ├── linux/
        │   └── x86_64/
        │       └── _pytransform.so
        ├── windows/  
        │   └── x86_64/
        │       └── _pytransform.dll
        └── darwin/
            └── x86_64/
                └── _pytransform.dylib
    """

def obfuscate_for_platforms(scripts: list, platforms: list, **kwargs) -> dict:
    """
    Obfuscate scripts for multiple target platforms.
    
    Args:
        scripts (list): List of script file paths
        platforms (list): Target platform specifications  
        **kwargs: Obfuscation options
            - output (str): Base output directory
            - shared_runtime (bool): Use shared runtime package
            - platform_suffix (bool): Add platform suffix to output
    
    Returns:
        dict: Mapping of platforms to output directories
        
    Example output structure:
        dist/
        ├── linux.x86_64/
        │   ├── main.py
        │   └── pyarmor_runtime/
        ├── windows.x86_64/
        │   ├── main.py  
        │   └── pyarmor_runtime/
        └── shared_runtime/  # If shared_runtime=True
            └── pyarmor_runtime/
    """

Platform-Specific Features

Platform Capability Detection

def get_platform_features(platname: str) -> dict:
    """
    Get available features for specific platform.
    
    Args:
        platname (str): Platform specification
        
    Returns:
        dict: Available features and capabilities
            - bcc_supported (bool): BCC mode support
            - jit_supported (bool): JIT compilation support
            - rft_supported (bool): RFT transformation support  
            - themida_supported (bool): Themida protection support
            - vm_supported (bool): VM mode support
            - architectures (list): Supported architectures
            - max_protection_level (int): Maximum protection level
    
    Example return:
        {
            'bcc_supported': True,
            'jit_supported': True, 
            'rft_supported': True,
            'themida_supported': False,  # Windows only
            'vm_supported': True,
            'architectures': ['x86_64'],
            'max_protection_level': 5
        }
    """

def check_platform_compatibility(platname: str, features: list) -> dict:
    """
    Check feature compatibility for specific platform.
    
    Args:
        platname (str): Platform specification
        features (list): Features to check compatibility
    
    Returns:
        dict: Compatibility results
            - compatible (bool): Overall compatibility
            - supported_features (list): Supported features
            - unsupported_features (list): Unsupported features
            - warnings (list): Compatibility warnings
    """

Embedded and Specialized Platforms

Embedded System Support

def configure_embedded_platform(platname: str, **kwargs) -> dict:
    """
    Configure obfuscation for embedded systems and IoT devices.
    
    Args:
        platname (str): Embedded platform specification
        **kwargs: Embedded-specific options
            - memory_limit (int): Memory usage limit in MB
            - minimal_runtime (bool): Use minimal runtime package
            - startup_optimization (bool): Optimize for fast startup
            - size_optimization (bool): Optimize for small size
    
    Returns:
        dict: Optimized configuration for embedded platform
        
    Supported embedded platforms:
        - linux.armv7 (Raspberry Pi, BeagleBone)
        - linux.aarch64 (Raspberry Pi 4, Jetson Nano)
        - linux.mips32el (OpenWrt routers)
        - android.armv7 (ARM Android devices)
        - android.aarch64 (ARM64 Android devices)
    """

def optimize_for_container(platname: str, container_type: str) -> dict:
    """
    Optimize obfuscation for containerized deployment.
    
    Args:
        platname (str): Container platform specification
        container_type (str): Container type ('docker', 'podman', 'alpine')
        
    Returns:
        dict: Container-optimized configuration
        
    Optimizations:
        - Minimal runtime dependencies
        - Static linking where possible
        - Reduced file system footprint
        - Container-friendly licensing
    """

Platform Constants and Mappings

# Supported platforms by category
WINDOWS_PLATFORMS = [
    'windows.x86_64',    # Windows 64-bit
    'windows.x86',       # Windows 32-bit
    'cygwin.x86_64'      # Cygwin environment
]

LINUX_PLATFORMS = [
    'linux.x86_64',     # Linux Intel/AMD 64-bit
    'linux.x86',        # Linux Intel/AMD 32-bit
    'linux.aarch64',    # Linux ARM 64-bit
    'linux.armv7',      # Linux ARM 32-bit
    'linux.mips32el',   # Linux MIPS 32-bit little-endian
    'linux.mips64el',   # Linux MIPS 64-bit little-endian
    'linux.ppc64le',    # Linux PowerPC 64-bit little-endian
    'linux.riscv64'     # Linux RISC-V 64-bit
]

DARWIN_PLATFORMS = [
    'darwin.x86_64',    # macOS Intel
    'darwin.arm64'      # macOS Apple Silicon
]

FREEBSD_PLATFORMS = [
    'freebsd.x86_64'    # FreeBSD 64-bit
]

ANDROID_PLATFORMS = [
    'android.x86_64',   # Android Intel/AMD 64-bit
    'android.x86',      # Android Intel/AMD 32-bit
    'android.aarch64',  # Android ARM 64-bit
    'android.armv7'     # Android ARM 32-bit
]

ALPINE_PLATFORMS = [
    'alpine.x86_64',    # Alpine Linux 64-bit
    'alpine.aarch64',   # Alpine Linux ARM 64-bit
    'alpine.mips32el',  # Alpine Linux MIPS 32-bit
    'alpine.mips64el',  # Alpine Linux MIPS 64-bit
    'alpine.ppc64le',   # Alpine Linux PowerPC 64-bit
    'alpine.riscv64'    # Alpine Linux RISC-V 64-bit
]

# Platform feature matrix
PLATFORM_FEATURES = {
    'windows.x86_64': {
        'bcc': True, 'jit': True, 'rft': True, 'themida': True, 'vm': True
    },
    'linux.x86_64': {
        'bcc': True, 'jit': True, 'rft': True, 'themida': False, 'vm': True
    },
    'darwin.x86_64': {
        'bcc': True, 'jit': True, 'rft': True, 'themida': False, 'vm': True
    },
    'darwin.arm64': {
        'bcc': True, 'jit': True, 'rft': True, 'themida': False, 'vm': True
    },
    'linux.aarch64': {
        'bcc': True, 'jit': False, 'rft': True, 'themida': False, 'vm': True
    }
}

Usage Examples

Platform Information

from pyarmor import utils

# Show all hardware information
print(utils.show_hd_info())

# Show specific hardware info
print("MAC addresses:", utils.show_hd_info('mac'))
print("Disk serials:", utils.show_hd_info('disk'))
print("IP addresses:", utils.show_hd_info('ipv4'))

# Get current platform
current_platform = utils.get_platform_name()
print(f"Current platform: {current_platform}")

# Format custom platform
custom_platform = utils.format_platform('Linux', 'aarch64')
print(f"Custom platform: {custom_platform}")

Cross-Platform Library Management

# List all supported platforms
platforms = utils.list_available_platforms()
print("Supported platforms:")
for platform in platforms:
    print(f"  {platform}")

# Download libraries for target platforms
target_platforms = ['linux.x86_64', 'windows.x86_64', 'darwin.x86_64']

for platform in target_platforms:
    try:
        print(f"Downloading library for {platform}")
        utils.download_pytransform(platform, update=True, timeout=30.0)
        print(f"  Success")
    except Exception as e:
        print(f"  Failed: {e}")

# Validate cross-platform setup
try:
    utils.check_cross_platform(target_platforms, download=True)
    print("Cross-platform setup validated")
except Exception as e:
    print(f"Validation failed: {e}")

Multi-Platform Obfuscation

from pyarmor import utils

# Initialize PyArmor
utils.pytransform_bootstrap()

# Target platforms for deployment
platforms = [
    'linux.x86_64',    # Linux servers
    'windows.x86_64',  # Windows desktops
    'darwin.x86_64',   # macOS Intel
    'darwin.arm64',    # macOS Apple Silicon
    'linux.aarch64'    # ARM servers (Raspberry Pi, AWS Graviton)
]

# Generate capsule
capsule = utils.make_capsule()

# Generate cross-platform runtime
utils.generate_cross_platform_runtime(
    capsule, 
    "dist/runtime", 
    platforms,
    shared=True,
    bootstrap=1
)

# Obfuscate scripts for all platforms
scripts = ['main.py', 'module1.py', 'module2.py']

for platform in platforms:
    output_dir = f"dist/{platform}"
    print(f"Obfuscating for {platform}")
    
    # Platform-specific obfuscation
    for script in scripts:
        utils.encrypt_script(
            capsule,
            script,
            f"{output_dir}/{script}",
            platform=platform,
            obf_code=2,
            mix_str=1
        )
    
    # Copy runtime for platform
    utils.make_runtime(capsule, output_dir, platform=platform)

Platform-Specific Optimization

# Configure for embedded Linux ARM
embedded_config = utils.configure_embedded_platform(
    'linux.armv7',
    memory_limit=128,        # 128MB memory limit
    minimal_runtime=True,    # Minimal runtime package
    startup_optimization=True,  # Fast startup
    size_optimization=True   # Small binary size
)

# Apply embedded configuration
utils.encrypt_script(
    capsule,
    'embedded_app.py',
    'dist/embedded/embedded_app.py',
    **embedded_config
)

# Container optimization for Docker
container_config = utils.optimize_for_container(
    'alpine.x86_64',
    'docker'
)

# Apply container configuration
utils.encrypt_script(
    capsule,
    'container_app.py', 
    'dist/container/container_app.py',
    **container_config
)

Feature Compatibility Checking

# Check platform capabilities
def check_platform_setup(platforms, required_features):
    """Check if platforms support required features."""
    
    for platform in platforms:
        print(f"\nChecking {platform}:")
        
        # Get platform features
        features = utils.get_platform_features(platform)
        print(f"  Available features: {features}")
        
        # Check compatibility
        compat = utils.check_platform_compatibility(platform, required_features)
        
        if compat['compatible']:
            print(f"  ✓ Compatible")
        else:
            print(f"  ✗ Incompatible")
            print(f"    Unsupported: {compat['unsupported_features']}")
            
        if compat['warnings']:
            print(f"    Warnings: {compat['warnings']}")

# Check setup for advanced features
required_features = ['bcc', 'jit', 'rft']
target_platforms = ['linux.x86_64', 'windows.x86_64', 'linux.aarch64']

check_platform_setup(target_platforms, required_features)

Advanced Cross-Platform Deployment

# Enterprise multi-platform deployment
def deploy_cross_platform(app_files, target_environments):
    """Deploy application across multiple environments."""
    
    capsule = utils.make_capsule()
    deployment_map = {}
    
    for env_name, env_config in target_environments.items():
        platforms = env_config['platforms']
        features = env_config.get('features', {})
        
        print(f"Preparing {env_name} deployment...")
        
        # Validate platform compatibility
        utils.check_cross_platform(platforms, **features)
        
        # Create environment-specific output
        env_output = f"dist/{env_name}"
        
        # Configure obfuscation for environment
        obf_options = {
            'obf_code': env_config.get('protection_level', 2),
            'mix_str': env_config.get('string_protection', True),
            'restrict': env_config.get('restrict_mode', 2),
            **features
        }
        
        # Generate runtime for all platforms in environment
        utils.generate_cross_platform_runtime(
            capsule,
            f"{env_output}/runtime",
            platforms,
            shared=True
        )
        
        # Obfuscate application files
        for app_file in app_files:
            utils.encrypt_script(
                capsule,
                app_file,
                f"{env_output}/{app_file}",
                platform=",".join(platforms),
                **obf_options
            )
        
        deployment_map[env_name] = {
            'output': env_output,
            'platforms': platforms,
            'files': app_files
        }
    
    return deployment_map

# Define deployment environments
environments = {
    'production': {
        'platforms': ['linux.x86_64', 'windows.x86_64'],
        'protection_level': 5,  # Maximum protection
        'string_protection': True,
        'restrict_mode': 3,
        'features': {'enable_bcc': True, 'enable_rft': True}
    },
    'staging': {
        'platforms': ['linux.x86_64'],
        'protection_level': 2,  # Moderate protection
        'features': {'enable_jit': True}
    },
    'embedded': {
        'platforms': ['linux.armv7', 'linux.aarch64'],
        'protection_level': 1,  # Basic protection for performance
        'memory_limit': 256,
        'minimal_runtime': True
    }
}

# Deploy application
app_files = ['main.py', 'core.py', 'utils.py']
deployment = deploy_cross_platform(app_files, environments)

print("Deployment complete:")
for env, info in deployment.items():
    print(f"  {env}: {info['output']} ({len(info['platforms'])} platforms)")

Error Handling

from pyarmor.utils import DownloadError, PlatformError, LibraryError

try:
    # Platform operations
    utils.download_pytransform('linux.x86_64')
    utils.check_cross_platform(['invalid.platform'])
    
except DownloadError as e:
    print(f"Download failed: {e}")
    print("Check network connection and try again")
    
except PlatformError as e:
    print(f"Platform error: {e}")
    print("Check platform specification format")
    
except LibraryError as e:
    print(f"Library error: {e}")
    print("Try downloading platform libraries manually")

# Safe platform operations
def safe_download_platform(platform, retries=3):
    """Safely download platform library with retries."""
    for attempt in range(retries):
        try:
            utils.download_pytransform(platform, timeout=30.0)
            return True
        except Exception as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            if attempt == retries - 1:
                return False
    return False

# Example usage
if safe_download_platform('linux.x86_64'):
    print("Platform library downloaded successfully")
else:
    print("Failed to download platform library after all retries")

Install with Tessl CLI

npx tessl i tessl/pypi-pyarmor

docs

cli.md

configuration.md

index.md

licensing.md

obfuscation.md

platform-support.md

project-management.md

tile.json