How to virus scan an EXE file in Python

Virus scanning incoming executable files is crucial for maintaining the integrity of your project’s security. We need an easy method for getting this functionality up and running in Python, so we are going to use an API that will do just that. Here’s how to set it up.

Install the client for our API first:

pip install cloudmersive-virus-api-client

Now scan_file can be called through use of an API instance. If you look at the following sample code, you will see exactly what I’m talking about.

from __future__ import print_functionimport timeimport cloudmersive_virus_api_clientfrom cloudmersive_virus_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_virus_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_virus_api_client.ScanApi(cloudmersive_virus_api_client.ApiClient(configuration))input_file = '/path/to/file' # file | Input file to perform the operation on.try:# Scan a file for virusesapi_response = api_instance.scan_file(input_file)pprint(api_response)except ApiException as e:print("Exception when calling ScanApi->scan_file: %s\n" % e)

Now run it with your file and you will soon know if the file is safe. For additional functionality, such as restricting file types and allowing password protected files, you can use scan_file_advanced.

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store