-6

import os import hashlib import logging import argparse from typing import Dict, Optional import cx_Oracle

Configure logging

logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler()] ) logger = logging.getLogger(name)

Known malware signatures (SHA-256 hashes)

malware_signatures: Dict[str, str] = { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855": "EICAR Test", # Add more signatures as needed }

Oracle database connection details

db_user = "scott" db_password = "tiger" db_host = "db-server.example.com" db_port = 1521 db_service = "orcl"

def calculate_file_hash(file_path: str) -> Optional[str]: """Calculate SHA-256 hash of a file.""" try: hasher = hashlib.sha256() with open(file_path, "rb") as f: while chunk := f.read(8192): hasher.update(chunk) return hasher.hexdigest() except Exception as e: logger.error(f"Hash calculation error for {file_path}: {e}") return None

def scan_file(file_path: str) -> bool: """Scan a file for malware signatures.""" logger.info(f"Scanning: {file_path}") file_hash = calculate_file_hash(file_path) if file_hash is None: return False

if file_hash in malware_signatures:
    logger.warning(f"Malware detected: {file_path} ({malware_signatures[file_hash]})")
    return True
logger.info(f"File clean: {file_path}")
return False

def scan_directory(directory: str, recursive: bool = True): """Scan files in a directory.""" if not os.path.isdir(directory): logger.error(f"Invalid directory: {directory}") return

for root, _, files in os.walk(directory):
    for file in files:
        file_path = os.path.join(root, file)
        scan_file(file_path)
    if not recursive:
        break

def store_scan_result(file_path: str, is_malware: bool): """Store scan result in Oracle database.""" dsn = f"{db_host}:{db_port}/{db_service}" try: connection = cx_Oracle.connect(user=db_user, password=db_password, dsn=dsn) cursor = connection.cursor() cursor.execute("INSERT INTO scan_results (file_path, is_malware) VALUES (:1, :2)", (file_path, is_malware)) connection.commit() except cx_Oracle.Error as e: logger.error(f"Database error: {e}") finally: if 'connection' in locals(): connection.close()

def parse_args(): parser = argparse.ArgumentParser(description="Malware signature scanner") parser.add_argument("path", help="File or directory to scan") parser.add_argument("-r", "--recursive", action="store_true", help="Recursive scan") parser.add_argument("-v", "--verbose", action="store_true", help="Verbose logging") return parser.parse_args()

if name == "main": args = parse_args() if args.verbose: logger.setLevel(logging.DEBUG)

path = args.path
if os.path.isfile(path):
    is_malware = scan_file(path)
    store_scan_result(path, is_malware)
elif os.path.isdir(path):
    for root, _, files in os.walk(path):
        for file in files:
            file_path = os.path.join(root, file)
            is_malware = scan_file(file_path)
            store_scan_result(file_path, is_malware)
        if not args.recursive:
            break
else:
    logger.error(f"Invalid path: {path}")
New contributor
Ru. is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • Welcome to Main Meta! We're the site for issues relating to the Stack Exchange network as a whole, your question will not be answered here. Please check-out our complete list of sites and ensure to take the tour and read the help center on your chosen site before posting. This is to ensure that your post is in-shape and on-topic. Commented 2 hours ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.