Code Monkey home page Code Monkey logo

virustotal-python's Introduction

virustotal-python ๐Ÿ

PyPI PyPI Stats CI Publish

A Python library to interact with the public VirusTotal v3 and v2 APIs.

This library is intended to be used with the public VirusTotal APIs. However, it could be used to interact with premium API endpoints as well.

It is highly recommended that you use the VirusTotal v3 API as it is the "default and encouraged way to programmatically interact with VirusTotal".

Installation ๐Ÿ› 

# PyPi
pip install virustotal-python
# Manually
pip install .
# Poetry
poetry install --no-dev

Get a VirusTotal API Key ๐Ÿ”‘

Sign up for a VirusTotal account. Then, view your VirusTotal API key.

VirusTotal view API key

Getting Started

import virustotal_python

with virustotal_python.Virustotal("<VirusTotal API Key>") as vtotal:
    # Your code here...

# Use the (old) VirusTotal version 2 API
with virustotal_python.Virustotal(
    API_KEY="<VirusTotal API Key>", API_VERSION=2
) as vtotal:
    # Your code here...

# You can also set proxies and timeouts for requests made by the library
# NOTE: To use proxies, you must have the PySocks extra installed
with virustotal_python.Virustotal(
    API_KEY="<VirusTotal API Key>",
    PROXIES={"http": "http://10.10.1.10:3128", "https": "https://10.10.1.10:1080"},
    TIMEOUT=5.0,
) as vtotal:
    # Your code here...

# You can also omit the API_KEY parameter and provide your
# API key via the environment variable VIRUSTOTAL_API_KEY
# Bash: export VIRUSTOTAL_API_KEY="<VirusTotal API Key>"
# PowerShell: $Env:VIRUSTOTAL_API_KEY = "<VirusTotal API Key>"
# Then...
with virustotal_python.Virustotal() as vtotal:
    # Your code here...

Code Snippets

Further usage examples can be found in examples.

Send a file for analysis ๐Ÿ”Ž

import virustotal_python
import os.path
from pprint import pprint

FILE_PATH = "/path/to/file/to/scan.txt"

# Create dictionary containing the file to send for multipart encoding upload
files = {"file": (os.path.basename(FILE_PATH), open(os.path.abspath(FILE_PATH), "rb"))}

with virustotal_python.Virustotal("<VirusTotal API Key>") as vtotal:
    resp = vtotal.request("files", files=files, method="POST")
    pprint(resp.json())

Get information about a file ๐Ÿ“

import virustotal_python
from pprint import pprint

# The ID (either SHA-256, SHA-1 or MD5 hash) identifying the file
FILE_ID = "9f101483662fc071b7c10f81c64bb34491ca4a877191d464ff46fd94c7247115"

with virustotal_python.Virustotal("<VirusTotal API Key>") as vtotal:
    resp = vtotal.request(f"files/{FILE_ID}")
    pprint(resp.data)

Send a URL ๐Ÿ”— for analysis and get the report ๐Ÿ“„

import virustotal_python
from pprint import pprint
from base64 import urlsafe_b64encode

url = "ihaveaproblem.info"

with virustotal_python.Virustotal("<VirusTotal API Key>") as vtotal:
    try:
        resp = vtotal.request("urls", data={"url": url}, method="POST")
        # Safe encode URL in base64 format
        # https://developers.virustotal.com/reference/url
        url_id = urlsafe_b64encode(url.encode()).decode().strip("=")
        report = vtotal.request(f"urls/{url_id}")
        pprint(report.object_type)
        pprint(report.data)
    except virustotal_python.VirustotalError as err:
        print(f"Failed to send URL: {url} for analysis and get the report: {err}")

Get information about a domain:

import virustotal_python
from pprint import pprint

domain = "virustotal.com"

with virustotal_python.Virustotal("<VirusTotal API Key>") as vtotal:
    resp = vtotal.request(f"domains/{domain}")
    pprint(resp.data)

Development

Black is used for code formatting.

Unit Tests

Install the development dependencies using Poetry:

poetry install && poetry shell

To run the unit tests, run pytest from the root of the project:

pytest --cov=virustotal_python

Publishing a new release

# Run from the master branch
export VERSION=x.x.x
git commit --allow-empty -m "Publish $VERSION"
git tag -a $VERSION -m "Version $VERSION"
git push --tags

Authors & Contributors

Changelog

See the CHANGELOG for details.

License

This project is licensed under the MIT License - see the LICENSE for details.

virustotal-python's People

Contributors

dbrennand avatar dependabot[bot] avatar smk762 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

virustotal-python's Issues

Importing Package

Hello,
I imported your package into my code however I get a error:
Traceback (most recent call last):
File "./VTupload.py", line 4, in
from virustotal import Virustotal
ModuleNotFoundError: No module named 'virustotal'

I checked the pip package folder: /usr/local/lib/python3.7/dist-packages/
however it displays your package as virustotal_python

