vt-py

repository·master·Indexed 20 days ago

https://github.com/virustotal/vt-py

The official Python client library for the VirusTotal REST API v3. It provides a lightweight wrapper for automating security workflows, including file and URL scanning, intelligence searches, LiveHunt management, Retrohunt jobs, and VirusTotal Graphs. The library features the vt.Client class for API interaction, utility functions like vt.url_id for URL conversion, and support for premium features such as Feed API access and file downloads.

Tokens
11.8K
Snippets
33
Records
39
Agent score
73%

What's inside vt-py

  1. Overview of vt-py

    master
    vt-py is the official Python client library for the VirusTotal REST API v3. It allows developers to automate workflows involving file and URL scanning, intelligence searches, LiveHunt management, Retrohunt jobs, and VirusTotal Graphs.
  2. Understand the design philosophy of vt-py

    master

    The vt-py library is designed to be a lightweight, generic wrapper around the VirusTotal REST API rather than a high-level abstraction that hides it.

    Key characteristics include:

    • API Parity: The library's API closely mirrors the underlying VirusTotal REST API. You will frequently need to refer to the VirusTotal REST API documentation to identify correct endpoints and object attributes.
    • Generic HTTP Methods: It provides generic methods like vt.Client.get and vt.Client.post to interact with endpoints.
    • Reduced Boilerplate: While it doesn't abstract away the API structure, it handles low-level details such as setting HTTP headers and serializing/deserializing JSON.
    • Resilience: Because it is lightweight and generic, changes to the VirusTotal REST API often do not require a new version of the vt-py client library.
  3. Install vt-py from source

    master

    You can install vt-py from source by cloning the GitHub repository or downloading a release tarball, then running pip install . from within the project directory.

    # Option 1: Clone from GitHub
    $ git clone https://github.com/VirusTotal/vt-py.git
    $ cd vt-py
    $ pip install .
    
    # Option 2: Use a downloaded tarball
    $ tar -zxvf vt-py-X.Y.Z.tar.gz
    $ cd vt-py-X.Y.Z
    $ pip install .
  4. Initialize the VirusTotal Client

    master

    To use vt-py, import the vt module and instantiate a vt.Client with your API key. It is recommended to use the client as a context manager to ensure it is properly closed at the end of your script, which prevents tracebacks related to unclosed clients.

    import vt
    
    # Using a context manager (recommended)
    with vt.Client("<apikey>") as client:
        # Your code here
        pass
    
    # Manual initialization
    client = vt.Client("<apikey>")
    # ... perform tasks ...
    client.close()
  5. Handle HTTP responses with ClientResponse

    master

    The ClientResponse class wraps aiohttp.ClientResponse to provide both synchronous and asynchronous methods for reading response data. It also handles chunked transfer encoding automatically.

    Available Methods:

    • read() / read_async(): Returns response body as bytes.
    • json() / json_async(): Returns response body as a dict.
    • text() / text_async(): Returns response body as a str.
    • content: Returns a StreamReader for streaming the response body.

    Note: Methods ending in _async are coroutines and must be awaited.

    # Async example
    response = await client.get_async('/some/endpoint')
    data = await response.json_async()
    
    # Sync example
    response = client.get('/some/endpoint')
    data = response.json()
  6. Initialize the Client

    master

    The Client class is the primary entry point for interacting with the VirusTotal API. It supports both synchronous and asynchronous usage. You can configure proxies, custom headers, timeouts, and SSL verification during initialization.

    Parameters:

    • apikey (str): Your VirusTotal API key.
    • agent (str): A string identifying your application (default: "unknown").
    • host (str, optional): The API host (default: "https://www.virustotal.com").
    • trust_env (bool): If True, retrieves proxy information from HTTP_PROXY/HTTPS_PROXY environment variables (default: False).
    • timeout (int): Request timeout in seconds (default: 300).
    • proxy (str, optional): Proxy URL to use for requests.
    • headers (dict, optional): Custom HTTP headers.
    • verify_ssl (bool): Whether to verify SSL certificates (default: True).
    • connector (aiohttp.BaseConnector, optional): A custom aiohttp connector.
    from vt import Client
    
    # Synchronous usage
    client = Client(apikey='YOUR_API_KEY')
    
    # Asynchronous usage (recommended for high performance)
    async with Client(apikey='YOUR_API_KEY') as client:
        # perform async operations
        pass
  7. Use the vt.Client class to interact with the VirusTotal API

    master

    The vt.Client class is the primary entry point for using the vt-py library. It manages the connection to the VirusTotal API and provides methods for making requests. You must provide an API key when initializing the client.

    Commonly associated types include:

    • Client: The main client instance.
    • ClientResponse: Represents the response received from the API.
    • APIError: The exception raised when an API request fails.
    import vt
    
    client = vt.Client('YOUR_API_KEY')
    # Use client to make API calls
  8. Scan a file or URL

    master

    You can submit files or URLs for analysis using client.scan_file() or client.scan_url().

    Handling Analysis Status: When a scan is submitted, the returned object initially only contains an id. You must poll the /analyses/ endpoint until the status attribute is "completed".

    Wait for Completion: Alternatively, you can pass wait_for_completion=True to the scan method. This makes the method blocking, so it will not return until the analysis is finished.

    import vt
    import time
    client = vt.Client("<apikey>")
    
    # Option 1: Non-blocking scan with manual polling
    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)
    
    # Option 2: Blocking scan (waits for completion)
    with open("/path/to/file", "rb") as f:
        analysis = client.scan_file(f, wait_for_completion=True)
    
    # Scanning a URL
    analysis = client.scan_url('https://somedomain.com/foo/bar')
  9. Convert a URL to a VirusTotal URL ID using `vt.url_id`

    master

    The vt.url_id utility function converts a standard URL into a VirusTotal-compatible URL ID. This ID is used when performing lookups or interacting with URL objects via the API, ensuring the URL is properly formatted for VirusTotal's internal identification system.

    import vt
    
    url_id = vt.url_id("https://www.google.com")
    # Returns the formatted ID used for API requests
  10. Get information about a URL

    master

    To retrieve information about a URL, you must first generate a unique identifier using vt.url_id(). This identifier is then used to construct the API path. You can use Python's string formatting to inject the url_id into the path string.

    import vt
    client = vt.Client("<apikey>")
    
    # Generate the required URL identifier
    url_id = vt.url_id("http://www.virustotal.com")
    
    # Retrieve the URL object
    url = client.get_object("/urls/{}", url_id)
    # OR using string formatting:
    # url = client.get_object("/urls/{}".format(url_id))
    
    print(url.times_submitted)