Add captive_portal_with_ip_input.py

This commit is contained in:
Adil Sadqi 2024-12-23 21:02:55 +00:00
commit 6d825148a7
1 changed files with 122 additions and 0 deletions

View File

@ -0,0 +1,122 @@
import os
import subprocess
from http.server import SimpleHTTPRequestHandler, HTTPServer
def get_ip_range():
"""Automatically detect or manually specify the IP range."""
try:
# Automatically detect the IP range
result = subprocess.run(["ip", "route"], capture_output=True, text=True)
for line in result.stdout.splitlines():
if "src" in line:
ip_range = line.split()[0] # Extract the IP range (e.g., 192.168.0.0/24)
return ip_range
raise Exception("IP range detection failed.")
except Exception as e:
print(f"Error detecting IP range: {e}")
# Prompt the user to enter the IP range manually
return input("Enter your network IP range (e.g., 10.0.0.0/24): ")
def setup_iptables(server_ip, ip_range):
"""Configure iptables to redirect HTTP traffic to the warning page."""
os.system("sudo iptables -t nat -F")
os.system(f"sudo iptables -t nat -A PREROUTING -p tcp -s {ip_range} --dport 80 -j DNAT --to-destination {server_ip}:80")
os.system("sudo iptables -t nat -A POSTROUTING -j MASQUERADE")
def clear_iptables():
"""Clear iptables rules."""
os.system("sudo iptables -t nat -F")
def create_warning_page(message, content_type, content_path=None):
"""Create an HTML file with the warning message and optional content."""
with open("index.html", "w") as f:
f.write(f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Warning</title>
<style>
body {{
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}}
h1 {{
color: red;
}}
img {{
max-width: 100%;
height: auto;
}}
video {{
max-width: 100%;
height: auto;
}}
</style>
</head>
<body>
<h1>Attention!</h1>
<p>{message}</p>
""")
if content_type == "image":
f.write(f'<img src="{content_path}" alt="Warning Image">')
elif content_type == "video":
f.write(f'<video controls autoplay><source src="{content_path}" type="video/mp4">Your browser does not support the video tag.</video>')
f.write("""
</body>
</html>
""")
def start_server():
"""Start the HTTP server to serve the warning page."""
server_address = ('', 80)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print("Captive portal is active. Press Ctrl+C to stop.")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nStopping server...")
httpd.server_close()
if __name__ == "__main__":
try:
# Get the message from the user
message = input("Enter the warning message to display: ")
print("Choose the content type:")
print("1. Text only")
print("2. Image")
print("3. Video")
content_choice = input("Enter your choice (1/2/3): ")
content_type = None
content_path = None
if content_choice == "2":
content_type = "image"
content_path = input("Enter the path to the image file: ")
elif content_choice == "3":
content_type = "video"
content_path = input("Enter the path to the video file (MP4 format): ")
create_warning_page(message, content_type, content_path)
# Get the IP address of the Linux machine
server_ip = os.popen("hostname -I").read().strip().split()[0]
print(f"Server IP: {server_ip}")
# Get the IP range of the network
ip_range = get_ip_range()
print(f"Detected/Entered IP Range: {ip_range}")
# Set up iptables for redirection
setup_iptables(server_ip, ip_range)
# Start the HTTP server
start_server()
except Exception as e:
print(f"Error: {e}")
finally:
# Clear iptables rules when the program exits
clear_iptables()
print("Iptables rules cleared.")