pyClamd

0.4.0 · active · verified Thu Apr 16

pyClamd provides a Pythonic interface to the ClamAV daemon (clamd), allowing applications to scan files and streams for viruses. Currently at version 0.4.0, it offers a robust way to integrate anti-malware scanning into Python projects, with releases occurring as needed for bug fixes or minor enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to the ClamAV daemon using `ClamdAgnostic`, ping it to verify connectivity, and then scan both a byte stream and a temporary file containing the EICAR test string. It includes basic error handling for common connection issues.

import pyclamd
import os

# Ensure Clamd daemon is running and accessible (e.g., via network or Unix socket)
# For network socket: Host (default '127.0.0.1'), Port (default 3310)
# For Unix socket: Socket path (default '/var/run/clamav/clamd.ctl')

clamd_host = os.environ.get('CLAMD_HOST', '127.0.0.1')
clamd_port = int(os.environ.get('CLAMD_PORT', '3310'))
clamd_socket = os.environ.get('CLAMD_SOCKET', '/var/run/clamav/clamd.ctl') # Default for many Linux systems

try:
    # Use ClamdAgnostic for automatic detection (Unix socket preferred if available)
    # This will try UnixSocket first, then NetworkSocket
    cd = pyclamd.ClamdAgnostic(
        unix_socket=clamd_socket,
        host=clamd_host,
        port=clamd_port
    )

    # Ping the ClamAV daemon to check connectivity
    cd.ping()
    print("Successfully connected to ClamAV daemon.")

    # EICAR test string (standard antivirus test file)
    eicar_string = b"X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
    
    # Scan a stream of bytes
    result_stream = cd.scan_stream(eicar_string)
    print(f"Scan stream result for EICAR: {result_stream}")

    # Create a dummy file for file scan
    test_file_path = "eicar_test.txt"
    with open(test_file_path, "wb") as f:
        f.write(eicar_string)
    
    result_file = cd.scan_file(test_file_path)
    print(f"Scan file result for '{test_file_path}': {result_file}")

    if os.path.exists(test_file_path):
        os.remove(test_file_path)

except pyclamd.ClamdError as e:
    print(f"ClamAV daemon error: {e}")
    print("Please ensure the ClamAV daemon (clamd) is running and accessible.")
    print(f"  Network: {clamd_host}:{clamd_port}")
    print(f"  Unix Socket: {clamd_socket}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →