Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
vt-py
https://virustotal.github.io/vt-py/
Admin
vt-py is the official Python client library for the VirusTotal API v3.
Tokens:
19,480
Snippets:
165
Trust Score:
9.7
Update:
3 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install from local source Source: https://virustotal.github.io/vt-py/_sources/howtoinstall.rst.txt Execute the installation command after obtaining the source code. ```sh $ pip install . ``` -------------------------------- ### Clone and install from source Source: https://virustotal.github.io/vt-py/howtoinstall.html Steps to clone the repository from GitHub and perform a local installation. ```bash $ git clone https://github.com/VirusTotal/vt-py.git $ cd vt-py ``` ```bash $ pip install . ``` -------------------------------- ### Install from tarball Source: https://virustotal.github.io/vt-py/_sources/howtoinstall.rst.txt Download and extract the source code archive to prepare for installation. ```sh $ tar -zxvf vt-py-X.Y.Z.tar.gz $ cd vt-py-X.Y.Z ``` -------------------------------- ### Install vt-py via pip Source: https://virustotal.github.io/vt-py/_sources/howtoinstall.rst.txt The recommended method for installing the library using the Python package manager. ```sh $ pip install vt-py ``` -------------------------------- ### get(path, *path_args, params=None) Source: https://virustotal.github.io/vt-py/api/client.html Sends a low-level GET request to a given API endpoint and returns a raw ClientResponse. ```APIDOC ## get(path, *path_args, params=None) ### Description Sends a GET request to a given API endpoint. This is a low-level function that returns a raw HTTP response without error checking or parsing. ### Parameters - **path** (str) - Required - Path to API endpoint, can contain format placeholders {}. - **path_args** (Any) - Optional - A variable number of arguments that are put into any placeholders used in path. - **params** (Dict) - Optional - Parameters sent in the request. ``` -------------------------------- ### get_object(path, *path_args, params=None) Source: https://virustotal.github.io/vt-py/api/client.html Sends a GET request and returns an Object instance. ```APIDOC ## get_object(path, *path_args, params=None) ### Description Sends a GET request to a given API endpoint and returns an Object. This is intended for endpoints that return an individual object (e.g., /files/{file_id}). ### Parameters - **path** (str) - Required - Path to API endpoint, can contain format placeholders {}. - **path_args** (Any) - Optional - A variable number of arguments that are put into any placeholders used in path. - **params** (Dict) - Optional - Parameters sent in the request. ``` -------------------------------- ### Example JSON response format Source: https://virustotal.github.io/vt-py/api/client.html The expected structure for most VirusTotal API responses. ```json {"data": <response data>} ``` -------------------------------- ### get_json(path, *path_args, params=None) Source: https://virustotal.github.io/vt-py/api/client.html Sends a GET request and returns the parsed JSON response as a dictionary. ```APIDOC ## get_json(path, *path_args, params=None) ### Description Sends a GET request to a given API endpoint, parses the JSON, checks for errors, and returns the response as a dictionary. ### Parameters - **path** (str) - Required - Path to API endpoint, can contain format placeholders {}. - **path_args** (Any) - Optional - A variable number of arguments that are put into any placeholders used in path. - **params** (Dict) - Optional - Parameters sent in the request. ``` -------------------------------- ### get_data(path, *path_args, params=None) Source: https://virustotal.github.io/vt-py/api/client.html Sends a GET request and returns the data field from the JSON response. ```APIDOC ## get_data(path, *path_args, params=None) ### Description Sends a GET request to a given API endpoint and returns the response's data field. It expects a JSON format of {"data": <response data>}. ### Parameters - **path** (str) - Required - Path to API endpoint, can contain format placeholders {}. - **path_args** (Any) - Optional - A variable number of arguments that are put into any placeholders used in path. - **params** (Dict) - Optional - Parameters sent in the request. ``` -------------------------------- ### Retrieve attributes safely Source: https://virustotal.github.io/vt-py/quickstart.html Use the get method to retrieve attributes, which returns None if the attribute is missing. ```python >>> file.get("size") 68 ``` ```python >>> file.get("type_tag") 'text' ``` -------------------------------- ### Iterate over a VirusTotal feed Source: https://virustotal.github.io/vt-py/_modules/vt/feed.html Use the client.feed method to iterate over objects in a feed. This example demonstrates a synchronous loop to print the ID of each file object as it is processed. ```python with vt.Client(<apikey>) as client: for file_obj in client.feed(vt.FeedType.FILES): print(file_obj.id) ``` -------------------------------- ### Retrieve File Information Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Fetch file metadata using a hash and access attributes directly or via the get method. ```python file = client.get_object("/files/44d88612fea8a8f36de82e1278abb02f") file.size file.sha256 file.type_tag file.last_analysis_stats file.get("size") file.get("type_tag") ``` -------------------------------- ### Send GET Requests Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Low-level methods for sending GET requests to API endpoints. These methods do not perform error checking or response parsing. ```python def get( self, path: str, *path_args: typing.Any, params: typing.Optional[typing.Dict] = None, ) -> ClientResponse: """Sends a GET request to a given API endpoint. This is a low-level function that returns a raw HTTP response, no error checking nor response parsing is performed. See :func:`get_json`, :func:`get_data` and :func:`get_object` for higher-level functions. :param path: Path to API endpoint, can contain format placeholders {}. :param path_args: A variable number of arguments that are put into any placeholders used in path. :param params: Parameters sent in the request. :type path: str :type params: dict :returns: An instance of :class:`ClientResponse`. """ return make_sync(self.get_async(path, *path_args, params=params)) ``` ```python async def get_async( self, path: str, *path_args: typing.Any, params: typing.Optional[typing.Dict] = None, ) -> ClientResponse: """Like :func:`get` but returns a coroutine.""" return ClientResponse( await self._get_session().get( self._full_url(path, *path_args), params=params, proxy=self._proxy ) ) ``` -------------------------------- ### Initialize vt-py client Source: https://virustotal.github.io/vt-py/quickstart.html Import the module and instantiate the client with your API key. ```python >>> import vt ``` ```python >>> client = vt.Client("<apikey>") ``` -------------------------------- ### Initialize VirusTotal Client Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Import the module and instantiate the client with your API key. ```python import vt client = vt.Client("<apikey>") ``` -------------------------------- ### Client Class Initialization Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Initializes the VirusTotal client with authentication and connection configuration. ```python def __init__( self, apikey: str, agent: str = "unknown", host: typing.Optional[str] = None, trust_env: bool = False, timeout: int = 300, proxy: typing.Optional[str] = None, headers: typing.Optional[typing.Dict] = None, verify_ssl: bool = True, connector: aiohttp.BaseConnector = None, ): """Initialize the client with the provided API key.""" if not isinstance(apikey, str): raise ValueError("API key must be a string") if not apikey: raise ValueError("API key can not be an empty string") self._host = host or _API_HOST self._apikey = apikey self._agent = agent self._session = None self._trust_env = trust_env self._timeout = timeout self._proxy = proxy self._user_headers = headers self._verify_ssl = verify_ssl if connector is not None: self._connector = connector else: # the TCPConnector class expects to be instantiated inside a event loop. # If there is none, create one. try: event_loop = asyncio.get_event_loop() except RuntimeError: event_loop = asyncio.new_event_loop() asyncio.set_event_loop(event_loop) self._connector = aiohttp.TCPConnector( ssl=self._verify_ssl, loop=event_loop ) ``` -------------------------------- ### Client Initialization Source: https://virustotal.github.io/vt-py/api/client.html Initializes a new VirusTotal client instance with the provided API key and configuration options. ```APIDOC ## Client(apikey, agent='unknown', host=None, trust_env=False, timeout=300, proxy=None, headers=None, verify_ssl=True, connector=None) ### Description Initializes the client for interacting with VirusTotal. ### Parameters - **apikey** (str) - Required - Your VirusTotal API key. - **agent** (str) - Optional - A string that identifies your application. - **host** (str) - Optional - The API host URL (defaults to https://www.virustotal.com). - **timeout** (int) - Optional - Request timeout in seconds (defaults to 300). ``` -------------------------------- ### Creating a LiveHunt Ruleset Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Initialize a hunting_ruleset object and post it to the collection. ```python >>> rs = vt.Object("hunting_ruleset") >>> rs.name = "My test ruleset" >>> rs.rules = "rule test { condition:false }" >>> rs = client.post_object("/intelligence/hunting_rulesets", obj=rs) ``` -------------------------------- ### Use a context manager for client lifecycle Source: https://virustotal.github.io/vt-py/quickstart.html Automatically handle client closure by using the context manager pattern. ```python >>> with vt.Client('<apikey>') as client: ... file = client.get_object("/files/44d88612fea8a8f36de82e1278abb02f") ... print(file.type_tag) text ``` -------------------------------- ### Initialize a hunting ruleset object Source: https://virustotal.github.io/vt-py/quickstart.html Create a new hunting_ruleset object and define its name and YARA rules. ```python >>> rs = vt.Object("hunting_ruleset") >>> rs.name = "My test ruleset" >>> rs.rules = "rule test { condition:false }" ``` -------------------------------- ### get_data Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Sends a GET request to a given API endpoint and returns the parsed data field from the JSON response. ```APIDOC ## get_data(path, *path_args, params=None) ### Description Sends a GET request to a given API endpoint and returns the response's data. It expects a JSON response in the format {"data": <response data>}. ### Parameters - **path** (str) - Required - Path to API endpoint, can contain format placeholders {}. - **path_args** (Any) - Optional - A variable number of arguments that are put into any placeholders used in path. - **params** (dict) - Optional - Parameters sent in the request. ``` -------------------------------- ### Retrieve API Response Data Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Sends a GET request and parses the JSON response to return only the data field. ```python def get_data( self, path: str, *path_args: typing.Any, params: typing.Optional[typing.Dict] = None, ) -> typing.Any: """Sends a GET request to a given API endpoint and returns response's data. Most VirusTotal API responses are JSON-encoded with the following format:: {"data": <response data>} This function parses the server's response and return only the data, if the response is not in the expected format an exception is raised. For endpoints where the data is a VirusTotal object you can use :func:`get_object` instead. ``` -------------------------------- ### Client Internal Helper Methods Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Internal methods for URL construction and session management. ```python def _full_url(self, path: str, *args: typing.Any) -> str: try: path = path.format(*args) except IndexError as exc: raise ValueError( "Not enough arguments to fill all placeholders in path" ) from exc # pylint: disable=line-too-long if path.startswith("http"): return path return self._host + _ENDPOINT_PREFIX + path def _get_session(self) -> aiohttp.ClientSession: if not self._session: headers = { "X-Apikey": self._apikey, "Accept-Encoding": "gzip", "User-Agent": _USER_AGENT_FMT.format_map( {"agent": self._agent, "version": __version__} ), } ``` -------------------------------- ### Managing Client Lifecycle Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Close the client manually or use a context manager to ensure proper resource cleanup. ```python >>> client.close() >>> with vt.Client('<apikey>') as client: ... file = client.get_object("/files/44d88612fea8a8f36de82e1278abb02f") ... print(file.type_tag) text ``` -------------------------------- ### JSON Response Retrieval Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Sends a GET request and parses the JSON response into a dictionary, available in both synchronous and asynchronous forms. ```python def get_json( self, path: str, *path_args: typing.Any, params: typing.Optional[typing.Dict] = None, ) -> typing.Dict: """Sends a GET request to a given API endpoint and parses the response. Most VirusTotal API responses are JSON-encoded. This function parses the JSON, check for errors, and return the server response as a dictionary. :param path: Path to API endpoint, can contain format placeholders {}. :param path_args: A variable number of arguments that are put into any placeholders used in path. :param params: Parameters sent in the request. :type path: str :type params: dict :returns: A dictionary with the backend's response. """ return make_sync(self.get_json_async(path, *path_args, params=params)) ``` ```python async def get_json_async( self, path: str, *path_args: typing.Any, params: typing.Optional[typing.Dict] = None, ) -> typing.Dict: """Like :func:`get_json` but returns a coroutine.""" response = await self.get_async(path, *path_args, params=params) return await self._response_to_json(response) ``` -------------------------------- ### Download a File Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Download a file by hash to a local file-like object. Requires premium access. ```python with open("/path/to/target_file", "wb") as f: client.download_file("44d88612fea8a8f36de82e1278abb02f", f) ``` -------------------------------- ### post_object(path, *path_args, obj) Source: https://virustotal.github.io/vt-py/api/client.html Sends a POST request for creating a new object. ```APIDOC ## post_object(path, *path_args, obj) ### Description Creates a new object. The endpoint must identify a collection, such as /intelligence/hunting_rulesets. ### Parameters - **path** (str) - Required - Path to API endpoint. - **path_args** (Any) - Optional - Variable number of arguments for path placeholders. - **obj** (Object) - Required - Instance of Object with the expected type. ``` -------------------------------- ### Clone vt-py repository Source: https://virustotal.github.io/vt-py/_sources/howtoinstall.rst.txt Retrieve the source code directly from the GitHub repository. ```sh $ git clone https://github.com/VirusTotal/vt-py.git $ cd vt-py ``` -------------------------------- ### Scan a File Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Upload a file for scanning and monitor the analysis status. ```python with open("/path/to/file", "rb") as f: analysis = client.scan_file(f) while True: analysis = client.get_object("/analyses/{}", analysis.id) print(analysis.status) if analysis.status == "completed": break time.sleep(30) with open("/path/to/file", "rb") as f: analysis = client.scan_file(f, wait_for_completion=True) ``` -------------------------------- ### Scan a file Source: https://virustotal.github.io/vt-py/quickstart.html Uploads a file for scanning using the client. ```python >>> with open("/path/to/file", "rb") as f: >>> analysis = client.scan_file(f) ``` -------------------------------- ### Initialize VirusTotal API Object Source: https://virustotal.github.io/vt-py/_modules/vt/object.html Initializes an Object instance with a type, optional ID, and optional attributes dictionary. ```python def __init__( self, obj_type: str, obj_id: typing.Optional[str] = None, obj_attributes: typing.Optional[typing.Dict] = None, ): """Initializes a VirusTotal API object.""" if not isinstance(obj_attributes, (dict, type(None))): raise ValueError("Object attributes must be a dictionary") self._type = obj_type self._id = obj_id # Initialize object attributes with the ones coming in the obj_attributes, # this way if obj_attributes contains {'foo': 'somevalue'} you can access # the attribute as obj.foo and it will return 'somevalue'. if obj_attributes: for attr, value in obj_attributes.items(): setattr(self, attr, value) self._modified_attrs = [] self._modified_data = {} self._error = None ``` -------------------------------- ### post(path, *path_args, data=None, json_data=None) Source: https://virustotal.github.io/vt-py/api/client.html Sends a low-level POST request to a given API endpoint. ```APIDOC ## post(path, *path_args, data=None, json_data=None) ### Description Sends a POST request to a given API endpoint. This is a low-level function that returns a raw HTTP response. ### Parameters - **path** (str) - Required - Path to API endpoint. - **path_args** (Any) - Optional - Variable number of arguments for path placeholders. - **data** (str/bytes) - Optional - Data sent in the request body. - **json_data** (dict) - Optional - JSON data sent in the request body. ``` -------------------------------- ### vt.Object.from_dict(obj_dict) Source: https://virustotal.github.io/vt-py/api/object.html Creates an object instance from its dictionary representation. ```APIDOC ## vt.Object.from_dict(obj_dict) ### Description Creates an object from its dictionary representation. Requires 'type' and 'id' keys to be present in the dictionary. ### Parameters - **obj_dict** (Dict) - Required - The dictionary representation of the object. ``` -------------------------------- ### Download File Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Downloads a file by its hash and writes it to a provided file object. The file object must be opened in 'wb' mode. ```python def download_file(self, file_hash: str, file: typing.BinaryIO) -> None: """Downloads a file given its _ (SHA-256, SHA-1 or MD5). The file identified by the hash will be written to the provided file object. The file object must be opened in write binary mode ('wb'). :param file_hash: File hash. :param file: A file object where the downloaded file will be written to. :type file_hash: str :type file: file-like object """ return make_sync(self.download_file_async(file_hash, file)) ``` ```python async def download_file_async( self, file_hash: str, file: typing.BinaryIO ) -> None: """Like :func:`download_file` but returns a coroutine.""" await self.__download_async(f"/files/{file_hash}/download", file) ``` -------------------------------- ### Client.download_file Source: https://virustotal.github.io/vt-py/api/client.html Downloads a file from VirusTotal by its hash. ```APIDOC ## Client.download_file(file_hash, file) ### Description Downloads a file given its hash (SHA-256, SHA-1 or MD5). The file is written to the provided file object. ### Parameters - **file_hash** (str) - Required - The file hash. - **file** (BinaryIO) - Required - A file object opened in write binary mode ('wb'). ``` -------------------------------- ### download_zip_files Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Creates a zip bundle containing one or multiple files identified by their hashes and writes the result to a provided file object. ```APIDOC ## download_zip_files(hashes, zipfile, password=None, sleep_time=20) ### Description Creates a bundle zip containing one or multiple files. The file identified by the hash will be written to the provided file object, which must be opened in write binary mode ('wb'). ### Parameters - **hashes** (List[str]) - Required - List of file hashes (SHA-256, SHA-1 or MD5). - **zipfile** (BinaryIO) - Required - A file object where the downloaded zip file will be written to. - **password** (str) - Optional - A password to protect the zip file. - **sleep_time** (int) - Optional - Seconds to sleep between each request. ``` -------------------------------- ### download_file(file_hash, file) Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Downloads a file given its hash (SHA-256, SHA-1 or MD5). ```APIDOC ## download_file(file_hash, file) ### Description Downloads a file given its hash (SHA-256, SHA-1 or MD5). The file identified by the hash will be written to the provided file object. The file object must be opened in write binary mode ('wb'). ### Parameters - **file_hash** (str) - Required - File hash. - **file** (BinaryIO) - Required - A file object where the downloaded file will be written to. ``` -------------------------------- ### Scan a URL Source: https://virustotal.github.io/vt-py/quickstart.html Initiate a URL scan using the client's scan_url method. ```python >>> analysis = client.scan_url('https://somedomain.com/foo/bar') ``` -------------------------------- ### Access metadata asynchronously Source: https://virustotal.github.io/vt-py/_modules/vt/iterator.html Retrieves metadata information, triggering a batch load if not already present. ```python @property async def meta_async(self) -> typing.Dict: """Meta information. The cursor is not included, as it's exposed as a property. """ if self._meta is None: # Load the first batch of items in order to retrieve the meta info. self._items, self._meta = await self._get_batch_async() self._server_cursor = self._meta.pop("cursor", None) self._batch_cursor = 0 return self._meta ``` -------------------------------- ### vt.Client.iterator Source: https://virustotal.github.io/vt-py/_modules/vt/iterator.html Creates an iterator for a specific API collection path. This is the preferred method for initializing an iterator. ```APIDOC ## vt.Client.iterator(path, params=None, cursor=None, limit=None, batch_size=0) ### Description Creates an iterator instance to loop through objects in a VirusTotal API collection. ### Parameters - **path** (str) - Required - The API endpoint path representing a collection (e.g., '/comments'). - **params** (dict) - Optional - Additional query parameters for the API request. - **cursor** (str) - Optional - A cursor string to resume iteration from a previous point. - **limit** (int) - Optional - The maximum number of items to retrieve. - **batch_size** (int) - Optional - The number of items to retrieve per API request. ### Usage Example ```python client = vt.Client(<apikey>) it = client.iterator('/comments', batch_size=20, limit=200) for comment in it: print(comment.text) print(it.cursor) ``` ``` -------------------------------- ### Manage Retrohunt Jobs Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Create and post a Retrohunt job with YARA rules. Requires premium access. ```python job = vt.Object("retrohunt_job") job.rules = "rule test { condition:false }" job = client.post_object("/intelligence/retrohunt_jobs", obj=job) ``` -------------------------------- ### Post a hunting ruleset to the collection Source: https://virustotal.github.io/vt-py/quickstart.html Upload the ruleset object to the VirusTotal intelligence collection. ```python >>> rs = client.post_object("/intelligence/hunting_rulesets", obj=rs) ``` -------------------------------- ### Scan a URL Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Submit a URL for analysis. ```python analysis = client.scan_url('https://somedomain.com/foo/bar') ``` -------------------------------- ### post / post_async Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Sends a raw POST request to a specified API endpoint. ```APIDOC ## post(path, *path_args, data=None, json_data=None) ### Description Sends a POST request to a given API endpoint. This is a low-level function that returns a raw HTTP response. ### Parameters - **path** (str) - Required - Path to API endpoint, can contain format placeholders {}. - **path_args** (Any) - Optional - A variable number of arguments that are put into any placeholders used in path. - **data** (str or bytes) - Optional - Data sent in the request body. - **json_data** (dict) - Optional - Data to send in the request body as JSON. ### Returns - **ClientResponse** - An instance of ClientResponse. ``` -------------------------------- ### vt.Object(obj_type, obj_id=None, obj_attributes=None) Source: https://virustotal.github.io/vt-py/api/object.html Initializes a new instance of a VirusTotal API object. This is typically used when creating new objects to be sent to the backend via vt.Client.post_object(). ```APIDOC ## vt.Object(obj_type, obj_id=None, obj_attributes=None) ### Description Encapsulates any type of object in the VirusTotal API. ### Parameters - **obj_type** (str) - Required - The type of the object. - **obj_id** (str) - Optional - The unique identifier of the object. - **obj_attributes** (Dict) - Optional - A dictionary of object attributes. ``` -------------------------------- ### scan_file(file, wait_for_completion=False) Source: https://virustotal.github.io/vt-py/api/client.html Scans a file using the VirusTotal API. ```APIDOC ## scan_file(file, wait_for_completion=False) ### Description Scans a file. ### Parameters - **file** (BinaryIO) - Required - File-like object to be scanned. - **wait_for_completion** (bool) - Optional - If True, waits until analysis is completed. ``` -------------------------------- ### Scan file with wait_for_completion Source: https://virustotal.github.io/vt-py/quickstart.html Scans a file and blocks execution until the analysis is finished. ```python >>> with open("/path/to/file", "rb") as f: >>> analysis = client.scan_file(f, wait_for_completion=True) ``` -------------------------------- ### Iterate over a file feed Source: https://virustotal.github.io/vt-py/api/feed.html Uses the client's feed method to retrieve file objects in real-time. Requires a valid API key and premium access. ```python >>> with vt.Client(<apikey>) as client: >>> for file_obj in client.feed(vt.FeedType.FILES): >>> print(file_obj.id) ``` -------------------------------- ### Access URL attributes Source: https://virustotal.github.io/vt-py/quickstart.html Demonstrates accessing specific attributes from a returned URL object. ```python >>> url.times_submitted 213730 ``` ```python >>> url.last_analysis_stats {'harmless': 61, 'malicious': 0, 'suspicious': 1, 'timeout': 0, 'undetected': 8} ``` -------------------------------- ### Create Object via POST Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Creates a new object using a POST request. Synchronous and asynchronous versions are available. ```python def post_object( self, path: str, *path_args: typing.Any, obj: Object ) -> Object: """Sends a POST request for creating an object. This function create a new object. The endpoint must be one that identifies a collection, like /intelligence/hunting_rulesets. :param path: Path to API endpoint. :param path_args: A variable number of arguments that are put into any placeholders used in path. :param obj: Instance :class:`Object` with the type expected by the API endpoint. :type path: str :type obj: :class:`Object` :returns: An instance of :class:`Object` representing the new object. """ return make_sync(self.post_object_async(path, *path_args, obj=obj)) ``` ```python async def post_object_async( self, path: str, *path_args: typing.Any, obj: Object ) -> Object: """Like :func:`post_object` but returns a coroutine.""" data = {"data": obj.to_dict()} response = await self.post_async(path, *path_args, json_data=data) return await self._response_to_object(response) ``` -------------------------------- ### Access metadata synchronously Source: https://virustotal.github.io/vt-py/_modules/vt/iterator.html Provides a synchronous wrapper for accessing metadata. ```python @property def meta(self) -> typing.Dict: return make_sync(self.meta_async) ``` -------------------------------- ### scan_url(url, wait_for_completion=False) Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Scans a URL using the VirusTotal API. This method is synchronous and returns an analysis object. ```APIDOC ## scan_url(url, wait_for_completion=False) ### Description Scans a URL. ### Parameters - **url** (str) - Required - The URL to be scanned. - **wait_for_completion** (bool) - Optional - If True the function doesn't return until the analysis has been completed. ### Returns - **Object** - An instance of Object of analysis type. ``` -------------------------------- ### scan_url_private_async(url: str, wait_for_completion: bool = False) -> Object Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Submits a URL for a private scan asynchronously. Returns an analysis object, optionally waiting for the scan to complete. ```APIDOC ## scan_url_private_async ### Description Submits a URL for a private scan asynchronously. Returns an analysis object, optionally waiting for the scan to complete. ### Parameters - **url** (str) - Required - The URL to scan. - **wait_for_completion** (bool) - Optional - If True, waits for the analysis to reach 'completed' status before returning. ### Returns - **Object** - The analysis object containing scan results. ``` -------------------------------- ### Check ruleset enabled status Source: https://virustotal.github.io/vt-py/quickstart.html Verify the default enabled status of a newly created ruleset. ```python >>> rs.enabled False ``` -------------------------------- ### StreamReader Wrapper Implementation Source: https://virustotal.github.io/vt-py/_modules/vt/client.html A wrapper around aiohttp.StreamReader that provides both synchronous and asynchronous methods for reading data. ```python def __init__(self, aiohttp_stream_reader: aiohttp.StreamReader): self._aiohttp_stream_reader = aiohttp_stream_reader def __getattr__(self, attr: str) -> typing.Any: return getattr(self._aiohttp_stream_reader, attr) async def read_async(self, n: int = -1) -> bytes: return await self._aiohttp_stream_reader.read(n) def read(self, n: int = -1) -> bytes: return make_sync(self.read_async(n)) async def readany_async(self) -> bytes: return await self._aiohttp_stream_reader.readany() def readany(self) -> str: return make_sync(self.readany_async()) async def readexactly_async(self, n: int) -> bytes: return await self._aiohttp_stream_reader.readexactly(n) def readexactly(self, n: int) -> bytes: return make_sync(self.readexactly_async(n)) async def readline_async(self) -> bytes: return await self._aiohttp_stream_reader.readline() def readline(self) -> bytes: return make_sync(self.readline_async()) async def readchunk_async(self) -> typing.Tuple[bytes, bool]: return await self._aiohttp_stream_reader.readchunk() def readchunk(self) -> typing.Tuple[bytes, bool]: return make_sync(self.readchunk_async()) ``` -------------------------------- ### Download Zip Files Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Downloads a bundle of files as a zip archive. The target file object must be opened in write binary mode ('wb'). ```python def download_zip_files( self, hashes: typing.List[str], zipfile: typing.BinaryIO, password: typing.Optional[str] = None, sleep_time: int = 20, ) -> None: """Creates a bundle zip bundle containing one or multiple files. The file identified by the hash will be written to the provided file object. The file object must be opened in write binary mode ('wb'). :param hashes: list of file hashes (SHA-256, SHA-1 or MD5). :param zipfile: A file object where the downloaded zip file will be written to. :param password: optional, a password to protect the zip file. :param sleep_time: optional, seconds to sleep between each request. """ return make_sync( self.download_zip_files_async(hashes, zipfile, password, sleep_time) ) ``` ```python async def download_zip_files_async( self, hashes: typing.List[str], zipfile: typing.BinaryIO, password: typing.Optional[str] = None, sleep_time: int = 20, ) -> None: data = {"hashes": hashes} if password: data["password"] = password response = await self.post_async( "/intelligence/zip_files", data=json.dumps({"data": data}) ) error = await self.get_error_async(response) if error: raise error res_data = (await response.json_async())["data"] # wait until the zip file is ready while res_data["attributes"]["status"] in ("creating", "starting"): await asyncio.sleep(sleep_time) response = await self.get_async( f'/intelligence/zip_files/{res_data["id"]}' ) error = await self.get_error_async(response) if error: raise error res_data = (await response.json_async())["data"] # check for errors creating the zip file if res_data["attributes"]["status"] != "finished": raise APIError( "ServerError", f'Error when creating zip file: {res_data["attributes"]["status"]}', ) # download the zip file await self.__download_async( f'/intelligence/zip_files/{res_data["id"]}/download', zipfile ) ``` -------------------------------- ### Create Object from dictionary Source: https://virustotal.github.io/vt-py/_modules/vt/object.html Instantiates an Object from a dictionary representation containing type, id, and attributes. Requires type and id fields to be present. ```python @classmethod def from_dict(cls, obj_dict: typing.Dict): """Creates an object from its dictionary representation. The dictionary representation of a VirusTotal API object has the following structure:: { "type": <object type>, "id": <object id>, "links": { "self": "https://www.virustotal.com/api/v3/<collection name>/<obj id>" }, "attributes": { ... } } At least `type` and `id` are required to be present in the dictionary, if not, an exception is raised. """ if not isinstance(obj_dict, dict): raise ValueError(f"Expecting dictionary, got: {type(obj_dict).__name__}") for field in ("type", "id"): if field not in obj_dict: raise ValueError(f"Object {field} not found") obj = cls( obj_dict.get("type"), obj_dict.get("id"), obj_dict.get("attributes") ) if "context_attributes" in obj_dict: obj._context_attributes = obj_dict["context_attributes"] if "relationships" in obj_dict: obj._relationships = obj_dict["relationships"] if "error" in obj_dict: obj._error = obj_dict["error"] return obj ``` -------------------------------- ### Retrieve URL Information Source: https://virustotal.github.io/vt-py/_sources/quickstart.rst.txt Generate a URL identifier and fetch its metadata from the API. ```python url_id = vt.url_id("http://www.virustotal.com") url = client.get_object("/urls/{}", url_id) url = client.get_object("/urls/{}".format(url_id)) url.times_submitted url.last_analysis_stats ``` -------------------------------- ### Create a Retrohunt job Source: https://virustotal.github.io/vt-py/quickstart.html Define a new retrohunt_job object with YARA rules. ```python >>> job = vt.Object("retrohunt_job") >>> job.rules = "rule test { condition:false }" ``` -------------------------------- ### wait_for_analysis_completion(analysis: Object, private_path: bool = False) -> Object Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Waits for an analysis to complete by polling the analysis status. ```APIDOC ## wait_for_analysis_completion ### Description Waits for an analysis to complete by polling the analysis status. ### Parameters - **analysis** (Object) - Required - The analysis object to track. - **private_path** (bool) - Optional - Whether to use the private API path for polling. ### Returns - **Object** - The completed analysis object. ``` -------------------------------- ### scan_file_private_async(file: typing.Union[typing.BinaryIO, str], wait_for_completion: bool = False) -> Object Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Asynchronously scans a file privately. Accepts a file path string or a file object. ```APIDOC ## scan_file_private_async ### Description Asynchronously scans a file privately. Accepts a file path string or a file object. ### Parameters - **file** (typing.Union[typing.BinaryIO, str]) - Required - The file to scan (path string or file object). - **wait_for_completion** (bool) - Optional - If True, waits for the analysis to reach 'completed' status before returning. ### Returns - **Object** - The analysis object containing scan results. ``` -------------------------------- ### Scan a file Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Scans a file and optionally waits for the analysis to complete. ```python def scan_file( self, file: typing.BinaryIO, wait_for_completion: bool = False ) -> Object: """Scans a file. :param file: File to be scanned. :param wait_for_completion: If True the function doesn't return until the analysis has been completed. :type file: File-like object. :type wait_for_completion: bool :returns: An instance of :class:`Object` of analysis type. """ return make_sync( self.scan_file_async(file, wait_for_completion=wait_for_completion) ) ``` -------------------------------- ### Scan a URL Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Scans a URL and optionally waits for the analysis to complete. ```python def scan_url(self, url: str, wait_for_completion: bool = False) -> Object: """Scans a URL. :param url: The URL to be scanned. :param wait_for_completion: If True the function doesn't return until the analysis has been completed. :type url: str :type wait_for_completion: bool :returns: An instance of :class:`Object` of analysis type. """ return make_sync( self.scan_url_async(url, wait_for_completion=wait_for_completion) ) ``` -------------------------------- ### Scan File Privately Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Synchronous wrapper for private file scanning. ```python def scan_file_private( self, file: typing.Union[typing.BinaryIO, str], wait_for_completion: bool = False, ) -> Object: """Scan file privately. Args: file: File to scan (path string or file object) wait_for_completion: Wait for completion Returns: Object: Analysis object with scan results """ return make_sync(self.scan_file_private_async(file, wait_for_completion)) ``` -------------------------------- ### Implement asynchronous iteration in vt.iterator Source: https://virustotal.github.io/vt-py/_modules/vt/iterator.html Handles batch retrieval and cursor progression for asynchronous iteration. ```python async def __anext__(self) -> Object: if self._limit and self._count == self._limit: raise StopAsyncIteration() if not self._items and (self.cursor or self._count == 0): self._items, self._meta = await self._get_batch_async() self._server_cursor = self._meta.pop("cursor", None) self._batch_cursor = 0 if not self._items and not self._server_cursor: raise StopAsyncIteration() item = self._items.pop(0) self._count += 1 self._batch_cursor += 1 return Object.from_dict(item) ``` -------------------------------- ### vt.Object.get(attr_name, default=None) Source: https://virustotal.github.io/vt-py/api/object.html Retrieves an attribute value by its name. ```APIDOC ## vt.Object.get(attr_name, default=None) ### Description Returns an attribute by name. If the attribute is not present, returns the default value. ### Parameters - **attr_name** (str) - Required - Name of the attribute. - **default** (Any) - Optional - Value returned if the attribute is missing. ``` -------------------------------- ### POST Request to API Endpoint Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Sends a low-level POST request to an API endpoint. Returns a raw ClientResponse. ```python def post( self, path: str, *path_args: typing.Any, data: typing.Optional[typing.Union[str, bytes]] = None, json_data: typing.Optional[typing.Dict] = None, ) -> ClientResponse: """Sends a POST request to a given API endpoint. This is a low-level function that returns a raw HTTP response, no error checking nor response parsing is performed. See :func:`post_object` for a higher-level function. :param path: Path to API endpoint, can contain format placeholders {}. :param path_args: A variable number of arguments that are put into any placeholders used in path. :param data: Data sent in the request body. :param json_data: dict containing data to send in the request body as JSON. :type path: str :type data: A string or bytes :type json_data: dict :returns: An instance of :class:`ClientResponse`. """ return make_sync( self.post_async(path, *path_args, data=data, json_data=json_data) ) ``` ```python async def post_async( self, path: str, *path_args: typing.Any, data: typing.Optional[typing.Union[str, bytes]] = None, json_data: typing.Optional[typing.Dict] = None, ) -> ClientResponse: """Like :func:`post` but returns a coroutine.""" return ClientResponse( await self._get_session().post( self._full_url(path, *path_args), data=data, json=json_data, proxy=self._proxy, ) ) ``` -------------------------------- ### Retrieve file object Source: https://virustotal.github.io/vt-py/quickstart.html Fetch a file object from VirusTotal using its hash identifier. ```python >>> file = client.get_object("/files/44d88612fea8a8f36de82e1278abb02f") ``` -------------------------------- ### close() Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Closes the client and releases resources like TCP connections. ```APIDOC ## close() ### Description Closes the client. When the client is not needed anymore it must be closed for releasing resources like TCP connections. Not closing the client after it's used might show error tracebacks indicating it was not properly closed. ``` -------------------------------- ### scan_url Source: https://virustotal.github.io/vt-py/api/client.html Scans a URL and returns an analysis object. ```APIDOC ## scan_url(url, wait_for_completion=False) ### Description Scans a URL and returns an analysis object. ### Parameters - **url** (str) - Required - The URL to be scanned. - **wait_for_completion** (bool) - Optional - If True, waits for the analysis to complete before returning. ``` -------------------------------- ### Close the client connection Source: https://virustotal.github.io/vt-py/quickstart.html Manually terminate the client connection to prevent potential tracebacks. ```python >>> client.close() ``` -------------------------------- ### patch(path, *path_args, data=None, json_data=None) Source: https://virustotal.github.io/vt-py/api/client.html Sends a low-level PATCH request to a given API endpoint. ```APIDOC ## patch(path, *path_args, data=None, json_data=None) ### Description Sends a PATCH request to a given API endpoint. This is a low-level function that returns a raw HTTP response. ### Parameters - **path** (str) - Required - Path to API endpoint. - **path_args** (Any) - Optional - Variable number of arguments for path placeholders. - **data** (str/bytes) - Optional - Data sent in the request body. - **json_data** (dict) - Optional - JSON data sent in the request body. ``` -------------------------------- ### vt.Object.set_data(key, value) Source: https://virustotal.github.io/vt-py/api/object.html Sets a field of the object's data. ```APIDOC ## vt.Object.set_data(key, value) ### Description Sets a field of the object's data. ### Parameters - **key** (str) - Required - The key of the field. - **value** (Any) - Required - The value to set. ``` -------------------------------- ### Post a Retrohunt job Source: https://virustotal.github.io/vt-py/quickstart.html Submit the retrohunt_job object to the API collection. ```python >>> job = client.post_object("/intelligence/retrohunt_jobs", obj=job) ``` -------------------------------- ### scan_url_private(url, wait_for_completion=False) Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Scans a URL privately using the VirusTotal API. This method is synchronous and returns an analysis object. ```APIDOC ## scan_url_private(url, wait_for_completion=False) ### Description Scans a URL privately. ### Parameters - **url** (str) - Required - The URL to be scanned. - **wait_for_completion** (bool) - Optional - If True the function doesn't return until the analysis has been completed. ### Returns - **Object** - An instance of Object of analysis type. ``` -------------------------------- ### patch / patch_async Source: https://virustotal.github.io/vt-py/_modules/vt/client.html Sends a raw PATCH request to a specified API endpoint. ```APIDOC ## patch(path, *path_args, data=None, json_data=None) ### Description Sends a PATCH request to a given API endpoint. This is a low-level function that returns a raw HTTP response. ### Parameters - **path** (str) - Required - Path to API endpoint, can contain format placeholders {}. - **path_args** (Any) - Optional - A variable number of arguments that are put into any placeholders used in path. - **data** (str or bytes) - Optional - Data sent in the request body. - **json_data** (dict) - Optional - Data to send in the request body as JSON. ### Returns - **ClientResponse** - An instance of ClientResponse. ``` -------------------------------- ### Asynchronous Feed Iteration Source: https://virustotal.github.io/vt-py/_modules/vt/feed.html Handles batch retrieval and item parsing from the feed stream. ```python async def __anext__(self): while True: if not self._batch: await self._get_next_batch_async() self._skip(self._batch_skip) self._batch_skip = 0 next_item = self._batch.readline() if next_item: self._count += 1 self._batch_cursor += 1 return Object.from_dict(json.loads(next_item.decode("utf-8"))) else: self._batch = None ``` -------------------------------- ### iterator(path, *path_args, params=None, cursor=None, limit=None, batch_size=0) Source: https://virustotal.github.io/vt-py/api/client.html Returns an iterator for a collection specified by the given path, such as /comments or /intelligence/search. ```APIDOC ## iterator(path, *path_args, params=None, cursor=None, limit=None, batch_size=0) ### Description Returns an iterator for the collection specified by the given path. The endpoint must return a collection of objects. ### Parameters - **path** (str) - Required - Path to API endpoint returning a collection. - **path_args** (Any) - Optional - Variable number of arguments for path placeholders. - **params** (dict) - Optional - Additional parameters passed to the endpoint. - **cursor** (str) - Optional - Cursor for resuming iteration. - **limit** (int) - Optional - Maximum number of objects to return. - **batch_size** (int) - Optional - Maximum number of objects retrieved per call. ``` -------------------------------- ### Access file attributes Source: https://virustotal.github.io/vt-py/quickstart.html Access file metadata directly as object attributes. ```python >>> file.size 68 ``` ```python >>> file.sha256 '275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f' ``` ```python >>> file.type_tag 'text' ``` ```python >>> file.last_analysis_stats {'failure': 0, 'harmless': 0, 'malicious': 62, 'suspicious': 0, 'timeout': 0, 'type-unsupported': 9, 'undetected': 2} ```