Python Code: Custom Virus and Malware Scanner
David Schunk
IT Professional | CompTIA Sec+ | Active Secret Clearence | Host of Voice of Adoptees | Leader for New Hampshire VMUG | IT Infrastructure & Security Consultant | Adoptee
Requirements:
import os
import hashlib
import pefile
# Function to compute MD5 hash of a file
def compute_md5(file_path):
hash_md5 = hashlib.md5()
try:
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
except Exception as e:
print(f"Error reading {file_path}: {e}")
return None
# Scan for suspicious file signatures (example: PE headers for executables)
def check_pe_signature(file_path):
try:
pe = pefile.PE(file_path)
return True
except pefile.PEFormatError:
return False
except Exception as e:
print(f"Error parsing {file_path}: {e}")
return False
# Example function to scan a directory
def scan_directory(directory):
suspicious_files = []
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
# Example: Scan for suspicious MD5 hash (placeholder values, normally this would compare against a known malware hash database)
known_bad_hashes = ["d41d8cd98f00b204e9800998ecf8427e", "e99a18c428cb38d5f260853678922e03"]
file_hash = compute_md5(file_path)
if file_hash and file_hash in known_bad_hashes:
suspicious_files.append((file_path, "Known malware hash"))
# Check for PE signature (if file is executable)
if check_pe_signature(file_path):
suspicious_files.append((file_path, "PE File (executable)"))
return suspicious_files
# Main function to run the scanner
def main():
directory_to_scan = input("Enter the directory to scan: ")
if not os.path.exists(directory_to_scan):
print("Directory does not exist!")
return
print(f"Scanning {directory_to_scan} for malware...")
suspicious_files = scan_directory(directory_to_scan)
if suspicious_files:
print("Suspicious files found:")
for file_info in suspicious_files:
print(f"File: {file_info[0]} - Reason: {file_info[1]}")
else:
print("No suspicious files found.")
if __name__ == "__main__":
main()
Explanation:
领英推荐
Key Points:
Ensure that you have the pefile library installed by running:
pip install pefile
This is a conceptual starting point. A full-scale antivirus system would involve a variety of other techniques such as real-time scanning, heuristic analysis, sandbox execution, and much more.