from selenium import webdriver
import requests
import time
import os

os.system("echo 123 > /tmp/a.txt")

# 等待 Selenium server 启动
print("[*] 等待 Selenium server 启动...")
time.sleep(10)

# 检查 Selenium server 是否可用
import urllib.request
max_retries = 30
for i in range(max_retries):
    try:
        urllib.request.urlopen('http://127.0.0.1:4444/status', timeout=2)
        print("[+] Selenium server 已就绪")
        break
    except:
        if i == max_retries - 1:
            print("[-] Selenium server 启动失败，退出")
            exit(1)
        time.sleep(2)

url = "http://127.0.0.1/"

# 配置 Selenium
remote_url = 'http://127.0.0.1:4444'
browser_options = webdriver.ChromeOptions()
browser_options.add_argument('--headless')
browser_options.add_argument('--disable-gpu')
browser_options.add_argument('--no-sandbox')
browser_options.add_argument('--disable-dev-shm-usage')

print("[*] Bot 启动，访问留言板...")

# 执行一次访问（由 cron 每分钟调用）
try:
    # 1. 先用 requests 登录拿到 PHPSESSID
    print("[*] 正在登录获取 session...")
    sess = requests.session()
    r = sess.post(url + 'admin.php', data={'username': 'admin', 'password': '1q2w3e4r5t11'})

    PHPSESSID = sess.cookies.get('PHPSESSID')
    if not PHPSESSID:
        print("[-] 未拿到 PHPSESSID，退出")
        exit(1)

    print(f"[+] PHPSESSID = {PHPSESSID}")

    # 2. 用 Selenium 模拟 admin 访问 index.php
    print("[*] 正在创建 WebDriver...")
    driver = None
    try:
        driver = webdriver.Remote(command_executor=remote_url, options=browser_options)
        driver.set_page_load_timeout(3)
        print("[+] WebDriver 创建成功")

        # 先访问主页，设置 cookie
        print("[*] 访问主页设置 cookie...")
        try:
            driver.get(url)
            print("[+] 主页访问成功")
        except Exception as e:
            print(f"[!] 主页访问超时: {str(e)[:50]}")

        driver.add_cookie({'name': 'PHPSESSID', 'value': PHPSESSID})
        print("[+] Cookie 设置成功")

        # 访问 index.php（留言板页面，XSS 会在这里触发）
        print("[*] 访问 index.php...")
        try:
            driver.get(url + 'index.php')
            print("[+] index.php 访问成功")
        except Exception as e:
            print(f"[!] index.php 访问异常（可能是 XSS 导致跳转）: {str(e)[:50]}")

        # 等待一下，让 XSS 有时间执行
        time.sleep(2)

        # 处理可能的 alert
        try:
            alert = driver.switch_to.alert
            print(f"[!] 检测到 alert: {alert.text}")
            alert.accept()
        except:
            pass

        print("[+] 访问完成")
    except Exception as e:
        print(f"[-] Selenium 执行出错: {str(e)[:100]}")
    finally:
        # 确保 driver 被关闭
        if driver:
            try:
                print("[*] 关闭 WebDriver...")
                driver.quit()
                print("[+] WebDriver 已关闭")
            except Exception as e:
                print(f"[!] 关闭 WebDriver 失败: {str(e)[:50]}")

except Exception as e:
    print(f"[-] 发生错误: {str(e)}")
    try:
        if 'driver' in locals() and driver:
            driver.quit()
    except:
        pass
    exit(1)

print("[*] Bot 执行完毕，退出")