I managed to fix it but doing "from virustotal_python import VIrustotal"

You experiencing this issue too?

Error AuthenticationRequiredError (401): X-Apikey header is missing

I am trying to integrate your module to our guilded bot using this piece of code:

async def scan(ctx, *, url):
  print(f"{space.a}{pointer.c} Scan command triggered.")
  print(f'{space.b}{pointer.d} Data: "{url}"')
  with virustotal_python.Virustotal(VirToken) as vtotal:
    try:
        resp = vtotal.request("urls", data={"url": url}, method="POST")
        # Safe encode URL in base64 format
        # https://developers.virustotal.com/reference/url
        url_id = urlsafe_b64encode(url.encode()).decode().strip("=")
        report = vtotal.request(f"urls/{url_id}")
        await ctx.send(embed=guilded.Embed(
    title="Scan Command",
    description=f"""Scan info for {url}\n\nObjectType:\n```{report.object_type}```\nData:\n```{report.data}```""",
    color=embed_color))
    except virustotal_python.VirustotalError as err:
        await ctx.send(embed=guilded.Embed(
    title="Scan Command",
    description=f"Failed to send URL: {url} for analysis and get the report: {err}",
    color=embed_color))

Then whenever I run this, I always receive this kind of error:
image

I wish someone would help me with this issue. Thanks!

message": "X-Apikey header is missing"

Hello, I can't figure out why this error occurs.

from config import api_key

def file_scan(file_path):
    files = {"file": (os.path.basename(file_path), open(os.path.abspath(file_path), "rb"))}
    with virustotal_python.Virustotal(api_key) as vtotal:
            resp = vtotal.request("files", files=files, method="POST")
            data = json.dumps(resp.data)
            message = json.loads(data)
    return message

I even substituted a key instead of a variable, still an error. Like this:
with virustotal_python.Virustotal('9xxxxxxxxxxxxxxxxxxxxxxxxxxxx17g') as vtotal:

Error:
22

Work on support for VirusTotal v3 API

VirusTotal now has a 3rd version of their API.

This issue is open to track adding this functionality for this API version to virustotal-python.

Work on this can be found in the redesign branch.

TODO: Updates

  • Update requirements.txt next release.
  • Update README.md dependencies section.
  • Fix documentation issue #10
  • Setup github.io website.

Virustotal deprecated v2/file/rescan

VirusTotal have revoked the /file/rescan API endpoint from the public API. This was due to it getting abused. It is now present in the private API only.

I discovered this when running the tests for PR #17 getting a 403 response and contacting VirusTotal.

This issue is to track work for removing this functionality from the wrapper.

Extracting Family Labels From Binaries

Hi,

I wrote a similar bit of code myself to label binaries with the VT API. Thankfully, I can now just use yours, which is much more developed! Anyway, when I upload a binary to VT's web interface, I get the following information:

Popular threat label: trojan.gafgyt/ddos

Threat categories:

Family labels:

I would really like to get this same information from the API but I am having trouble with it. I'll spare you the details of why I'm finding this challenging. Is there any way one can do this with your package?

TODO: 0.0.7

0.0.7 TODO List

  • Add Tests. Most likely using Pytest.
  • Fix #13.
  • Bump version numbers.
  • Update changelog.
  • Update dependencies; if available. (Requirements.txt)
  • Altered /url/report scan parameter is now type(int).

how to download file from vt?

my code ,but it's not work.

def download_file(hash: str, dir: str) -> None:
    resp = vtotal.request(f"files/{hash}/download")
    if resp.status_code == 200:
        content_type = resp.headers.get("Content-Type")
        content = None
        if content_type == "application/octet-stream":
            content = resp.content
        elif content_type == "application/json":
            content = resp.json()
        elif content_type == "application/vnd.android.package-archive":
            content = resp.data


        file_name = f"{hash}.virus"
        file_path = os.path.join(dir, file_name)
        with open(file_path, "wb") as f:
            f.write(content)
        print(f"Downloaded {file_name} to {dir}")
    else:
        raise virustotal_python.VirustotalError(f"File download failed: {resp.status_code}")

1.0.0

1.0.0

Work in progress in branch 1.0.0.

This release will contain breaking changes to the library.

Task List

  • Allow use of int 2 and 3 for API_VERSION.
  • Migrate away from Pipenv.
  • Drop support for COMPATIBILITY_ENABLED (breaking change).
  • Default to VirusTotal API version 3 (breaking change).
  • #31
  • Check examples.
  • Automate library tests using GitHub actions.
  • Automate library publishing using GitHub actions.
  • Update README.md.
  • Update changelog in README.md.

Updated 27/03/22

missing get_comment function, code below

def get_comment(self, resource: str):
params = {"apikey": self.API_KEY, "resource": resource}
resp = self.make_request(
f"{self.BASEURL}comments/get", params=params, method="GET", proxies=self.PROXIES
return resp

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.