### Install anyrun-sdk using pip Source: https://github.com/anyrun/anyrun-sdk/blob/main/README.md Install the SDK using pip for quick integration. ```bash pip install anyrun-sdk ``` -------------------------------- ### Install anyrun-sdk manually Source: https://github.com/anyrun/anyrun-sdk/blob/main/README.md Install the SDK manually by cloning the repository and using pyproject.toml. ```bash git clone git@github.com:anyrun/anyrun-sdk.git cd anyrun-sdk python -m pip install . ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/anyrun/anyrun-sdk/blob/main/CONTRIBUTING.md Install the project's development dependencies using pip. ```bash pip install -e .[dev] ``` -------------------------------- ### Basic Sandbox API Usage in Python Source: https://github.com/anyrun/anyrun-sdk/blob/main/README.md This example demonstrates submitting a URL for analysis, monitoring its status, retrieving the verdict and report, and finally deleting the task. Ensure the ANY_RUN_Sandbox_API_KEY environment variable is set. ```python import os from anyrun.connectors import SandboxConnector def main(): with SandboxConnector.android(api_key) as connector: # Initialize the url analysis analysis_id = connector.run_url_analysis('https://any.run') print(f'Analysis successfully initialized. Analysis uuid: {analysis_id}') # View analysis status in real time for status in connector.get_task_status(analysis_id): print(status) # Get analysis verdict verdict = connector.get_analysis_verdict(analysis_id) if verdict in ('Suspicious', 'Malicious'): # Get analysis report connector.get_analysis_report(analysis_id, report_format='html', filepath='.') # Remove the analysis from history connector.delete_task(analysis_id) if __name__ == '__main__': # Setup ANY.RUN api key api_key = os.getenv('ANY_RUN_Sandbox_API_KEY') main() ``` -------------------------------- ### Run File Analysis Asynchronously on Android Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Performs asynchronous file analysis on Android. Requires an API key. This example demonstrates using `async` and `await` for running tasks and retrieving status and reports. ```python async def run_android(): async with SandboxConnector.android(api_key=api_key) as connector: task_uuid = await connector.run_file_analysis_async( filepath="./app.apk", opt_timeout=240, opt_automated_interactivity=True, ) async for status in connector.get_task_status_async(task_uuid): print(status) report = await connector.get_analysis_report_async(task_uuid) return report asyncio.run(run_android()) ``` -------------------------------- ### macOS File and URL Analysis Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Execute file analysis for macOS and perform URL analysis using specified browsers. This section demonstrates initiating tasks and setting parameters like timeout and start folder. ```APIDOC ## macOS File and URL Analysis ### Description Execute file analysis for macOS and perform URL analysis using specified browsers. This section demonstrates initiating tasks and setting parameters like timeout and start folder. ### Method ```python with SandboxConnector.macos(api_key=api_key) as connector: task_uuid = connector.run_file_analysis( filepath="./macos_sample.dmg", opt_timeout=240, obj_ext_startfolder="downloads", ) task_uuid2 = connector.run_url_analysis( obj_url="https://example.com", obj_ext_browser="Safari", # "Safari", "Google Chrome", "Mozilla Firefox" ) ``` ``` -------------------------------- ### Git Branch Title Template Source: https://github.com/anyrun/anyrun-sdk/blob/main/CONTRIBUTING.md Template for naming Git branches, typically starting with 'feature/public-' followed by a short description. ```git git checkout -b Branch title template: feature/public-[TaskShortDescription] Example: feature/public-integration-tests-improvements ``` -------------------------------- ### Initialization & Authentication Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Demonstrates how to initialize and authenticate with ANY.RUN connectors using API keys. It covers both synchronous and asynchronous usage with context managers, proxy configuration, SSL settings, and timeout options. Exception handling for authentication errors is also shown. ```APIDOC ## Initialization & Authentication All connectors share a common constructor signature inherited from `AnyRunConnector`. The `api_key` parameter is the only required argument. ```python import os from anyrun.connectors import SandboxConnector, LookupConnector, FeedsConnector, YaraLookupConnector from anyrun.utils.exceptions import RunTimeException api_key = os.environ["ANY_RUN_API_KEY"] # Synchronous context manager with LookupConnector( api_key=api_key, proxy="https://proxy-host:8080", proxy_username="user", proxy_password="pass", verify_ssl=None, # None = enabled, path = CA bundle, False = disabled timeout=300, # seconds enable_requests=False, # True = use requests library instead of aiohttp ) as connector: auth = connector.check_authorization() print(auth) # {'data': {'auth': True}} # Async context manager import asyncio async def main(): async with LookupConnector(api_key=api_key) as connector: auth = await connector.check_authorization_async() print(auth) asyncio.run(main()) # Exception handling try: with LookupConnector(api_key="bad-key") as connector: connector.check_authorization() except RunTimeException as e: print(str(e)) # [AnyRun Exception] Status code: 401. Description: Unauthorized print(e.status_code) # '401' print(e.description) # 'Unauthorized' print(e.json) # {'description': 'Unauthorized', 'code': '401'} ``` ``` -------------------------------- ### Initialize and Authenticate Asynchronously Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Shows how to use an asynchronous context manager (`async with`) to initialize a LookupConnector and check authorization. Requires `asyncio` to run. ```python import asyncio async def main(): async with LookupConnector(api_key=api_key) as connector: auth = await connector.check_authorization_async() print(auth) asyncio.run(main()) ``` -------------------------------- ### Initialize and Authenticate Synchronously with Proxy Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Demonstrates synchronous initialization of a LookupConnector with proxy settings and SSL verification options. The `check_authorization` method verifies the API key. ```python import os from anyrun.connectors import SandboxConnector, LookupConnector, FeedsConnector, YaraLookupConnector from anyrun.utils.exceptions import RunTimeException api_key = os.environ["ANY_RUN_API_KEY"] # Synchronous context manager with LookupConnector( api_key=api_key, proxy="https://proxy-host:8080", proxy_username="user", proxy_password="pass", verify_ssl=None, # None = enabled, path = CA bundle, False = disabled timeout=300, # seconds enable_requests=False, # True = use requests library instead of aiohttp ) as connector: auth = connector.check_authorization() print(auth) # {'data': {'auth': True}} ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/anyrun/anyrun-sdk/blob/main/CONTRIBUTING.md Change the current directory to the anyrun-sdk project folder. ```bash cd anyrun-sdk ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/anyrun/anyrun-sdk/blob/main/CONTRIBUTING.md Create a new Python virtual environment and activate it for development. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Windows File Analysis with SandboxConnector Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Submit a file for analysis on Windows. Configure environment, network, privacy, and other options. Poll for status, retrieve reports (JSON, IOC, HTML), download artifacts, and manage the task. ```python import os from anyrun.connectors import SandboxConnector from anyrun.utils.exceptions import RunTimeException api_key = os.environ["ANY_RUN_API_KEY"] with SandboxConnector.windows(api_key=api_key) as connector: # Submit a file for analysis with open("malware_sample.exe", "rb") as f: file_bytes = f.read() task_uuid = connector.run_file_analysis( file_content=file_bytes, filename="malware_sample.exe", env_version="10", # "7", "10", "11", "server 2025" env_bitness=64, env_type="complete", # "complete" or "development" env_locale="en-US", opt_network_connect=True, opt_network_fakenet=False, opt_network_tor=False, opt_network_mitm=False, opt_kernel_heavyevasion=False, opt_privacy_type="bylink", # "public", "bylink", "owner", "byteam" opt_timeout=240, # 10–660 seconds opt_automated_interactivity=True, opt_auto_delete_after="month", # "day", "week", "2 weeks", "month" obj_ext_startfolder="temp", # "desktop","home","downloads","appdata","temp","windows","root" obj_ext_cmd=None, # optional command-line arguments obj_force_elevation=False, auto_confirm_uac=True, user_tags="ransomware,suspicious", ) print(f"Task UUID: {task_uuid}") # Poll status until completion for status in connector.get_task_status(task_uuid, simplify=True): # {'status': 'RUNNING', 'seconds_remaining': 180, 'info': '...'} print(status) # Retrieve JSON report report = connector.get_analysis_report(task_uuid, report_format="json") # Retrieve IOC report filtered by reputation iocs = connector.get_analysis_report( task_uuid, report_format="ioc", ioc_reputation="malicious", # "all", "suspicious", "malicious" ) # Save HTML report to disk connector.get_analysis_report(task_uuid, report_format="html", filepath="./report.html") # Human-readable verdict verdict = connector.get_analysis_verdict(task_uuid) print(verdict) # "No threats detected" | "Suspicious activity" | "Malicious activity" # Download PCAP (returns bytes or saves to file) pcap_bytes = connector.download_pcap(task_uuid) connector.download_pcap(task_uuid, filepath="./output/") # Download file sample as password-protected ZIP (password: infected) connector.download_file_sample(task_uuid, filepath="./samples/") # Extend running task by 60 seconds connector.add_time_to_task(task_uuid) # Stop a running task connector.stop_task(task_uuid) # Delete from history connector.delete_task(task_uuid) ``` -------------------------------- ### Windows URL and Download Analysis with SandboxConnector Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Perform URL analysis by opening it in a browser or analyze a file downloaded from a URL. Configure environment, network, and privacy settings. ```python import os from anyrun.connectors import SandboxConnector api_key = os.environ["ANY_RUN_API_KEY"] with SandboxConnector.windows(api_key=api_key) as connector: # URL analysis — open in browser task_uuid = connector.run_url_analysis( obj_url="https://suspicious-site.example.com/phishing", env_version="10", env_bitness=64, opt_network_connect=True, opt_timeout=120, obj_ext_browser="Google Chrome", # "Microsoft Edge", "Internet Explorer", "Google Chrome", "Mozilla Firefox" opt_privacy_type="bylink", user_tags="phishing", ) # Download analysis — fetch file from URL then analyze it task_uuid2 = connector.run_download_analysis( obj_url="https://malware-distrib.example.com/payload.exe", env_version="10", opt_timeout=240, obj_ext_startfolder="downloads", obj_ext_useragent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)", opt_privacy_hidesource=True, # Hide the source URL in the report ) for status in connector.get_task_status(task_uuid2, simplify=True): print(status) report = connector.get_analysis_report(task_uuid2) print(report["data"]["analysis"]["content"]["mainObject"]["info"]["verdict"]) ``` -------------------------------- ### Generating Intelligence URL with AnyRun SDK Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Create a URL for the ANY.RUN intelligence lookup service. This is useful for directly linking to detailed information about a specific indicator. ```python print(LookupSummary.intelligence_url("malware-c2.example.com")) ``` -------------------------------- ### GenericEnvironment Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Override the target endpoint URL for any connector using a context manager, or make raw authenticated HTTP requests to arbitrary ANY.RUN API paths. ```APIDOC ## GenericEnvironment — Custom Endpoint Requests Override the target endpoint URL for any connector using a context manager, or make raw authenticated HTTP requests to arbitrary ANY.RUN API paths. ### Raw request to a custom endpoint ```python generic = GenericEnvironment("https://intelligence.any.run/api/search") result = generic.generic_request( api_key=api_key, method="POST", json={"query": 'destinationIP:"198.51.100.1"'}, parse_response=True, ) print(result) ``` ### Override endpoint used by a standard connector ```python with GenericEnvironment("https://custom-proxy.internal/api/v1/intelligence/api/search"): with LookupConnector(api_key=api_key) as connector: result = connector.get_intelligence(destination_ip="198.51.100.1") print(result) ``` ### Async raw request ```python async def async_generic(): generic = GenericEnvironment("https://api.any.run/v1/analysis") result = await generic.generic_request_async( api_key=api_key, method="GET", parse_response=True, ) print(result) asyncio.run(async_generic()) ``` ``` -------------------------------- ### Handle API Errors with RunTimeException Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Illustrates how to catch `RunTimeException` to handle API errors, such as an invalid API key (401 Unauthorized). It shows how to access the status code, description, and JSON response from the exception. ```python # Exception handling try: with LookupConnector(api_key="bad-key") as connector: connector.check_authorization() except RunTimeException as e: print(str(e)) # [AnyRun Exception] Status code: 401. Description: Unauthorized print(e.status_code) # '401' print(e.description) # 'Unauthorized' print(e.json) # {'description': 'Unauthorized', 'code': '401'} ``` -------------------------------- ### Run File and URL Analysis on Linux Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Performs file and URL analysis on Linux environments (Ubuntu or Debian). Requires an API key. The `run_file_analysis` function can take optional parameters like timeout and run as root. The `run_url_analysis` function supports specifying the browser. ```python with SandboxConnector.linux(api_key=api_key) as connector: task_uuid = connector.run_file_analysis( filepath="./elf_sample", env_os="ubuntu", # "ubuntu" (22.04.2) or "debian" (12.2) opt_timeout=300, obj_ext_startfolder="home", run_as_root=True, obj_ext_extension=True, ) for status in connector.get_task_status(task_uuid): print(status) # URL analysis on Linux (Chrome or Firefox) task_uuid2 = connector.run_url_analysis( obj_url="https://example.com", env_os="debian", obj_ext_browser="Mozilla Firefox", ) ``` -------------------------------- ### SandboxConnector for Linux, macOS, and Android Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Factory methods are available to create OS-specific connectors for Linux, macOS, and Android analysis. ```python import os, asyncio from anyrun.connectors import SandboxConnector api_key = os.environ["ANY_RUN_API_KEY"] ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/anyrun/anyrun-sdk/blob/main/CONTRIBUTING.md Execute tests using pytest and generate a coverage report, highlighting missing lines. ```bash pytest --cov=anyrun --cov-report=term-missing -x ``` -------------------------------- ### Retrieve Analysis History, Environment, and Limits Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Retrieves personal and team analysis history, available environment options, API limits, and user-saved presets. Requires an API key. Pagination is supported for history retrieval. ```python import os from anyrun.connectors import SandboxConnector api_key = os.environ["ANY_RUN_API_KEY"] with SandboxConnector.windows(api_key=api_key) as connector: # Personal history (last 25 tasks) history = connector.get_analysis_history(team=False, skip=0, limit=25) for task in history: print(task["uuid"], task["verdict"]) # Team history with pagination page2 = connector.get_analysis_history(team=True, skip=25, limit=25) # Available environment options (OS versions, browsers, etc.) env = connector.get_user_environment() print(env) # API limits and quota limits = connector.get_user_limits() print(limits) # User-saved presets presets = connector.get_user_presets() for preset in presets: print(preset["name"]) ``` -------------------------------- ### Accessing File Metadata with AnyRun SDK Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Retrieve detailed metadata about a file, including its filename, path, extension, and various hash values. This is useful for identifying and tracking specific files within analyses. ```python file_meta = summary.file_meta() if file_meta: print(file_meta.filename) print(file_meta.filepath) print(file_meta.file_extension) print(file_meta.hashes.md5) print(file_meta.hashes.sha1) print(file_meta.hashes.sha256) print(file_meta.hashes.ssdeep) ``` -------------------------------- ### Run File and URL Analysis on macOS Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Performs file and URL analysis on macOS. Requires an API key. The `run_file_analysis` function takes a filepath and optional timeout. The `run_url_analysis` function takes a URL and browser choice. ```python with SandboxConnector.macos(api_key=api_key) as connector: task_uuid = connector.run_file_analysis( filepath="./macos_sample.dmg", opt_timeout=240, obj_ext_startfolder="downloads", ) task_uuid2 = connector.run_url_analysis( obj_url="https://example.com", obj_ext_browser="Safari", # "Safari", "Google Chrome", "Mozilla Firefox" ) ``` -------------------------------- ### Linux File and URL Analysis Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Perform file analysis and URL analysis on Linux environments using the SandboxConnector. This includes running analysis tasks and retrieving their status. ```APIDOC ## Linux File and URL Analysis ### Description Perform file analysis and URL analysis on Linux environments using the SandboxConnector. This includes running analysis tasks and retrieving their status. ### Method ```python with SandboxConnector.linux(api_key=api_key) as connector: task_uuid = connector.run_file_analysis( filepath="./elf_sample", env_os="ubuntu", # "ubuntu" (22.04.2) or "debian" (12.2) opt_timeout=300, obj_ext_startfolder="home", run_as_root=True, obj_ext_extension=True, ) for status in connector.get_task_status(task_uuid): print(status) # URL analysis on Linux (Chrome or Firefox) task_uuid2 = connector.run_url_analysis( obj_url="https://example.com", env_os="debian", obj_ext_browser="Mozilla Firefox", ) ``` ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/anyrun/anyrun-sdk/blob/main/CONTRIBUTING.md Stage all changes and commit them with a descriptive title. Replace `` with the commit message. ```bash git add . git commit -m ``` -------------------------------- ### General Error Handling with RunTimeException in AnyRun SDK Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Implement a general error handling pattern using a try-except block to catch RunTimeException. This allows for graceful handling of API errors, authentication failures, or connection problems. ```python from anyrun.utils.exceptions import RunTimeException from anyrun.connectors import SandboxConnector, LookupConnector, FeedsConnector import os api_key = os.environ["ANY_RUN_API_KEY"] try: with SandboxConnector.windows(api_key=api_key) as connector: task_uuid = connector.run_file_analysis(filepath="sample.exe") for status in connector.get_task_status(task_uuid): print(status) report = connector.get_analysis_report(task_uuid) except RunTimeException as e: # Human-readable representation print(str(e)) # [AnyRun Exception] Status code: 401. Description: Unauthorized # Programmatic access print(e.status_code) # '401' (string or int depending on source) print(e.description) # 'Unauthorized' print(e.json) # {'description': 'Unauthorized', 'code': '401'} # Branch on specific codes if e.status_code == "401": print("Invalid API key") elif e.status_code == "429": print("Rate limit exceeded — back off and retry") elif e.status_code == "500": print("Analysis failed to start or internal error") ``` -------------------------------- ### Android File Analysis (Async) Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Perform asynchronous file analysis on Android devices. This includes initiating the analysis, monitoring task status, and retrieving the final analysis report. ```APIDOC ## Android File Analysis (Async) ### Description Perform asynchronous file analysis on Android devices. This includes initiating the analysis, monitoring task status, and retrieving the final analysis report. ### Method ```python async def run_android(): async with SandboxConnector.android(api_key=api_key) as connector: task_uuid = await connector.run_file_analysis_async( filepath="./app.apk", opt_timeout=240, opt_automated_interactivity=True, ) async for status in connector.get_task_status_async(task_uuid): print(status) report = await connector.get_analysis_report_async(task_uuid) return report asyncio.run(run_android()) ``` ``` -------------------------------- ### Windows File Analysis Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Submit a file for analysis on a Windows environment. This method supports extensive configuration options for the analysis environment, network behavior, privacy, and task management. ```APIDOC ## run_file_analysis ### Description Submits a file for analysis on a Windows environment. Allows for detailed configuration of the analysis environment, network settings, privacy, and task options. ### Method `connector.run_file_analysis` ### Parameters - **file_content** (bytes) - Required - The content of the file to analyze. - **filename** (str) - Required - The name of the file. - **env_version** (str) - Optional - The Windows environment version (e.g., "7", "10", "11", "server 2025"). Defaults to "10". - **env_bitness** (int) - Optional - The environment bitness (32 or 64). Defaults to 64. - **env_type** (str) - Optional - The environment type ("complete" or "development"). Defaults to "complete". - **env_locale** (str) - Optional - The environment locale (e.g., "en-US"). Defaults to "en-US". - **opt_network_connect** (bool) - Optional - Enable network connections. Defaults to False. - **opt_network_fakenet** (bool) - Optional - Use fake network. Defaults to False. - **opt_network_tor** (bool) - Optional - Use Tor network. Defaults to False. - **opt_network_mitm** (bool) - Optional - Enable Man-in-the-Middle proxy. Defaults to False. - **opt_kernel_heavyevasion** (bool) - Optional - Enable heavy evasion techniques. Defaults to False. - **opt_privacy_type** (str) - Optional - Privacy setting ("public", "bylink", "owner", "byteam"). Defaults to "public". - **opt_timeout** (int) - Optional - Analysis timeout in seconds (10–660). Defaults to 120. - **opt_automated_interactivity** (bool) - Optional - Enable automated interactivity. Defaults to False. - **opt_auto_delete_after** (str) - Optional - Auto-delete task after a period ("day", "week", "2 weeks", "month"). Defaults to None. - **obj_ext_startfolder** (str) - Optional - Starting folder for analysis ("desktop", "home", "downloads", "appdata", "temp", "windows", "root"). Defaults to "temp". - **obj_ext_cmd** (str) - Optional - Optional command-line arguments to execute. Defaults to None. - **obj_force_elevation** (bool) - Optional - Force elevation. Defaults to False. - **auto_confirm_uac** (bool) - Optional - Automatically confirm UAC prompts. Defaults to False. - **user_tags** (str) - Optional - Comma-separated user tags for the task. ### Returns - **task_uuid** (str) - The unique identifier for the analysis task. ### Request Example ```python with open("malware_sample.exe", "rb") as f: file_bytes = f.read() task_uuid = connector.run_file_analysis( file_content=file_bytes, filename="malware_sample.exe", env_version="10", env_bitness=64, opt_network_connect=True, opt_timeout=240, opt_privacy_type="bylink", user_tags="ransomware,suspicious" ) ``` ``` -------------------------------- ### Windows Download Analysis Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Download a file from a URL and analyze the downloaded artifact on a Windows environment. Supports various options for download and analysis. ```APIDOC ## run_download_analysis ### Description Downloads a file from a given URL and analyzes the downloaded artifact on a Windows environment. Supports configuration for download source, environment, and analysis options. ### Method `connector.run_download_analysis` ### Parameters - **obj_url** (str) - Required - The URL to download the file from. - **env_version** (str) - Optional - The Windows environment version (e.g., "7", "10", "11", "server 2025"). Defaults to "10". - **opt_timeout** (int) - Optional - Analysis timeout in seconds. Defaults to 120. - **obj_ext_startfolder** (str) - Optional - Starting folder for analysis ("desktop", "home", "downloads", "appdata", "temp", "windows", "root"). Defaults to "temp". - **obj_ext_useragent** (str) - Optional - User-Agent string for the download request. - **opt_privacy_hidesource** (bool) - Optional - Hide the source URL in the report. Defaults to False. ### Returns - **task_uuid** (str) - The unique identifier for the analysis task. ### Request Example ```python task_uuid2 = connector.run_download_analysis( obj_url="https://malware-distrib.example.com/payload.exe", env_version="10", opt_timeout=240, obj_ext_startfolder="downloads", obj_ext_useragent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)", opt_privacy_hidesource=True ) ``` ``` -------------------------------- ### Create a New Local Branch Source: https://github.com/anyrun/anyrun-sdk/blob/main/CONTRIBUTING.md Create a new local Git branch for development. Replace `` with a descriptive name. ```bash git checkout -b ``` -------------------------------- ### SandboxConnector - History & Environment Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Retrieve past analysis tasks and query available environment options and user limits using the SandboxConnector. This allows users to access their analysis history, available environments, API limits, and saved presets. ```APIDOC ## SandboxConnector - History & Environment ### Description Retrieve past analysis tasks and query available environment options and user limits using the SandboxConnector. This allows users to access their analysis history, available environments, API limits, and saved presets. ### Method ```python import os from anyrun.connectors import SandboxConnector api_key = os.environ["ANY_RUN_API_KEY"] with SandboxConnector.windows(api_key=api_key) as connector: # Personal history (last 25 tasks) history = connector.get_analysis_history(team=False, skip=0, limit=25) for task in history: print(task["uuid"], task["verdict"]) # Team history with pagination page2 = connector.get_analysis_history(team=True, skip=25, limit=25) # Available environment options (OS versions, browsers, etc.) env = connector.get_user_environment() print(env) # API limits and quota limits = connector.get_user_limits() print(limits) # User-saved presets presets = connector.get_user_presets() for preset in presets: print(preset["name"]) ``` ``` -------------------------------- ### Task Management and Reporting Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Provides methods for retrieving task status, analysis reports in various formats, verdicts, and managing downloaded artifacts. ```APIDOC ## Task Management and Reporting Methods ### Description These methods allow users to monitor the status of analysis tasks, retrieve detailed reports, obtain a human-readable verdict, download network capture files (PCAP), download analyzed samples, and manage the lifecycle of a task. ### Methods - **`connector.get_task_status(task_uuid, simplify=False)`** - Retrieves the status of a given task. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - `simplify` (bool): If True, returns a simplified status dictionary. Defaults to False. - **Returns**: - An iterator yielding status dictionaries. - **`connector.get_analysis_report(task_uuid, report_format='json', filepath=None, ioc_reputation=None)`** - Retrieves the analysis report in the specified format. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - `report_format` (str): The desired report format ('json', 'ioc', 'html'). Defaults to 'json'. - `filepath` (str): If provided, saves the report to this file path. - `ioc_reputation` (str): Filter for IOC reports ('all', 'suspicious', 'malicious'). Only applicable when `report_format` is 'ioc'. - **Returns**: - Report data (dict for JSON, str for HTML, dict for IOC) or None if saved to file. - **`connector.get_analysis_verdict(task_uuid)`** - Retrieves a human-readable verdict for the analysis task. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - **Returns**: - A string representing the verdict (e.g., "No threats detected", "Suspicious activity", "Malicious activity"). - **`connector.download_pcap(task_uuid, filepath=None)`** - Downloads the PCAP (network capture) file for the task. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - `filepath` (str): If provided, saves the PCAP to this file path. - **Returns**: - PCAP data as bytes if `filepath` is None, otherwise None. - **`connector.download_file_sample(task_uuid, filepath=None)`** - Downloads the analyzed file sample, typically as a password-protected ZIP. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - `filepath` (str): If provided, saves the sample to this directory. - **Returns**: - None. The file is saved to the specified `filepath`. - **`connector.add_time_to_task(task_uuid, seconds=60)`** - Extends the running time of a task. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - `seconds` (int): The number of seconds to add. Defaults to 60. - **Returns**: - None. - **`connector.stop_task(task_uuid)`** - Stops a running analysis task. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - **Returns**: - None. - **`connector.delete_task(task_uuid)`** - Deletes a task from the analysis history. - **Parameters**: - `task_uuid` (str): The unique identifier of the task. - **Returns**: - None. ### Examples ```python # Poll status until completion for status in connector.get_task_status(task_uuid, simplify=True): print(status) # Retrieve JSON report report = connector.get_analysis_report(task_uuid, report_format="json") # Retrieve IOC report filtered by reputation iocs = connector.get_analysis_report( task_uuid, report_format="ioc", ioc_reputation="malicious", ) # Save HTML report to disk connector.get_analysis_report(task_uuid, report_format="html", filepath="./report.html") # Human-readable verdict verdict = connector.get_analysis_verdict(task_uuid) print(verdict) # Download PCAP pcap_bytes = connector.download_pcap(task_uuid) connector.download_pcap(task_uuid, filepath="./output/") # Download file sample connector.download_file_sample(task_uuid, filepath="./samples/") # Extend running task connector.add_time_to_task(task_uuid) # Stop a running task connector.stop_task(task_uuid) # Delete from history connector.delete_task(task_uuid) ``` ``` -------------------------------- ### Manual Pagination for TAXII STIX Feeds Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Manually paginate through TAXII STIX threat indicator feeds by repeatedly calling `get_taxii_stix` with the `next_page` token from the previous response until no `next` key is present. ```python # Manual pagination next_page = page.get("next") while next_page: page = connector.get_taxii_stix(collection="full", next_page=next_page) next_page = page.get("next") ``` -------------------------------- ### LookupConnector - Threat Intelligence Queries Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Query the ANY.RUN Threat Intelligence database using keyword filters or a raw query string. Supports both synchronous and asynchronous operations. ```APIDOC ## LookupConnector — Threat Intelligence Queries Query the ANY.RUN Threat Intelligence database using keyword filters or a raw query string. ### Method: `get_intelligence` This method allows querying the threat intelligence database. #### Parameters (Keyword Arguments): - `start_date` (str) - Optional - The start date for the query. - `end_date` (str) - Optional - The end date for the query. - `domain_name` (str) - Optional - Filter by domain name. - `threat_level` (str) - Optional - Filter by threat level (e.g., "suspicious", "malicious", "info"). - `os` (str) - Optional - Filter by operating system. - `mitre` (str) - Optional - Filter by MITRE ATT&CK technique ID. - `destinationIP` (str) - Optional - Filter by destination IP address. - `sha256` (str) - Optional - Filter by SHA256 hash. - `parse_response` (bool) - Optional - If True, returns a `LookupSummary` object; otherwise, returns a raw dictionary. #### Parameters (Raw Query String): - `query` (str) - A raw query string to filter results. - `lookup_depth` (int) - Optional - The depth of the lookup. ### Method: `get_intelligence_async` Asynchronous version of `get_intelligence`. #### Parameters: - `destination_ip` (str) - Required - The destination IP address to query. - `parse_response` (bool) - Optional - If True, returns a `LookupSummary` object; otherwise, returns a raw dictionary. ### Response Example (Raw): ```json { "data": [ // ... threat intelligence data ... ] } ``` ### Response Example (LookupSummary): ```python # Assuming summary is a LookupSummary object print(f"Verdict: {summary.verdict()}") print(f"Last seen: {summary.last_modified()}") ``` ``` -------------------------------- ### YARA Rule Lookup with ANY.RUN SDK Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Submit a YARA rule to search the ANY.RUN malware corpus. Supports both automated and manual control flows, including JSON and STIX result formats. Iterators and async operations are also demonstrated. ```python import os from anyrun.connectors import YaraLookupConnector from anyrun.iterators import YaraIterator api_key = os.environ["ANY_RUN_API_KEY"] yara_rule = """ rule SuspiciousPE { meta: description = "Detects suspicious PE files" strings: $mz = { 4D 5A } $suspicious = "CreateRemoteThread" ascii condition: $mz at 0 and $suspicious } """ with YaraLookupConnector(api_key=api_key) as connector: # ── Automated (recommended): run + wait + return ─────────────────────── matches_json = connector.get_yara(yara_rule, stix=False) matches_stix = connector.get_yara(yara_rule, stix=True) print(f"Found {len(matches_json)} matches") # ── Manual control ───────────────────────────────────────────────────── search_id = connector.run_yara_search(yara_rule) print(f"Search ID: {search_id}") # Poll until COMPLETED for status in connector.get_search_status(search_id, simplify=True): print(status) # {'status': 'PREPARING'|'RUNNING'|'COMPLETED'|'FAILED'} # Retrieve results (JSON format) results = connector.get_search_result(search_id, simplify=False) if results: for match in results: print(match) # Retrieve results (STIX format) stix_results = connector.get_stix_search_result(search_id) # ── Iterator ─────────────────────────────────────────────────────────── for match in YaraIterator.json(connector, yara_rule, chunk_size=10): # yields list of 10 JSON match dicts print(match) for stix_obj in YaraIterator.stix(connector, yara_rule, chunk_size=5): # yields list of 5 STIX objects print(stix_obj) # ── Async ────────────────────────────────────────────────────────────── import asyncio async def async_yara(): async with YaraLookupConnector(api_key=api_key) as conn: matches = await conn.get_yara_async(yara_rule, stix=False) print(matches) asyncio.run(async_yara()) ``` ```python import asyncio async def async_yara(): async with YaraLookupConnector(api_key=api_key) as conn: matches = await conn.get_yara_async(yara_rule, stix=False) print(matches) asyncio.run(async_yara()) ``` -------------------------------- ### Custom Endpoint Requests with GenericEnvironment Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Override the target endpoint URL for any connector or make raw authenticated HTTP requests to arbitrary ANY.RUN API paths. Supports both synchronous and asynchronous operations. ```python import os from anyrun.connectors import LookupConnector from anyrun.connectors.generic_environment import GenericEnvironment api_key = os.environ["ANY_RUN_API_KEY"] # ── Raw request to a custom endpoint ────────────────────────────────────── generic = GenericEnvironment("https://intelligence.any.run/api/search") result = generic.generic_request( api_key=api_key, method="POST", json={"query": 'destinationIP:"198.51.100.1"'}, parse_response=True, ) print(result) # ── Override endpoint used by a standard connector ───────────────────────── with GenericEnvironment("https://custom-proxy.internal/api/v1/intelligence/api/search"): with LookupConnector(api_key=api_key) as connector: result = connector.get_intelligence(destination_ip="198.51.100.1") print(result) # ── Async raw request ────────────────────────────────────────────────────── import asyncio async def async_generic(): generic = GenericEnvironment("https://api.any.run/v1/analysis") result = await generic.generic_request_async( api_key=api_key, method="GET", parse_response=True, ) print(result) asyncio.run(async_generic()) ``` ```python import asyncio async def async_generic(): generic = GenericEnvironment("https://api.any.run/v1/analysis") result = await generic.generic_request_async( api_key=api_key, method="GET", parse_response=True, ) print(result) asyncio.run(async_generic()) ``` -------------------------------- ### Iterating Through Related Objects in AnyRun SDK Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Process lists of related objects such as IP addresses, DNS records, and URLs found during an analysis. This allows for programmatic access to threat intelligence data. ```python for ip in summary.related_ips: print(ip.destinationIP, ip.threatLevel, ip.threatName) ``` ```python for dns in summary.related_dns: print(dns.domainName, dns.isMalconf) ``` ```python for url in summary.related_urls: print(url.url, url.date) ``` -------------------------------- ### Query Threat Intelligence with Keyword Filters Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Use keyword arguments to filter threat intelligence data. Combine multiple filters for precise queries. Ensure the ANY_RUN_API_KEY environment variable is set. ```python import os from anyrun.connectors import LookupConnector from anyrun.models.lookup_summary import LookupSummary api_key = os.environ["ANY_RUN_API_KEY"] with LookupConnector(api_key=api_key) as connector: # ── Method 1: keyword arguments (combined with AND) ─────────────────── raw_result: dict = connector.get_intelligence( start_date="2025-01-01", end_date="2025-06-01", domain_name="malicious-domain.example.com", threat_level="malicious", # "suspicious", "malicious", "info" os="Windows 10", mitre="T1071", # MITRE ATT&CK technique ) print(raw_result["data"]) ``` -------------------------------- ### Async Error Handling with RunTimeException in AnyRun SDK Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Implement asynchronous error handling for operations like lookups using async/await and a try-except block. This ensures that asynchronous tasks also handle RunTimeException gracefully. ```python import asyncio from anyrun.utils.exceptions import RunTimeException from anyrun.connectors import SandboxConnector, LookupConnector, FeedsConnector import os api_key = os.environ["ANY_RUN_API_KEY"] async def safe_lookup(): try: async with LookupConnector(api_key=api_key) as connector: return await connector.get_intelligence_async(domain_name="example.com") except RunTimeException as e: print(f"Lookup failed: {e}") return None result = asyncio.run(safe_lookup()) ``` -------------------------------- ### YaraLookupConnector Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Submit a YARA rule to search the ANY.RUN malware corpus and retrieve matching samples. Supports automated and manual search control, as well as iterator and asynchronous operations. ```APIDOC ## YaraLookupConnector — YARA-Based Malware Search Submit a YARA rule to search the ANY.RUN malware corpus and retrieve matching samples. ### Automated (recommended) ```python matches_json = connector.get_yara(yara_rule, stix=False) matches_stix = connector.get_yara(yara_rule, stix=True) ``` ### Manual control ```python search_id = connector.run_yara_search(yara_rule) # Poll until COMPLETED for status in connector.get_search_status(search_id, simplify=True): print(status) # Retrieve results (JSON format) results = connector.get_search_result(search_id, simplify=False) # Retrieve results (STIX format) stix_results = connector.get_stix_search_result(search_id) ``` ### Iterator ```python # JSON format for match in YaraIterator.json(connector, yara_rule, chunk_size=10): print(match) # STIX format for stix_obj in YaraIterator.stix(connector, yara_rule, chunk_size=5): print(stix_obj) ``` ### Async ```python async def async_yara(): async with YaraLookupConnector(api_key=api_key) as conn: matches = await conn.get_yara_async(yara_rule, stix=False) print(matches) asyncio.run(async_yara()) ``` ``` -------------------------------- ### Windows URL Analysis Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Submit a URL for browser-based analysis on a Windows environment. This method allows specifying the browser and network options. ```APIDOC ## run_url_analysis ### Description Submits a URL for browser-based analysis on a Windows environment. Allows configuration of the environment, network, and browser. ### Method `connector.run_url_analysis` ### Parameters - **obj_url** (str) - Required - The URL to analyze. - **env_version** (str) - Optional - The Windows environment version (e.g., "7", "10", "11", "server 2025"). Defaults to "10". - **env_bitness** (int) - Optional - The environment bitness (32 or 64). Defaults to 64. - **opt_network_connect** (bool) - Optional - Enable network connections. Defaults to False. - **opt_timeout** (int) - Optional - Analysis timeout in seconds. Defaults to 120. - **obj_ext_browser** (str) - Optional - The browser to use for analysis ("Microsoft Edge", "Internet Explorer", "Google Chrome", "Mozilla Firefox"). Defaults to "Google Chrome". - **opt_privacy_type** (str) - Optional - Privacy setting ("public", "bylink", "owner", "byteam"). Defaults to "public". - **user_tags** (str) - Optional - Comma-separated user tags for the task. ### Returns - **task_uuid** (str) - The unique identifier for the analysis task. ### Request Example ```python task_uuid = connector.run_url_analysis( obj_url="https://suspicious-site.example.com/phishing", env_version="10", opt_network_connect=True, opt_timeout=120, obj_ext_browser="Google Chrome", opt_privacy_type="bylink", user_tags="phishing" ) ``` ``` -------------------------------- ### Query Threat Intelligence with Raw Query String Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Utilize a raw query string for complex filtering logic in threat intelligence lookups. The `lookup_depth` parameter can be adjusted. ```python raw_result2 = connector.get_intelligence( query='destinationIP:"198.51.100.1" AND threatLevel:"malicious"', lookup_depth=30, ) ``` -------------------------------- ### Handling Validation Errors with RunTimeException in AnyRun SDK Source: https://context7.com/anyrun/anyrun-sdk/llms.txt Catch RunTimeException specifically for validation errors, such as an empty API key. This demonstrates how to access the error description for user feedback or logging. ```python from anyrun.utils.exceptions import RunTimeException from anyrun.connectors import SandboxConnector, LookupConnector, FeedsConnector import os try: with LookupConnector(api_key="") as connector: # empty key → immediate exception pass except RunTimeException as e: print(e.description) # 'The ANY.RUN API key can not be empty.' ```