import re import dns.resolver def is_valid_email(email): """Validate the email format and check for MX records.""" # Regex pattern for validating an Email pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' if not re.match(pattern, email): return False, "Invalid email format." domain = email.split('@')[1] try: # Check for MX records dns.resolver.resolve(domain, 'MX') return True, "Valid email address with a working domain." except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN): return False, "Valid format but no MX record found." if __name__ == "__main__": email = input("Enter an email address to validate: ") is_valid, message = is_valid_email(email) print(message)
Category: python
-
Email Validation Script
-
Password Generator
import random import string def generate_password(length=12, use_uppercase=True, use_lowercase=True, use_digits=True, use_symbols=True): """Generate a secure random password based on user preferences.""" characters = '' if use_uppercase: characters += string.ascii_uppercase if use_lowercase: characters += string.ascii_lowercase if use_digits: characters += string.digits if use_symbols: characters += string.punctuation if not characters: raise ValueError("At least one character type must be selected!") password = ''.join(random.choice(characters) for _ in range(length)) return password if __name__ == "__main__": print("--- Password Generator ---") length = int(input("Enter desired password length (default is 12): ") or 12) use_uppercase = input("Include uppercase letters? (y/n, default is y): ").strip().lower() != 'n' use_lowercase = input("Include lowercase letters? (y/n, default is y): ").strip().lower() != 'n' use_digits = input("Include digits? (y/n, default is y): ").strip().lower() != 'n' use_symbols = input("Include symbols? (y/n, default is y): ").strip().lower() != 'n' try: generated_password = generate_password(length, use_uppercase, use_lowercase, use_digits, use_symbols) print(f"Generated Password: {generated_password}") except ValueError as e: print(e)
-
Text-Based Adventure Game
def start_game(): print("Welcome to the Adventure Game!") print("You find yourself in a dark forest. You can go left or right.") choice = input("Which way do you want to go? (left/right): ").strip().lower() if choice == "left": encounter_wolf() elif choice == "right": encounter_river() else: print("Invalid choice. Please try again.") start_game() def encounter_wolf(): print("\nYou encounter a wild wolf!") print("1. Try to scare it away.") print("2. Run away.") choice = input("What do you want to do? (1/2): ") if choice == "1": print("You bravely try to scare the wolf, and it runs away! You are safe.") elif choice == "2": print("You run away as fast as you can. The wolf chases you, but you manage to escape!") else: print("Invalid choice. Please try again.") encounter_wolf() def encounter_river(): print("\nYou come across a serene river.") print("1. Try to swim across.") print("2. Look for a bridge.") choice = input("What do you want to do? (1/2): ") if choice == "1": print("You bravely swim across the river. It's cold, but you make it!") elif choice == "2": print("You find a bridge and safely cross the river.") else: print("Invalid choice. Please try again.") encounter_river() if __name__ == "__main__": start_game()
-
File Integrity Checker
import hashlib import os import json def calculate_file_hash(file_path): """Calculate the SHA-256 hash of a file.""" if not os.path.isfile(file_path): raise FileNotFoundError(f"The file '{file_path}' does not exist.") sha256_hash = hashlib.sha256() with open(file_path, "rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest() def save_hash(file_path, hash_value): """Save the hash value to a .json file.""" if not os.path.exists("file_hashes.json"): with open("file_hashes.json", "w") as f: json.dump({}, f) with open("file_hashes.json", "r+") as f: try: data = json.load(f) except json.JSONDecodeError: data = {} data[file_path] = hash_value f.seek(0) json.dump(data, f, indent=4) def check_file_integrity(file_path): """Check if a file's hash matches the stored hash.""" current_hash = calculate_file_hash(file_path) if os.path.exists("file_hashes.json"): with open("file_hashes.json", "r") as f: data = json.load(f) stored_hash = data.get(file_path) if stored_hash: if current_hash == stored_hash: return "File is intact." else: return "File has been modified!" else: return "No stored hash found for this file." else: return "No hash records found. Please save the hash first." if __name__ == "__main__": action = input("Enter 'save' to save a file hash or 'check' to check file integrity: ").strip().lower() file_path = input("Enter the path of the file: ") if action == 'save': file_hash = calculate_file_hash(file_path) save_hash(file_path, file_hash) print(f"Hash for '{file_path}' saved.") elif action == 'check': result = check_file_integrity(file_path) print(result) else: print("Invalid action. Please enter 'save' or 'check'.")
-
YALAT (Yet Another Log Analysis Tool)
import re from collections import Counter # Define patterns for suspicious activities SUSPICIOUS_PATTERNS = { r"failed password": "Failed login attempt detected.", r"authentication failure": "Authentication failure detected.", r"root": "Root access attempt detected.", r"exec": "Execution of commands detected.", r"delete": "Delete operation detected.", r"unauthorized access": "Unauthorized access attempt detected.", } def analyze_log(file_path): with open(file_path, 'r') as file: log_data = file.readlines() findings = Counter() for line in log_data: for pattern, message in SUSPICIOUS_PATTERNS.items(): if re.search(pattern, line, re.IGNORECASE): findings[message] += 1 return findings def display_findings(findings): print("\n--- Log Analysis Findings ---") if findings: for message, count in findings.items(): print(f"{message}: {count} times") else: print("No suspicious activities detected.") if __name__ == "__main__": log_file_path = input("Enter the path to the log file: ") findings = analyze_log(log_file_path) display_findings(findings)
-
Basic WAF (Web Application Firewall)
from flask import Flask, request, render_template_string import re app = Flask(__name__) # Define common attack patterns to block with tailored messages BLOCKED_PATTERNS = { r"' OR '1'='1'": "Detected SQL Injection attempt: This input could manipulate database queries.", r"'(.*?)--": "Detected SQL Injection attempt: This input could terminate a query.", r"<script.*?>": "Detected XSS attempt: This input could execute malicious scripts in users' browsers.", r"(?i)DROP\s+TABLE": "Detected SQL Injection attempt: This input could delete database tables.", r"(?i)SELECT\s+\*": "Detected SQL Injection attempt: This input could retrieve sensitive data from the database.", r"(?i)INSERT\s+INTO": "Detected SQL Injection attempt: This input could insert data into the database.", r"(?i)DELETE\s+FROM": "Detected SQL Injection attempt: This input could delete data from the database.", r"(?i)UPDATE\s+\w+\s+SET": "Detected SQL Injection attempt: This input could update database records.", r"(?i)UNION\s+SELECT": "Detected SQL Injection attempt: This input could combine results from multiple queries.", r"<iframe.*?>": "Detected XSS attempt: This input could embed malicious content.", r"(?i)EXEC\s+": "Detected SQL Injection attempt: This input could execute arbitrary commands.", } def check_input(payload): for pattern, message in BLOCKED_PATTERNS.items(): if re.search(pattern, payload): return message, False return "Input received safely. Thank you!", True @app.route('/', methods=['GET', 'POST']) def index(): payload = request.form.get('input', '') message, is_safe = check_input(payload) if payload else (None, False) show_refresh = True # Always show the refresh button return render_template_string(render_template(message, payload, show_refresh, is_safe)) def render_template(message, payload, show_refresh, is_safe): message_color = "green" if is_safe else "red" if message else "black" refresh_button = '<form action="/" method="get"><input type="submit" value="Refresh"></form>' if show_refresh else '' return f''' <h1>Web Application Firewall</h1> <form method="post"> Input: <input type="text" name="input" value="{payload}"> <input type="submit" value="Submit"> </form> <h3 style="color: {message_color};">{message if message else ""}</h3> {refresh_button} ''' if __name__ == "__main__": app.run(port=5000)
-
Honeypot Script
import socket import logging import datetime # Configure logging logging.basicConfig(filename='honeypot.log', level=logging.INFO) def start_honeypot(port): # Create a socket honeypot_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) honeypot_socket.bind(('0.0.0.0', port)) honeypot_socket.listen(5) print(f"Honeypot listening on port {port}...") while True: conn, addr = honeypot_socket.accept() print(f"Connection from {addr} has been established!") log_access_attempt(addr) conn.close() def log_access_attempt(addr): timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') logging.info(f"{timestamp} - Unauthorized access attempt from {addr}") if __name__ == "__main__": port = 9999 start_honeypot(port)
-
Network Forensics Script
from scapy.all import rdpcap def analyze_pcap(file_path): packets = rdpcap(file_path) print(f"Total packets: {len(packets)}") for packet in packets: if packet.haslayer('IP'): print(f"Source: {packet['IP'].src}, Destination: {packet['IP'].dst}") pcap_file = input("Enter the path to the PCAP file: ") analyze_pcap(pcap_file)
-
Malware Analysis Script
import requests API_KEY = 'your_api_key_here' def scan_file(file_path): url = 'https://www.virustotal.com/vtapi/v2/file/report' params = { 'apikey': API_KEY, 'resource': file_path } response = requests.get(url, params=params) return response.json() file_hash = input("Enter the file hash to check: ") result = scan_file(file_hash) if result['response_code'] == 1: print("Scan results:") for scan in result['scans']: print(f"{scan}: {result['scans'][scan]['result']}") else: print("File not found in the database.")
-
Phishing Detection Tool
import requests def check_phishing(url): # Example API endpoint (replace with a real phishing database API) api_url = f"https://phishing-database.example.com/check?url={url}" response = requests.get(api_url) if response.status_code == 200: data = response.json() return data['is_phishing'] return None url = input("Enter the URL to check: ") result = check_phishing(url) if result is None: print("Error checking the URL.") elif result: print("Warning: This URL is potentially a phishing site!") else: print("This URL appears to be safe.")