### Install ClamAV Daemon on Ubuntu Source: https://github.com/graingert/python-clamd/blob/master/README.rst Provides the necessary shell commands to install the ClamAV daemon and its related components on an Ubuntu system. It includes steps for installing the packages, updating virus definitions, and starting the daemon service. ```bash sudo apt-get install clamav-daemon clamav-freshclam clamav-unofficial-sigs sudo freshclam sudo service clamav-daemon start ``` -------------------------------- ### Install Clamd and ClamAV Daemon Source: https://context7.com/graingert/python-clamd/llms.txt Instructions for installing the Python clamd package and setting up the ClamAV daemon on Debian-based systems. ```bash pip install clamd sudo apt-get install clamav-daemon clamav-freshclam clamav-unofficial-sigs sudo freshclam sudo service clamav-daemon start ``` -------------------------------- ### Scan Files and Directories Source: https://context7.com/graingert/python-clamd/llms.txt Examples of scanning single files, performing parallel directory scans, and continuous scanning to handle errors gracefully. ```python import clamd import os import tempfile cd = clamd.ClamdUnixSocket() # Single file scan result = cd.scan('/path/to/document.pdf') # Parallel directory scan results = cd.multiscan('/var/uploads') # Continuous scan results_cont = cd.contscan('/home/user/downloads') ``` -------------------------------- ### Get Daemon Statistics with stats() Source: https://context7.com/graingert/python-clamd/llms.txt The stats() method retrieves runtime statistics from the ClamAV daemon. This includes information about the pool status, queue information, and memory usage, providing insights into the daemon's operational state. ```python import clamd cd = clamd.ClamdUnixSocket() stats = cd.stats() print(stats) # Output: # POOLS: 1 # STATE: VALID PRIMARY # THREADS: live 1 idle 0 max 10 idle-timeout 30 # QUEUE: 0 items # MEMSTATS: heap N/A mmap N/A used N/A free N/A releasable N/A pools 1 pools_used N/A pools_total N/A # END ``` -------------------------------- ### version() - Get ClamAV Version Source: https://context7.com/graingert/python-clamd/llms.txt Retrieves the ClamAV version string and virus database information. ```APIDOC ## GET /version ### Description Returns the ClamAV version string and virus database information from the running daemon. ### Method GET ### Endpoint /version ### Response #### Success Response (200) - **version_info** (string) - The version string of the ClamAV daemon. #### Response Example "ClamAV 0.103.2/26144/Wed Apr 14 10:12:18 2021" ``` -------------------------------- ### Connect and Ping Clamd Daemon (Python) Source: https://github.com/graingert/python-clamd/blob/master/README.rst Demonstrates how to establish a connection to a running clamd daemon using a Unix socket and perform a basic ping operation to verify connectivity. It also shows how to retrieve the daemon's version and trigger a reload. ```python import clamd cd = clamd.ClamdUnixSocket() print(cd.ping()) print(cd.version()) print(cd.reload()) ``` -------------------------------- ### Connect to ClamAV via Unix Socket Source: https://context7.com/graingert/python-clamd/llms.txt Demonstrates how to initialize a connection to the ClamAV daemon using local Unix domain sockets. ```python import clamd cd = clamd.ClamdUnixSocket() cd = clamd.ClamdUnixSocket(path="/var/run/clamav/clamd.sock", timeout=30.0) response = cd.ping() print(response) ``` -------------------------------- ### Scan File with Clamd (Python) Source: https://github.com/graingert/python-clamd/blob/master/README.rst Illustrates how to scan a specified file for viruses using the clamd daemon. This involves writing a test signature to a file and then passing the file path to the scan function. The output indicates if a threat is found. ```python import clamd # Assuming clamd.EICAR contains the EICAR test signature with open('/tmp/EICAR', 'wb') as f: f.write(clamd.EICAR) cd = clamd.ClamdUnixSocket() result = cd.scan('/tmp/EICAR') print(result) ``` -------------------------------- ### Check Daemon Connectivity and Version Source: https://context7.com/graingert/python-clamd/llms.txt Methods to verify if the ClamAV daemon is responsive and to retrieve the current version information. ```python import clamd cd = clamd.ClamdUnixSocket() try: response = cd.ping() if response == 'PONG': print("ClamAV daemon is running and responsive") except clamd.ConnectionError as e: print(f"Cannot connect to ClamAV daemon: {e}") version_info = cd.version() print(version_info) ``` -------------------------------- ### Connect to ClamAV via TCP Network Source: https://context7.com/graingert/python-clamd/llms.txt Demonstrates how to connect to a remote or containerized ClamAV daemon instance using TCP. ```python import clamd cd = clamd.ClamdNetworkSocket() cd = clamd.ClamdNetworkSocket(host='192.168.1.100', port=3310, timeout=60.0) response = cd.ping() print(response) ``` -------------------------------- ### ping() - Check Daemon Connectivity Source: https://context7.com/graingert/python-clamd/llms.txt Sends a PING command to verify the ClamAV daemon is responsive. ```APIDOC ## GET /ping ### Description Sends a PING command to verify the ClamAV daemon is responsive and accepting connections. ### Method GET ### Endpoint /ping ### Response #### Success Response (200) - **status** (string) - Returns 'PONG' if the daemon is responsive. #### Response Example "PONG" ``` -------------------------------- ### multiscan() - Parallel Directory Scanning Source: https://context7.com/graingert/python-clamd/llms.txt Scans a directory using multiple threads for improved performance. ```APIDOC ## POST /multiscan ### Description Scans a directory using multiple threads for improved performance on multi-core systems. ### Method POST ### Parameters #### Request Body - **path** (string) - Required - Absolute path to the directory to scan. ### Response #### Success Response (200) - **results** (object) - A dictionary mapping file paths to a tuple of (status, signature). #### Response Example { "/var/uploads/file1.pdf": ("OK", None), "/var/uploads/file2.exe": ("FOUND", "Win.Trojan.Agent-12345") } ``` -------------------------------- ### Reload Virus Database with reload() Source: https://context7.com/graingert/python-clamd/llms.txt The reload() method instructs the ClamAV daemon to reload its virus signature database. This is useful after updating definitions with freshclam, allowing the daemon to recognize new threats without requiring a service restart. ```python import clamd cd = clamd.ClamdUnixSocket() # Reload virus definitions after freshclam update result = cd.reload() print(result) # Output: 'RELOADING' ``` -------------------------------- ### Clamd Error Handling in Python Source: https://context7.com/graingert/python-clamd/llms.txt This snippet demonstrates how to handle various exceptions provided by the clamd library during operations like connection, response errors, and buffer overflows. Proper error handling ensures robust integration of virus scanning. ```python import clamd from io import BytesIO cd = clamd.ClamdUnixSocket() # Handle connection errors try: cd.ping() except clamd.ConnectionError as e: print(f"Failed to connect to ClamAV daemon: {e}") # Handle response errors try: result = cd.scan('/nonexistent/file') except clamd.ResponseError as e: print(f"ClamAV returned an error: {e}") # Handle buffer too long errors (stream exceeds StreamMaxLength) try: large_data = BytesIO(b"x" * 100000000) # Very large stream result = cd.instream(large_data) except clamd.BufferTooLongError as e: print(f"Stream too large for scanning: {e}") # Comprehensive error handling try: result = cd.scan('/path/to/file') except clamd.ConnectionError: print("Cannot connect to ClamAV - is clamd running?") except clamd.ResponseError as e: print(f"Scan failed: {e}") except clamd.ClamdError as e: print(f"ClamAV error: {e}") ``` -------------------------------- ### Scan Stream with Clamd (Python) Source: https://github.com/graingert/python-clamd/blob/master/README.rst Shows how to scan data directly from a byte stream without saving it to a file. This is useful for scanning in-memory data or data piped from other sources. The function takes a BytesIO object containing the data to be scanned. ```python from io import BytesIO import clamd cd = clamd.ClamdUnixSocket() stream_data = BytesIO(clamd.EICAR) result = cd.instream(stream_data) print(result) ``` -------------------------------- ### Stop the Daemon with shutdown() Source: https://context7.com/graingert/python-clamd/llms.txt The shutdown() method sends a command to stop the ClamAV daemon gracefully. Use this method with caution as it terminates the service. It does not return a value as the daemon process exits. ```python import clamd cd = clamd.ClamdUnixSocket() # Gracefully shutdown the daemon (requires appropriate permissions) cd.shutdown() # Note: No return value; daemon process exits ``` -------------------------------- ### scan() - Scan a Single File Source: https://context7.com/graingert/python-clamd/llms.txt Scans a single file or directory for viruses. ```APIDOC ## POST /scan ### Description Scans a single file or directory for viruses. The path must be absolute and accessible to the clamd daemon process. ### Method POST ### Parameters #### Request Body - **path** (string) - Required - Absolute path to the file or directory to scan. ### Response #### Success Response (200) - **results** (object) - A dictionary mapping file paths to a tuple of (status, signature). #### Response Example { "/path/to/file.pdf": ("OK", None) } ``` -------------------------------- ### Scan Data Stream with instream() Source: https://context7.com/graingert/python-clamd/llms.txt The instream() method scans data from a file-like object without writing to disk. This is ideal for scanning uploaded files or network streams before saving them. It takes a BytesIO object or any file-like object as input and returns a dictionary indicating the scan result. ```python import clamd from io import BytesIO cd = clamd.ClamdUnixSocket() # Scan a byte stream (e.g., file upload) file_data = b"This is some file content to scan" result = cd.instream(BytesIO(file_data)) print(result) # Output for clean data: {'stream': ('OK', None)} # Scan stream containing virus signature infected_stream = BytesIO(clamd.EICAR) result = cd.instream(infected_stream) print(result) # Output: {'stream': ('FOUND', 'Eicar-Test-Signature')} # Integration with file uploads (Flask example) def scan_upload(uploaded_file): cd = clamd.ClamdUnixSocket() result = cd.instream(uploaded_file.stream) status, signature = result['stream'] if status == 'FOUND': raise ValueError(f"Malware detected: {signature}") return True ``` -------------------------------- ### Use EICAR Test Signature Source: https://context7.com/graingert/python-clamd/llms.txt The clamd module provides the EICAR test signature as a harmless byte string. This allows developers to verify that their antivirus scanning integration is functioning correctly by simulating the detection of a known virus. ```python import clamd from io import BytesIO # EICAR is the industry-standard antivirus test signature # It is detected as a virus by all AV software but is completely harmless print(clamd.EICAR) # Output: b'X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' # Use EICAR to verify scanning is working cd = clamd.ClamdUnixSocket() result = cd.instream(BytesIO(clamd.EICAR)) assert result == {'stream': ('FOUND', 'Eicar-Test-Signature')} print("Antivirus scanning is working correctly!") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.