you can use a combination of Static Analysis and Heuristic Detection.
Malicious scripts frequently use specific patterns like obfuscation (hiding the code's meaning), dynamic execution (running code stored in strings), and unusual network imports.
1. The Malicious Code Detector Script
This Python script scans another file for "red flags" such as suspicious library imports and dangerous functions like eval() or exec().
import ast
import os
# Keywords often used in malicious or unauthorized scripts
SUSPICIOUS_FUNCTIONS = {'eval', 'exec', 'getattr', 'os.system', 'subprocess.Popen'}
SUSPICIOUS_MODULES = {'base64', 'socket', 'requests', 'cryptography', 'pynput'}
def analyze_code(file_path):
if not os.path.exists(file_path):
print("Error: File not found.")
return
with open(file_path, "r", encoding="utf-8") as file:
tree = ast.parse(file.read())
found_flags = []
# Walk through the code structure (AST)
for node in ast.walk(tree):
# Check for suspicious imports
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name in SUSPICIOUS_MODULES:
found_flags.append(f"[!] Suspicious Module Imported: {alias.name}")
# Check for dangerous function calls
if isinstance(node, ast.Call):
func_name = ""
if isinstance(node.func, ast.Name):
func_name = node.func.id
elif isinstance(node.func, ast.Attribute):
func_name = f"{node.func.value.id if hasattr(node.func.value, 'id') else '?'}.{node.func.attr}"
if func_name in SUSPICIOUS_FUNCTIONS:
found_flags.append(f"[!] Dangerous Function Call: {func_name}")
# Output findings
if found_flags:
print(f"--- Analysis Report for {file_path} ---")
for flag in found_flags:
print(flag)
else:
print("No immediate red flags detected.")
if __name__ == "__main__":
target = input("Enter the path of the script to analyze: ")
analyze_code(target)
2. Common "Hacker" Patterns Explained
When looking at code you suspect is malicious, you are likely to see these three techniques:
A. Obfuscation (The "Shell" Game)
Attackers hide their code using Base64 encoding or character shifting to bypass security scanners.
What it looks like:
exec(base64.b64decode("Y29udGVudA=="))Why it's used: It prevents you from seeing the actual commands (like deleting files or stealing data) until the code is actually running.
B. Reverse Shells (The "Open Door")
A script that connects your computer back to the attacker's server, giving them command-line access.
What it looks like: Uses the
socketlibrary to connect to an external IP on a port like4444.Why it's used: It allows the hacker to control your machine remotely as if they were sitting in front of it.
C. Persistence Mechanisms (The "Sticky" Code)
Malicious code often tries to ensure it runs every time you restart your computer.
What it looks like: Code that modifies
crontab(Linux) or theRegistry(Windows).Why it's used: So that even if you find and stop the running process, the script will simply "wake up" again later.
Python File Backup Script
This script will recursively copy all folders and files from your specified source to a new destination folder.
Pythonimport shutil import os def backup_disk_data(source_dir, destination_dir): """ Copies all content from source_dir to destination_dir. """ try: # Check if the source exists if not os.path.exists(source_dir): print(f"Error: Source path '{source_dir}' does not exist.") return # Create destination directory if it doesn't exist if not os.path.exists(destination_dir): os.makedirs(destination_dir) print(f"Created destination folder: {destination_dir}") # Copying process print(f"Starting copy from {source_dir} to {destination_dir}...") # dirs_exist_ok=True allows copying into an existing folder without crashing shutil.copytree(source_dir, destination_dir, dirs_exist_ok=True) print("Backup completed successfully!") except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": # Update these paths for your system # Example for Windows: "E:\\" (External Disk) # Example for Mac/Linux: "/Volumes/MyDisk" source = "SOURCE_PATH_HERE" destination = "DESTINATION_PATH_HERE" backup_disk_data(source, destination)Key Considerations
Permissions: Ensure the script is run with enough privileges to read the source disk and write to the destination.
Path Formatting: On Windows, use double backslashes (
\\) or a raw string (r"C:\Path") to avoid escape character errors.Disk Space: Before running the script, verify that the destination disk has enough free space to hold the entire contents of the source.
Managing File Duplicates
If your goal is to manage or find existing duplicates on your disks to save space, you might be interested in a Hashing approach. This involves reading files and generating a unique "fingerprint" (MD5 or SHA256) for each to identify identical files even if they have different names.
Comments
Post a Comment