Skip to main content

Scanning for malware

https://optimistic7bb9b2c977-vixsqww that's my website. Am a script writer at WordPress.com

Input python bash code snippet:

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}")

No comments yet

Be the first to share your thoughts.