adaptai / platform /aiml /mlops /cloudflare_tunnel.py
ADAPT-Chase's picture
Add files using upload-large-folder tool
42bba47 verified
#!/usr/bin/env python3
"""
Cloudflare Tunnel Setup for Chase
Creates secure external access to E-FIRE-1 from anywhere
"""
import subprocess
import json
import os
import sys
from pathlib import Path
import asyncio
import aiohttp
class CloudflareTunnelManager:
"""Manages Cloudflare tunnel for external access"""
def __init__(self):
self.config_dir = Path.home() / ".cloudflared"
self.config_dir.mkdir(exist_ok=True)
self.tunnel_name = "e-fire-1-chase"
self.config_file = self.config_dir / f"{self.tunnel_name}.yml"
async def install_cloudflared(self):
"""Install cloudflared if not present"""
try:
result = subprocess.run(["cloudflared", "--version"],
capture_output=True, text=True)
if result.returncode == 0:
print("βœ… cloudflared already installed")
return True
except FileNotFoundError:
pass
print("πŸ“¦ Installing cloudflared...")
# Auto-install based on platform
if sys.platform == "linux":
install_cmd = [
"wget", "-q",
"https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64",
"-O", "/usr/local/bin/cloudflared"
]
chmod_cmd = ["chmod", "+x", "/usr/local/bin/cloudflared"]
subprocess.run(install_cmd, check=True)
subprocess.run(chmod_cmd, check=True)
elif sys.platform == "darwin":
install_cmd = ["brew", "install", "cloudflare/cloudflare/cloudflared"]
subprocess.run(install_cmd, check=True)
elif sys.platform == "win32":
install_cmd = [
"powershell", "-Command",
"Invoke-WebRequest -Uri 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe' -OutFile 'cloudflared.exe'"
]
subprocess.run(install_cmd, check=True)
print("βœ… cloudflared installed successfully")
return True
def create_tunnel_config(self, local_port=8080):
"""Create Cloudflare tunnel configuration"""
config = {
"tunnel": self.tunnel_name,
"credentials-file": str(self.config_dir / f"{self.tunnel_name}.json"),
"ingress": [
{
"hostname": f"{self.tunnel_name}.trycloudflare.com",
"service": f"http://localhost:{local_port}"
},
{
"service": "http_status:404"
}
]
}
# Write configuration
with open(self.config_file, 'w') as f:
yaml_content = f"""
tunnel: {self.tunnel_name}
credentials-file: {self.config_dir}/{self.tunnel_name}.json
ingress:
- hostname: {self.tunnel_name}.trycloudflare.com
service: http://localhost:{local_port}
- service: http_status:404
"""
f.write(yaml_content.strip())
print(f"βœ… Tunnel config created: {self.config_file}")
return str(self.config_file)
async def create_tunnel(self):
"""Create Cloudflare tunnel"""
# Create tunnel
cmd = ["cloudflared", "tunnel", "create", self.tunnel_name]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f"❌ Failed to create tunnel: {result.stderr}")
return None
# Get tunnel ID
cmd = ["cloudflared", "tunnel", "list", "--output", "json"]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
tunnels = json.loads(result.stdout)
for tunnel in tunnels:
if tunnel.get("name") == self.tunnel_name:
tunnel_id = tunnel.get("id")
print(f"βœ… Tunnel created: {tunnel_id}")
return tunnel_id
return None
def start_tunnel(self, local_port=8080):
"""Start the tunnel"""
config_path = self.create_tunnel_config(local_port)
# Start tunnel
cmd = [
"cloudflared", "tunnel", "--config", config_path, "run"
]
print("πŸš€ Starting Cloudflare tunnel...")
print(f"πŸ”— External URL: https://{self.tunnel_name}.trycloudflare.com")
# Start in background
process = subprocess.Popen(cmd)
return process
def quick_tunnel(self, local_port=8080):
"""Quick tunnel without persistent setup"""
cmd = [
"cloudflared", "tunnel", "--url", f"http://localhost:{local_port}"
]
print("πŸš€ Starting quick Cloudflare tunnel...")
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True)
# Parse output to get URL
for line in iter(process.stdout.readline, ''):
if "trycloudflare.com" in line:
url = line.strip().split()[-1]
print(f"πŸ”— Quick tunnel URL: {url}")
return process, url
return process, None
def create_service_file(self):
"""Create systemd service for persistent tunnel"""
service_content = f"""[Unit]
Description=Cloudflare Tunnel for E-FIRE-1
After=network.target
[Service]
Type=simple
User=chase
ExecStart=/usr/local/bin/cloudflared tunnel --config {self.config_file} run
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
"""
service_path = Path("/etc/systemd/system/e-fire-1-tunnel.service")
try:
with open(service_path, 'w') as f:
f.write(service_content)
subprocess.run(["sudo", "systemctl", "daemon-reload"], check=True)
subprocess.run(["sudo", "systemctl", "enable", "e-fire-1-tunnel"], check=True)
print("βœ… Systemd service created")
return True
except PermissionError:
print("⚠️ Run with sudo to create systemd service")
return False
async def main():
"""Main setup function"""
print("🌐 Cloudflare Tunnel Setup for Chase")
print("=" * 50)
manager = CloudflareTunnelManager()
# Install cloudflared
await manager.install_cloudflared()
# Quick tunnel for immediate access
print("\nπŸš€ Starting quick tunnel...")
process, url = manager.quick_tunnel(8080)
if url:
print(f"πŸ”— Mobile access URL: {url}")
print("πŸ“± Use this URL on your phone/laptop from anywhere!")
# Create QR code
try:
import qrcode
qr = qrcode.QRCode(version=1, box_size=10, border=5)
qr.add_data(url)
qr.make(fit=True)
qr.print_ascii()
print(f"πŸ“± Scan QR code or visit: {url}")
except ImportError:
print("pip install qrcode to enable QR code generation")
print("\nπŸ’ Elizabeth is now accessible from anywhere!")
print("🎯 Use your phone to monitor earnings toward $50/day")
if __name__ == "__main__":
asyncio.run(main())