VirusTotal Python Client Library
vt-py is the official Python client library for the VirusTotal API v3. This library enables interaction with the VirusTotal REST API v3 to automate security workflows, including scanning files and URLs, retrieving comprehensive information about various entities (files, URLs, domains), managing VirusTotal Intelligence searches, LiveHunt rulesets, and launching Retrohunt jobs. It is actively maintained with regular releases.
Warnings
- breaking Python 3.7 support was officially dropped in `vt-py` version 0.21.0. Users on Python 3.7 or older will need to upgrade their Python version or pin `vt-py` to a version prior to 0.21.0.
- breaking In `vt-py` v0.20.0, the `WhistleBlowerDict` (a subclass of `collections.UserDict`) used internally for `vt.Object` attributes was converted to a plain Python `dict`. Code relying on `UserDict` specific behaviors or encountering 'Object of type WhistleBlowerDict is not JSON serializable' errors in older versions should be updated.
- gotcha The `vt-py` library is built around `asyncio`. Running client methods in synchronous code or within existing event loops (e.g., in some web frameworks or cloud functions) without proper `asyncio` context can lead to `RuntimeError: There is no current event loop in thread...` errors.
- gotcha It is crucial to explicitly close the `vt.Client` instance to release underlying network resources (like TCP connections) when it's no longer needed. Not doing so can lead to resource leaks and potential runtime warnings/errors.
- gotcha The `vt-py` library is designed as a relatively low-level wrapper around the VirusTotal API v3. Users are expected to have a good understanding of the VirusTotal API v3 concepts and REST endpoint paths, as the library mirrors the API structure rather than providing a high level of abstraction.
Install
-
pip install vt-py
Imports
- Client
from vt.client import Client
import vt client = vt.Client(api_key)
- url_id
from vt.client import url_id
import vt url_identifier = vt.url_id(url)
Quickstart
import os
import asyncio
import vt
async def get_file_info(api_key: str, file_hash: str):
"""Fetches information about a file hash from VirusTotal."""
async with vt.Client(api_key) as client:
try:
file_obj = await client.get_object(f"/files/{file_hash}")
print(f"File SHA256: {file_obj.sha256}")
print(f"File Size: {file_obj.size} bytes")
print(f"Detection Stats: {file_obj.last_analysis_stats}")
except vt.APIError as e:
print(f"VirusTotal API error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
VIRUSTOTAL_API_KEY = os.environ.get('VIRUSTOTAL_API_KEY', '')
if not VIRUSTOTAL_API_KEY:
print("Please set the VIRUSTOTAL_API_KEY environment variable.")
else:
# Example SHA256 hash of an EICAR test file
example_hash = "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"
asyncio.run(get_file_info(VIRUSTOTAL_API_KEY, example_hash))