实用技巧

腾讯云边缘安全加速平台 EO EdgeOne回源IP段获取工具

2026-08-04 19:24:48 一秒互联 7997 次阅读 EdgeOne,回源,防火墙
咨询相关开发

获取回源 IP 网段

登录 边缘安全加速平台 EO 控制台,在左侧菜单栏中,进入服务总览,单击网站安全加速内需配置的站点。

在站点详情页面,单击安全防护 > 源站防护。

在源站防护页面,单击立即使用,详细阅读 源站防护启用特别约定,确认可以接受“特别约定”中的内容后,单击确认启用。

单击源站防护状态的开关将其设置为启用,选择需要被防护的站点加速/四层代理资源,单击提交。

成功启用后,页面会显示当前回源 IP 列表(包含 IPv4和 IPv6地址段),可以复制此列表。

登录您的源站服务器所在的云平台或服务器本身,找到防火墙/安全组设置。添加入站规则,允许来自上述步骤5中获取的全部回源 IP 网段的流量访问您业务所需的端口(如80、443)。

.

宝塔代码php文件获取方式  支持宝塔定时查询。

<?php
declare(strict_types=1);
const CONFIG_FILE = __DIR__ . '/edgeone_config.php';
const DEFAULT_OUTPUT_FILE = __DIR__ . '/edgeone_origin_ips.txt';
const APP_TITLE = 'EdgeOne 回源 IP 获取工具';
date_default_timezone_set('Asia/Shanghai');
session_set_cookie_params([ 'httponly' => true, 'samesite' => 'Lax',
]);
session_start();
function page_html(string $value): string
{ return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function read_config(): array
{ if (!is_file(CONFIG_FILE)) { return []; } $rawContent = file_get_contents(CONFIG_FILE); if ($rawContent === false || trim($rawContent) === '') { return []; } $jsonContent = preg_replace('/^<\?php exit; \?>\s*/', '', $rawContent, 1); $config = json_decode((string) $jsonContent, true); if (!is_array($config)) { return []; } return $config;
}
function save_config(array $config): void
{ $jsonContent = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); if ($jsonContent === false) { throw new RuntimeException('配置内容生成失败,请检查填写内容'); } $saved = file_put_contents(CONFIG_FILE, '<?php exit; ?>' . PHP_EOL . $jsonContent, LOCK_EX); if ($saved === false) { throw new RuntimeException('配置文件保存失败,请检查当前目录是否有写入权限'); } @chmod(CONFIG_FILE, 0600);
}
function create_csrf_token(): string
{ if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(24)); } return (string) $_SESSION['csrf_token'];
}
function check_csrf_token(): void
{ $token = (string) ($_POST@['csrf_token'] ?? ''); if ($token === '' || empty($_SESSION['csrf_token']) || !hash_equals((string) $_SESSION['csrf_token'], $token)) { throw new RuntimeException('页面校验失败,请刷新页面后重试'); }
}
function is_logged_in(): bool
{ return !empty($_SESSION['edgeone_logged_in']);
}
function clean_text(string $value): string
{ return trim(str_replace(["\r", "\n", "\0"], '', $value));
}
function validate_api_host(string $host): string
{ $host = clean_text($host); $allowedHosts = [ 'teo.tencentcloudapi.com', 'teo.intl.tencentcloudapi.com', ]; if (!in_array($host, $allowedHosts, true)) { throw new RuntimeException('腾讯云接口地址不正确'); } return $host;
}
function validate_output_file(string $filePath): string
{ $filePath = trim($filePath); if ($filePath === '') { return DEFAULT_OUTPUT_FILE; } if (strpos($filePath, "\0") !== false) { throw new RuntimeException('保存路径不能包含非法字符'); } $folderPath = dirname($filePath); if ($folderPath === '' || $folderPath === '.') { throw new RuntimeException('保存路径请填写完整路径'); } if (!is_dir($folderPath)) { throw new RuntimeException('保存目录不存在:' . $folderPath); } if (!is_writable($folderPath)) { throw new RuntimeException('保存目录没有写入权限:' . $folderPath); } return $filePath;
}
function validate_cidr(string $cidr): bool
{ $cidr = trim($cidr); if ($cidr === '') { return false; } $parts = explode('/', $cidr, 2); $ip = $parts[0] ?? ''; $prefix = $parts[1] ?? null; $isIpv4 = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; $isIpv6 = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; if (!$isIpv4 && !$isIpv6) { return false; } if ($prefix === null) { return true; } if ($prefix === '' || !ctype_digit($prefix)) { return false; } $prefixNumber = (int) $prefix; if ($isIpv4) { return $prefixNumber >= 0 && $prefixNumber <= 32; } return $prefixNumber >= 0 && $prefixNumber <= 128;
}
function make_signature(string $secretKey, string $message): string
{ return hash_hmac('sha256', $message, $secretKey, true);
}
function summarize_origin_acl_info(array $originAclInfo): string
{ $status = (string) ($originAclInfo['Status'] ?? '未返回'); $l7Hosts = $originAclInfo['L7Hosts'] ?? []; $l4ProxyIds = $originAclInfo['L4ProxyIds'] ?? []; if (!is_array($l7Hosts)) { $l7Hosts = []; } if (!is_array($l4ProxyIds)) { $l4ProxyIds = []; } $l7Text = empty($l7Hosts) ? '无' : implode('、', array_slice(array_map('strval', $l7Hosts), 0, 10)); $l4Text = empty($l4ProxyIds) ? '无' : implode('、', array_slice(array_map('strval', $l4ProxyIds), 0, 10)); return '源站防护状态:' . $status . ';绑定七层域名:' . $l7Text . ';绑定四层代理:' . $l4Text;
}
function create_tencent_authorization(string $secretId, string $secretKey, string $payload, int $timestamp, string $host): string
{ $service = 'teo'; $action = 'DescribeOriginACL'; $algorithm = 'TC3-HMAC-SHA256'; $date = gmdate('Y-m-d', $timestamp); $canonicalHeaders = "content-type:application/json\nhost:" . $host . "\nx-tc-action:" . strtolower($action) . "\n"; $signedHeaders = 'content-type;host;x-tc-action'; $hashedPayload = hash('sha256', $payload); $canonicalRequest = implode("\n", [ 'POST', '/', '', $canonicalHeaders, $signedHeaders, $hashedPayload, ]); $credentialScope = $date . '/' . $service . '/tc3_request'; $stringToSign = implode("\n", [ $algorithm, (string) $timestamp, $credentialScope, hash('sha256', $canonicalRequest), ]); $secretDate = make_signature('TC3' . $secretKey, $date); $secretService = hash_hmac('sha256', $service, $secretDate, true); $secretSigning = hash_hmac('sha256', 'tc3_request', $secretService, true); $signature = hash_hmac('sha256', $stringToSign, $secretSigning); return $algorithm . ' Credential=' . $secretId . '/' . $credentialScope . ', SignedHeaders=' . $signedHeaders . ', Signature=' . $signature;
}
function http_post_json(string $url, array $headers, string $payload): array
{ if (function_exists('curl_init')) { $curl = curl_init($url); if ($curl === false) { throw new RuntimeException('无法初始化网络请求'); } $headerLines = []; foreach ($headers as $name => $value) { $headerLines[] = $name . ': ' . $value; } curl_setopt_array($curl, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPHEADER => $headerLines, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 25, ]); $body = curl_exec($curl); $statusCode = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); $curlError = curl_error($curl); curl_close($curl); if ($body === false) { throw new RuntimeException('网络请求失败:' . $curlError); } return [$statusCode, (string) $body]; } $headerText = ''; foreach ($headers as $name => $value) { $headerText .= $name . ': ' . $value . "\r\n"; } $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => $headerText, 'content' => $payload, 'timeout' => 25, 'ignore_errors' => true, ], ]); $body = file_get_contents($url, false, $context); if ($body === false) { throw new RuntimeException('网络请求失败,请检查 PHP 是否允许访问外部 HTTPS'); } $statusCode = 0; if (!empty($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $matches)) { $statusCode = (int) $matches[1]; } return [$statusCode, (string) $body];
}
function fetch_edgeone_origin_ips(array $config): array
{ $secretId = clean_text((string) ($config['secret_id'] ?? '')); $secretKey = clean_text((string) ($config['secret_key'] ?? '')); $zoneId = clean_text((string) ($config['zone_id'] ?? '')); $host = validate_api_host((string) ($config['api_host'] ?? 'teo.tencentcloudapi.com')); if ($secretId === '') { throw new RuntimeException('请先填写 SecretId'); } if ($secretKey === '') { throw new RuntimeException('请先填写 SecretKey'); } if ($zoneId === '') { throw new RuntimeException('请先填写 EdgeOne 站点 ID'); } $payload = json_encode(['ZoneId' => $zoneId], JSON_UNESCAPED_SLASHES); if ($payload === false) { throw new RuntimeException('请求内容生成失败'); } $timestamp = time(); $headers = [ 'Authorization' => create_tencent_authorization($secretId, $secretKey, $payload, $timestamp, $host), 'Content-Type' => 'application/json', 'Host' => $host, 'X-TC-Action' => 'DescribeOriginACL', 'X-TC-Timestamp' => (string) $timestamp, 'X-TC-Version' => '2022-09-01', ]; [$statusCode, $body] = http_post_json('https://' . $host, $headers, $payload); if ($statusCode < 200 || $statusCode >= 300) { throw new RuntimeException('腾讯云接口请求失败,状态码:' . $statusCode . ',返回:' . substr($body, 0, 500)); } $result = json_decode($body, true); if (!is_array($result)) { throw new RuntimeException('腾讯云接口返回格式不是 JSON'); } $response = $result['Response'] ?? null; if (!is_array($response)) { throw new RuntimeException('腾讯云接口返回内容缺少 Response'); } if (!empty($response['Error']) && is_array($response['Error'])) { $errorCode = (string) ($response['Error']['Code'] ?? 'Unknown'); $errorMessage = (string) ($response['Error']['Message'] ?? '未知错误'); throw new RuntimeException('腾讯云接口报错:' . $errorCode . ',' . $errorMessage); } $originAclInfo = $response['OriginACLInfo'] ?? []; if (!is_array($originAclInfo)) { throw new RuntimeException('没有获取到源站防护信息,请确认站点是否开启源站防护'); } $nextAcl = $originAclInfo['NextOriginACL'] ?? null; $currentAcl = $originAclInfo['CurrentOriginACL'] ?? null; $selectedAcl = is_array($nextAcl) && !empty($nextAcl) ? $nextAcl : $currentAcl; $sourceName = is_array($nextAcl) && !empty($nextAcl) ? 'NextOriginACL' : 'CurrentOriginACL'; if (!is_array($selectedAcl) || empty($selectedAcl)) { throw new RuntimeException('没有获取到回源 IP 网段。' . summarize_origin_acl_info($originAclInfo) . '。请到腾讯云 EdgeOne 控制台确认该站点已启用源站防护,并且已绑定需要防护的加速域名或四层代理实例。'); } $addresses = $selectedAcl['EntireAddresses'] ?? []; if (!is_array($addresses)) { throw new RuntimeException('回源 IP 网段格式异常。' . summarize_origin_acl_info($originAclInfo)); } $ipv4List = $addresses['IPv4'] ?? []; $ipv6List = $addresses['IPv6'] ?? []; if (!is_array($ipv4List)) { $ipv4List = []; } if (!is_array($ipv6List)) { $ipv6List = []; } $ipv4List = array_values(array_filter(array_map('trim', $ipv4List), 'validate_cidr')); $ipv6List = array_values(array_filter(array_map('trim', $ipv6List), 'validate_cidr')); if (empty($ipv4List) && empty($ipv6List)) { throw new RuntimeException('腾讯云返回了源站防护信息,但没有可用的 IPv4 或 IPv6 网段。' . summarize_origin_acl_info($originAclInfo) . '。如果状态不是 online,请先在 EdgeOne 控制台完成源站防护配置。'); } return [ 'source' => $sourceName, 'version' => (string) ($selectedAcl['Version'] ?? ''), 'updated_at' => date('Y-m-d H:i:s'), 'ipv4' => $ipv4List, 'ipv6' => $ipv6List, 'request_id' => (string) ($response['RequestId'] ?? ''), ];
}
function write_ip_file(array $data, string $outputFile, bool $includeIpv6): void
{ $outputFile = validate_output_file($outputFile); $lines = [ '# EdgeOne 回源 IP 网段', '# 技术支持 一秒互联公司 www.yimiaonet.com', '# 来源:' . $data['source'], '# 版本:' . $data['version'], '# 更新时间:' . $data['updated_at'], '', '[IPv4]', ]; foreach ($data['ipv4'] as $ip) { $lines[] = $ip; } if ($includeIpv6) { $lines[] = ''; $lines[] = '[IPv6]'; foreach ($data['ipv6'] as $ip) { $lines[] = $ip; } } $saved = file_put_contents($outputFile, implode(PHP_EOL, $lines) . PHP_EOL, LOCK_EX); if ($saved === false) { throw new RuntimeException('IP 文件保存失败,请检查路径权限:' . $outputFile); }
}
function build_plain_ip_text(array $data, bool $includeIpv6): string
{ $ips = $data['ipv4']; if ($includeIpv6) { $ips = array_merge($ips, $data['ipv6']); } return implode(PHP_EOL, $ips);
}
$config = read_config();
$message = '';
$error = '';
$fetchData = null;
$plainIpText = '';
$csrfToken = create_csrf_token();
try { $cronToken = clean_text((string) ($_GET@['cron'] ?? '')); if ($cronToken !== '') { header('Content-Type: text/plain; charset=utf-8'); if (empty($config['cron_token']) || !hash_equals((string) $config['cron_token'], $cronToken)) { http_response_code(403); echo '定时任务令牌错误'; exit; } $fetchData = fetch_edgeone_origin_ips($config); $includeIpv6 = !empty($config['include_ipv6']); write_ip_file($fetchData, (string) ($config['output_file'] ?? DEFAULT_OUTPUT_FILE), $includeIpv6); echo build_plain_ip_text($fetchData, $includeIpv6); exit; } if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') { check_csrf_token(); $action = (string) ($_POST@['action'] ?? ''); if ($action === 'login') { $password = (string) ($_POST@['password'] ?? ''); if (empty($config['password_hash']) || !password_verify($password, (string) $config['password_hash'])) { throw new RuntimeException('登录密码错误'); } $_SESSION['edgeone_logged_in'] = true; header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); exit; } if ($action === 'logout') { unset($_SESSION['edgeone_logged_in']); header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); exit; } if ($action === 'save_config') { $isFirstSetup = empty($config); if (!$isFirstSetup && !is_logged_in()) { throw new RuntimeException('请先登录后再修改配置'); } $secretId = clean_text((string) ($_POST@['secret_id'] ?? '')); $secretKeyInput = clean_text((string) ($_POST@['secret_key'] ?? '')); $zoneId = clean_text((string) ($_POST@['zone_id'] ?? '')); $apiHost = validate_api_host((string) ($_POST@['api_host'] ?? 'teo.tencentcloudapi.com')); $outputFile = validate_output_file((string) ($_POST@['output_file'] ?? DEFAULT_OUTPUT_FILE)); $includeIpv6 = !empty($_POST@['include_ipv6']); $newPassword = (string) ($_POST@['new_password'] ?? ''); if ($secretId === '') { throw new RuntimeException('SecretId 不能为空'); } if ($zoneId === '') { throw new RuntimeException('EdgeOne 站点 ID 不能为空'); } if ($isFirstSetup && $secretKeyInput === '') { throw new RuntimeException('首次配置必须填写 SecretKey'); } if ($isFirstSetup && strlen($newPassword) < 8) { throw new RuntimeException('首次配置请设置至少 8 位登录密码'); } if (!$isFirstSetup && $secretKeyInput === '') { $secretKeyInput = (string) ($config['secret_key'] ?? ''); } if ($secretKeyInput === '') { throw new RuntimeException('SecretKey 不能为空'); } if ($newPassword !== '' && strlen($newPassword) < 8) { throw new RuntimeException('新登录密码至少 8 位'); } $config = [ 'secret_id' => $secretId, 'secret_key' => $secretKeyInput, 'zone_id' => $zoneId, 'api_host' => $apiHost, 'output_file' => $outputFile, 'include_ipv6' => $includeIpv6, 'password_hash' => $newPassword !== '' ? password_hash($newPassword, PASSWORD_DEFAULT) : (string) ($config['password_hash'] ?? ''), 'cron_token' => (string) ($config['cron_token'] ?? bin2hex(random_bytes(24))), 'saved_at' => date('Y-m-d H:i:s'), ]; save_config($config); $_SESSION['edgeone_logged_in'] = true; $message = '配置已保存,之后不用重复填写密钥'; } if ($action === 'fetch_now') { if (!is_logged_in()) { throw new RuntimeException('请先登录'); } $fetchData = fetch_edgeone_origin_ips($config); $includeIpv6 = !empty($config['include_ipv6']); write_ip_file($fetchData, (string) ($config['output_file'] ?? DEFAULT_OUTPUT_FILE), $includeIpv6); $plainIpText = build_plain_ip_text($fetchData, $includeIpv6); $message = '获取成功,IP 列表已更新'; } }
} catch (Throwable $throwable) { $error = $throwable->getMessage();
}
$hasConfig = !empty($config);
$canViewConfig = !$hasConfig || is_logged_in();
$cronUrl = '';
if ($hasConfig && !empty($config['cron_token'])) { $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $hostName = (string) ($_SERVER['HTTP_HOST'] ?? '你的域名'); $path = strtok((string) ($_SERVER['REQUEST_URI'] ?? '/index.php'), '?'); $cronUrl = $scheme . '://' . $hostName . $path . '?cron=' . rawurlencode((string) $config['cron_token']);
}
?>
<!doctype html>
<html lang="zh-CN">
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php echo page_html(APP_TITLE); ?></title> <style> :root { --bg: #f4f7fb; --panel: #ffffff; --text: #172033; --muted: #667085; --line: #d9e1ef; --blue: #1f6feb; --blue-dark: #1659c7; --red: #c2410c; --green: #157347; } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--text); font-family: Arial, "Microsoft YaHei", sans-serif; font-size: 15px; line-height: 1.6; } .page { width: min(1040px, calc(100% - 32px)); margin: 32px auto; } .topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 18px; } h1 { margin: 0; font-size: 26px; line-height: 1.25; } .sub { margin: 6px 0 0; color: var(--muted); } .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 22px; margin-bottom: 18px; box-shadow: 0 14px 40px rgba(20, 30, 55, 0.08); } .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } label { display: block; margin-bottom: 6px; font-weight: 700; } input, select, textarea { width: 100%; border: 1px solid var(--line); border-radius: 6px; padding: 11px 12px; color: var(--text); background: #fff; font: inherit; outline: none; } textarea { min-height: 220px; resize: vertical; font-family: Consolas, "Courier New", monospace; } input:focus, select:focus, textarea:focus { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(31, 111, 235, 0.12); } .hint { margin-top: 6px; color: var(--muted); font-size: 13px; } .actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-top: 18px; } button, .button { border: 0; border-radius: 6px; background: var(--blue); color: #fff; padding: 10px 16px; font: inherit; font-weight: 700; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; min-height: 42px; } button:hover, .button:hover { background: var(--blue-dark); } .button-secondary { background: #eef3fb; color: var(--text); } .button-secondary:hover { background: #e1e9f6; } .notice { padding: 12px 14px; border-radius: 6px; margin-bottom: 18px; border: 1px solid transparent; } .notice-ok { color: var(--green); background: #ecfdf3; border-color: #bbf7d0; } .notice-error { color: var(--red); background: #fff7ed; border-color: #fed7aa; } .stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; } .stat { border: 1px solid var(--line); border-radius: 8px; padding: 14px; background: #fbfdff; } .stat strong { display: block; font-size: 22px; line-height: 1.2; } .stat span { color: var(--muted); font-size: 13px; } .checkline { display: flex; gap: 8px; align-items: center; margin-top: 8px; } .checkline input { width: 18px; height: 18px; } .footer { color: var(--muted); text-align: center; padding: 18px 0 8px; } .footer a { color: var(--blue); text-decoration: none; } @media (max-width: 760px) { .page { width: min(100% - 20px, 1040px); margin-top: 18px; } .topbar, .grid { grid-template-columns: 1fr; display: grid; } .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } } </style>
</head>
<body>
<main class="page"> <div class="topbar"> <div> <h1><?php echo page_html(APP_TITLE); ?></h1> <p class="sub">填写一次腾讯云配置,之后直接获取最新 EdgeOne 回源 IP。</p> </div> <?php if ($hasConfig && is_logged_in()) : ?> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="logout"> <button class="button-secondary" type="submit">退出登录</button> </form> <?php endif; ?> </div> <?php if ($message !== '') : ?> <div class="notice notice-ok"><?php echo page_html($message); ?></div> <?php endif; ?> <?php if ($error !== '') : ?> <div class="notice notice-error"><?php echo page_html($error); ?></div> <?php endif; ?> <?php if ($hasConfig && !is_logged_in()) : ?> <section class="panel"> <h2>登录管理页</h2> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="login"> <label for="password">登录密码</label> <input id="password" name="password" type="password" autocomplete="current-password" required> <div class="actions"> <button type="submit">登录</button> </div> </form> </section> <?php endif; ?> <?php if ($canViewConfig) : ?> <section class="panel"> <h2><?php echo $hasConfig ? '配置管理' : '首次配置'; ?></h2> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="save_config"> <div class="grid"> <div> <label for="secret_id">腾讯云 SecretId</label> <input id="secret_id" name="secret_id" value="<?php echo page_html((string) ($config['secret_id'] ?? '')); ?>" required> </div> <div> <label for="secret_key">腾讯云 SecretKey</label> <input id="secret_key" name="secret_key" type="password" autocomplete="new-password" placeholder="<?php echo $hasConfig ? '不修改请留空' : '首次配置必须填写'; ?>"> </div> <div> <label for="zone_id">EdgeOne 站点 ID</label> <input id="zone_id" name="zone_id" value="<?php echo page_html((string) ($config['zone_id'] ?? '')); ?>" placeholder="例如:zone-xxxx" required> </div> <div> <label for="api_host">腾讯云接口</label> <select id="api_host" name="api_host"> <?php $apiHost = (string) ($config['api_host'] ?? 'teo.tencentcloudapi.com'); ?> <option value="teo.tencentcloudapi.com" <?php echo $apiHost === 'teo.tencentcloudapi.com' ? 'selected' : ''; ?>>中国站 teo.tencentcloudapi.com</option> <option value="teo.intl.tencentcloudapi.com" <?php echo $apiHost === 'teo.intl.tencentcloudapi.com' ? 'selected' : ''; ?>>国际站 teo.intl.tencentcloudapi.com</option> </select> </div> <div> <label for="output_file">IP 列表保存路径</label> <input id="output_file" name="output_file" value="<?php echo page_html((string) ($config['output_file'] ?? DEFAULT_OUTPUT_FILE)); ?>" required> <div class="hint">这个文件只保存 IP,不保存密钥。</div> </div> <div> <label for="new_password"><?php echo $hasConfig ? '新登录密码' : '设置登录密码'; ?></label> <input id="new_password" name="new_password" type="password" autocomplete="new-password" placeholder="<?php echo $hasConfig ? '不修改请留空' : '至少 8 位'; ?>"> <div class="hint">用于保护这个管理页面。</div> </div> </div> <label class="checkline"> <input type="checkbox" name="include_ipv6" value="1" <?php echo !empty($config['include_ipv6']) ? 'checked' : ''; ?>> <span>同时保存 IPv6 网段</span> </label> <div class="actions"> <button type="submit">保存配置</button> <?php if ($hasConfig) : ?> <span class="hint">配置保存时间:<?php echo page_html((string) ($config['saved_at'] ?? '未知')); ?></span> <?php endif; ?> </div> </form> </section> <?php if ($hasConfig) : ?> <section class="panel"> <h2>获取 IP</h2> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="fetch_now"> <div class="actions"> <button type="submit">立即获取最新 IP</button> <?php if ($cronUrl !== '') : ?> <a class="button button-secondary" href="<?php echo page_html($cronUrl); ?>" target="_blank" rel="noopener">打开计划任务链接</a> <?php endif; ?> </div> </form> <?php if ($cronUrl !== '') : ?> <label for="cron_url" style="margin-top:16px;">宝塔计划任务 URL</label> <input id="cron_url" value="<?php echo page_html($cronUrl); ?>" readonly onclick="this.select()"> <div class="hint">宝塔计划任务可以用 URL 访问,定时执行后会自动更新保存路径里的 IP 文件。</div> <?php endif; ?> </section> <?php endif; ?> <?php endif; ?> <?php if (is_array($fetchData)) : ?> <section class="panel"> <h2>本次获取结果</h2> <div class="stats"> <div class="stat"> <strong><?php echo count($fetchData['ipv4']); ?></strong> <span>IPv4 数量</span> </div> <div class="stat"> <strong><?php echo count($fetchData['ipv6']); ?></strong> <span>IPv6 数量</span> </div> <div class="stat"> <strong><?php echo page_html((string) $fetchData['source']); ?></strong> <span>数据来源</span> </div> <div class="stat"> <strong><?php echo page_html((string) ($fetchData['version'] ?: '无')); ?></strong> <span>版本</span> </div> </div> <label for="ip_text">直接复制到防火墙白名单的 IP 网段</label> <textarea id="ip_text" readonly onclick="this.select()"><?php echo page_html($plainIpText); ?></textarea> <div class="hint">如果你的宝塔防火墙支持批量导入,可以直接复制上面的内容。</div> </section> <?php endif; ?> <footer class="footer"> 技术支持 <a href="https://www.yimiaonet.com" target="_blank" rel="noopener">一秒互联公司 www.yimiaonet.com</a> </footer>
</main>
</body>
</html>

升级版本2.0  支持查询到官方IP更新时 邮件通知管理员 即刻更新防火墙

<?php
declare(strict_types=1);
const CONFIG_FILE = __DIR__ . '/edgeone_config.php';
const SETUP_KEY_FILE = __DIR__ . '/edgeone_setup_key.php';
const SNAPSHOT_FILE = __DIR__ . '/edgeone_last_ips.php';
const DEFAULT_OUTPUT_FILE = __DIR__ . '/edgeone_origin_ips.txt';
const APP_TITLE = 'EdgeOne 回源 IP 获取工具';
date_default_timezone_set('Asia/Shanghai');
session_set_cookie_params([ 'httponly' => true, 'samesite' => 'Lax',
]);
session_start();
function page_html(string $value): string
{ return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function read_config(): array
{ if (!is_file(CONFIG_FILE)) { return []; } $rawContent = file_get_contents(CONFIG_FILE); if ($rawContent === false || trim($rawContent) === '') { return []; } $jsonContent = preg_replace('/^<\?php exit; \?>\s*/', '', $rawContent, 1); $config = json_decode((string) $jsonContent, true); if (!is_array($config)) { return []; } return $config;
}
function save_config(array $config): void
{ $jsonContent = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); if ($jsonContent === false) { throw new RuntimeException('配置内容生成失败,请检查填写内容'); } $saved = file_put_contents(CONFIG_FILE, '<?php exit; ?>' . PHP_EOL . $jsonContent, LOCK_EX); if ($saved === false) { throw new RuntimeException('配置文件保存失败,请检查当前目录是否有写入权限'); } @chmod(CONFIG_FILE, 0600);
}
function read_protected_file(string $filePath): string
{ if (!is_file($filePath)) { return ''; } $rawContent = file_get_contents($filePath); if ($rawContent === false) { return ''; } return trim((string) preg_replace('/^<\?php exit; \?>\s*/', '', $rawContent, 1));
}
function write_protected_file(string $filePath, string $content): void
{ $saved = file_put_contents($filePath, '<?php exit; ?>' . PHP_EOL . $content, LOCK_EX); if ($saved === false) { throw new RuntimeException('保护文件写入失败,请检查目录权限'); } @chmod($filePath, 0600);
}
function get_setup_key(): string
{ $setupKey = read_protected_file(SETUP_KEY_FILE); if ($setupKey !== '') { return $setupKey; } $setupKey = bin2hex(random_bytes(16)); write_protected_file(SETUP_KEY_FILE, $setupKey); return $setupKey;
}
function create_csrf_token(): string
{ if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(24)); } return (string) $_SESSION['csrf_token'];
}
function check_csrf_token(): void
{ $token = (string) ($_POST@['csrf_token'] ?? ''); if ($token === '' || empty($_SESSION['csrf_token']) || !hash_equals((string) $_SESSION['csrf_token'], $token)) { throw new RuntimeException('页面校验失败,请刷新页面后重试'); }
}
function is_logged_in(): bool
{ return !empty($_SESSION['edgeone_logged_in']);
}
function is_setup_unlocked(): bool
{ return !empty($_SESSION['edgeone_setup_unlocked']);
}
function clean_text(string $value): string
{ return trim(str_replace(["\r", "\n", "\0"], '', $value));
}
function validate_api_host(string $host): string
{ $host = clean_text($host); $allowedHosts = [ 'teo.tencentcloudapi.com', 'teo.intl.tencentcloudapi.com', ]; if (!in_array($host, $allowedHosts, true)) { throw new RuntimeException('腾讯云接口地址不正确'); } return $host;
}
function validate_output_file(string $filePath): string
{ $filePath = trim($filePath); if ($filePath === '') { return DEFAULT_OUTPUT_FILE; } if (strpos($filePath, "\0") !== false) { throw new RuntimeException('保存路径不能包含非法字符'); } $folderPath = dirname($filePath); if ($folderPath === '' || $folderPath === '.') { throw new RuntimeException('保存路径请填写完整路径'); } if (!is_dir($folderPath)) { throw new RuntimeException('保存目录不存在:' . $folderPath); } if (!is_writable($folderPath)) { throw new RuntimeException('保存目录没有写入权限:' . $folderPath); } return $filePath;
}
function validate_mail_address(string $email, string $fieldName): string
{ $email = clean_text($email); if ($email === '') { return ''; } if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) { throw new RuntimeException($fieldName . ' 格式不正确'); } return $email;
}
function validate_smtp_secure(string $secure): string
{ $secure = clean_text($secure); $allowed = ['ssl', 'tls', 'none']; if (!in_array($secure, $allowed, true)) { throw new RuntimeException('SMTP 加密方式不正确'); } return $secure;
}
function validate_smtp_port(string $port): int
{ $port = clean_text($port); if ($port === '') { return 465; } if (!ctype_digit($port)) { throw new RuntimeException('SMTP 端口必须是数字'); } $portNumber = (int) $port; if ($portNumber < 1 || $portNumber > 65535) { throw new RuntimeException('SMTP 端口范围必须是 1 到 65535'); } return $portNumber;
}
function validate_cidr(string $cidr): bool
{ $cidr = trim($cidr); if ($cidr === '') { return false; } $parts = explode('/', $cidr, 2); $ip = $parts[0] ?? ''; $prefix = $parts[1] ?? null; $isIpv4 = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; $isIpv6 = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; if (!$isIpv4 && !$isIpv6) { return false; } if ($prefix === null) { return true; } if ($prefix === '' || !ctype_digit($prefix)) { return false; } $prefixNumber = (int) $prefix; if ($isIpv4) { return $prefixNumber >= 0 && $prefixNumber <= 32; } return $prefixNumber >= 0 && $prefixNumber <= 128;
}
function make_signature(string $secretKey, string $message): string
{ return hash_hmac('sha256', $message, $secretKey, true);
}
function summarize_origin_acl_info(array $originAclInfo): string
{ $status = (string) ($originAclInfo['Status'] ?? '未返回'); $l7Hosts = $originAclInfo['L7Hosts'] ?? []; $l4ProxyIds = $originAclInfo['L4ProxyIds'] ?? []; if (!is_array($l7Hosts)) { $l7Hosts = []; } if (!is_array($l4ProxyIds)) { $l4ProxyIds = []; } $l7Text = empty($l7Hosts) ? '无' : implode('、', array_slice(array_map('strval', $l7Hosts), 0, 10)); $l4Text = empty($l4ProxyIds) ? '无' : implode('、', array_slice(array_map('strval', $l4ProxyIds), 0, 10)); return '源站防护状态:' . $status . ';绑定七层域名:' . $l7Text . ';绑定四层代理:' . $l4Text;
}
function create_tencent_authorization(string $secretId, string $secretKey, string $payload, int $timestamp, string $host): string
{ $service = 'teo'; $action = 'DescribeOriginACL'; $algorithm = 'TC3-HMAC-SHA256'; $date = gmdate('Y-m-d', $timestamp); $canonicalHeaders = "content-type:application/json\nhost:" . $host . "\nx-tc-action:" . strtolower($action) . "\n"; $signedHeaders = 'content-type;host;x-tc-action'; $hashedPayload = hash('sha256', $payload); $canonicalRequest = implode("\n", [ 'POST', '/', '', $canonicalHeaders, $signedHeaders, $hashedPayload, ]); $credentialScope = $date . '/' . $service . '/tc3_request'; $stringToSign = implode("\n", [ $algorithm, (string) $timestamp, $credentialScope, hash('sha256', $canonicalRequest), ]); $secretDate = make_signature('TC3' . $secretKey, $date); $secretService = hash_hmac('sha256', $service, $secretDate, true); $secretSigning = hash_hmac('sha256', 'tc3_request', $secretService, true); $signature = hash_hmac('sha256', $stringToSign, $secretSigning); return $algorithm . ' Credential=' . $secretId . '/' . $credentialScope . ', SignedHeaders=' . $signedHeaders . ', Signature=' . $signature;
}
function http_post_json(string $url, array $headers, string $payload): array
{ if (function_exists('curl_init')) { $curl = curl_init($url); if ($curl === false) { throw new RuntimeException('无法初始化网络请求'); } $headerLines = []; foreach ($headers as $name => $value) { $headerLines[] = $name . ': ' . $value; } curl_setopt_array($curl, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPHEADER => $headerLines, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 25, ]); $body = curl_exec($curl); $statusCode = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); $curlError = curl_error($curl); curl_close($curl); if ($body === false) { throw new RuntimeException('网络请求失败:' . $curlError); } return [$statusCode, (string) $body]; } $headerText = ''; foreach ($headers as $name => $value) { $headerText .= $name . ': ' . $value . "\r\n"; } $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => $headerText, 'content' => $payload, 'timeout' => 25, 'ignore_errors' => true, ], ]); $body = file_get_contents($url, false, $context); if ($body === false) { throw new RuntimeException('网络请求失败,请检查 PHP 是否允许访问外部 HTTPS'); } $statusCode = 0; if (!empty($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $matches)) { $statusCode = (int) $matches[1]; } return [$statusCode, (string) $body];
}
function fetch_edgeone_origin_ips(array $config): array
{ $secretId = clean_text((string) ($config['secret_id'] ?? '')); $secretKey = clean_text((string) ($config['secret_key'] ?? '')); $zoneId = clean_text((string) ($config['zone_id'] ?? '')); $host = validate_api_host((string) ($config['api_host'] ?? 'teo.tencentcloudapi.com')); if ($secretId === '') { throw new RuntimeException('请先填写 SecretId'); } if ($secretKey === '') { throw new RuntimeException('请先填写 SecretKey'); } if ($zoneId === '') { throw new RuntimeException('请先填写 EdgeOne 站点 ID'); } $payload = json_encode(['ZoneId' => $zoneId], JSON_UNESCAPED_SLASHES); if ($payload === false) { throw new RuntimeException('请求内容生成失败'); } $timestamp = time(); $headers = [ 'Authorization' => create_tencent_authorization($secretId, $secretKey, $payload, $timestamp, $host), 'Content-Type' => 'application/json', 'Host' => $host, 'X-TC-Action' => 'DescribeOriginACL', 'X-TC-Timestamp' => (string) $timestamp, 'X-TC-Version' => '2022-09-01', ]; [$statusCode, $body] = http_post_json('https://' . $host, $headers, $payload); if ($statusCode < 200 || $statusCode >= 300) { throw new RuntimeException('腾讯云接口请求失败,状态码:' . $statusCode . ',返回:' . substr($body, 0, 500)); } $result = json_decode($body, true); if (!is_array($result)) { throw new RuntimeException('腾讯云接口返回格式不是 JSON'); } $response = $result['Response'] ?? null; if (!is_array($response)) { throw new RuntimeException('腾讯云接口返回内容缺少 Response'); } if (!empty($response['Error']) && is_array($response['Error'])) { $errorCode = (string) ($response['Error']['Code'] ?? 'Unknown'); $errorMessage = (string) ($response['Error']['Message'] ?? '未知错误'); throw new RuntimeException('腾讯云接口报错:' . $errorCode . ',' . $errorMessage); } $originAclInfo = $response['OriginACLInfo'] ?? []; if (!is_array($originAclInfo)) { throw new RuntimeException('没有获取到源站防护信息,请确认站点是否开启源站防护'); } $nextAcl = $originAclInfo['NextOriginACL'] ?? null; $currentAcl = $originAclInfo['CurrentOriginACL'] ?? null; $selectedAcl = is_array($nextAcl) && !empty($nextAcl) ? $nextAcl : $currentAcl; $sourceName = is_array($nextAcl) && !empty($nextAcl) ? 'NextOriginACL' : 'CurrentOriginACL'; if (!is_array($selectedAcl) || empty($selectedAcl)) { throw new RuntimeException('没有获取到回源 IP 网段。' . summarize_origin_acl_info($originAclInfo) . '。请到腾讯云 EdgeOne 控制台确认该站点已启用源站防护,并且已绑定需要防护的加速域名或四层代理实例。'); } $addresses = $selectedAcl['EntireAddresses'] ?? []; if (!is_array($addresses)) { throw new RuntimeException('回源 IP 网段格式异常。' . summarize_origin_acl_info($originAclInfo)); } $ipv4List = $addresses['IPv4'] ?? []; $ipv6List = $addresses['IPv6'] ?? []; if (!is_array($ipv4List)) { $ipv4List = []; } if (!is_array($ipv6List)) { $ipv6List = []; } $ipv4List = array_values(array_filter(array_map('trim', $ipv4List), 'validate_cidr')); $ipv6List = array_values(array_filter(array_map('trim', $ipv6List), 'validate_cidr')); if (empty($ipv4List) && empty($ipv6List)) { throw new RuntimeException('腾讯云返回了源站防护信息,但没有可用的 IPv4 或 IPv6 网段。' . summarize_origin_acl_info($originAclInfo) . '。如果状态不是 online,请先在 EdgeOne 控制台完成源站防护配置。'); } return [ 'source' => $sourceName, 'version' => (string) ($selectedAcl['Version'] ?? ''), 'updated_at' => date('Y-m-d H:i:s'), 'ipv4' => $ipv4List, 'ipv6' => $ipv6List, 'request_id' => (string) ($response['RequestId'] ?? ''), ];
}
function write_ip_file(array $data, string $outputFile, bool $includeIpv6): void
{ $outputFile = validate_output_file($outputFile); $lines = [ '# EdgeOne 回源 IP 网段', '# 技术支持 一秒互联公司 www.yimiaonet.com', '# 来源:' . $data['source'], '# 版本:' . $data['version'], '# 更新时间:' . $data['updated_at'], '', '[IPv4]', ]; foreach ($data['ipv4'] as $ip) { $lines[] = $ip; } if ($includeIpv6) { $lines[] = ''; $lines[] = '[IPv6]'; foreach ($data['ipv6'] as $ip) { $lines[] = $ip; } } $saved = file_put_contents($outputFile, implode(PHP_EOL, $lines) . PHP_EOL, LOCK_EX); if ($saved === false) { throw new RuntimeException('IP 文件保存失败,请检查路径权限:' . $outputFile); }
}
function build_plain_ip_text(array $data, bool $includeIpv6): string
{ $ips = $data['ipv4']; if ($includeIpv6) { $ips = array_merge($ips, $data['ipv6']); } return implode(PHP_EOL, $ips);
}
function read_last_snapshot(): array
{ $content = read_protected_file(SNAPSHOT_FILE); if ($content === '') { return []; } $snapshot = json_decode($content, true); if (!is_array($snapshot)) { return []; } return $snapshot;
}
function save_last_snapshot(string $plainIpText, array $data): void
{ $snapshot = [ 'hash' => hash('sha256', $plainIpText), 'plain_ip_text' => $plainIpText, 'version' => (string) ($data['version'] ?? ''), 'source' => (string) ($data['source'] ?? ''), 'updated_at' => date('Y-m-d H:i:s'), ]; $jsonContent = json_encode($snapshot, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); if ($jsonContent === false) { throw new RuntimeException('IP 快照生成失败'); } write_protected_file(SNAPSHOT_FILE, $jsonContent);
}
function build_ip_change_message(array $oldSnapshot, string $newIpText, array $data): string
{ $oldIpText = (string) ($oldSnapshot['plain_ip_text'] ?? ''); $oldIps = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $oldIpText)))); $newIps = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $newIpText)))); $addedIps = array_values(array_diff($newIps, $oldIps)); $removedIps = array_values(array_diff($oldIps, $newIps)); $lines = [ 'EdgeOne 回源 IP 网段发生变化', '', '更新时间:' . date('Y-m-d H:i:s'), '数据来源:' . (string) ($data['source'] ?? ''), '版本:' . (string) ($data['version'] ?? ''), '', '新增 IP 网段:', empty($addedIps) ? '无' : implode(PHP_EOL, $addedIps), '', '移除 IP 网段:', empty($removedIps) ? '无' : implode(PHP_EOL, $removedIps), '', '当前完整 IP 网段:', $newIpText, '', '技术支持 一秒互联公司 www.yimiaonet.com', ]; return implode(PHP_EOL, $lines);
}
function smtp_read_response($socket): string
{ $response = ''; while (!feof($socket)) { $line = fgets($socket, 515); if ($line === false) { break; } $response .= $line; if (strlen($line) >= 4 && $line[3] === ' ') { break; } } return $response;
}
function smtp_command($socket, string $command, array $expectedCodes): string
{ if ($command !== '') { $written = fwrite($socket, $command . "\r\n"); if ($written === false) { throw new RuntimeException('SMTP 命令发送失败'); } } $response = smtp_read_response($socket); $code = substr($response, 0, 3); if (!in_array($code, $expectedCodes, true)) { throw new RuntimeException('SMTP 返回异常:' . trim($response)); } return $response;
}
function smtp_send_mail(array $config, string $subject, string $body): void
{ $host = clean_text((string) ($config['smtp_host'] ?? '')); $port = (int) ($config['smtp_port'] ?? 465); $secure = validate_smtp_secure((string) ($config['smtp_secure'] ?? 'ssl')); $username = clean_text((string) ($config['smtp_user'] ?? '')); $password = clean_text((string) ($config['smtp_pass'] ?? '')); $mailFrom = validate_mail_address((string) ($config['mail_from'] ?? ''), '发件邮箱'); $mailTo = validate_mail_address((string) ($config['mail_to'] ?? ''), '收件邮箱'); if ($host === '' || $mailFrom === '' || $mailTo === '') { throw new RuntimeException('邮件通知已开启,但 SMTP 地址、发件邮箱或收件邮箱未填写完整'); } if ($port < 1 || $port > 65535) { throw new RuntimeException('SMTP 端口不正确'); } $targetHost = $secure === 'ssl' ? 'ssl://' . $host : $host; $socket = fsockopen($targetHost, $port, $errorCode, $errorMessage, 20); if (!$socket) { throw new RuntimeException('连接 SMTP 失败:' . $errorCode . ',' . $errorMessage); } stream_set_timeout($socket, 20); try { smtp_command($socket, '', ['220']); smtp_command($socket, 'EHLO ' . ($_SERVER['SERVER_NAME'] ?? 'localhost'), ['250']); if ($secure === 'tls') { smtp_command($socket, 'STARTTLS', ['220']); $cryptoOk = stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if ($cryptoOk !== true) { throw new RuntimeException('SMTP TLS 加密开启失败'); } smtp_command($socket, 'EHLO ' . ($_SERVER['SERVER_NAME'] ?? 'localhost'), ['250']); } if ($username !== '' || $password !== '') { if ($username === '' || $password === '') { throw new RuntimeException('SMTP 账号和密码必须同时填写'); } smtp_command($socket, 'AUTH LOGIN', ['334']); smtp_command($socket, base64_encode($username), ['334']); smtp_command($socket, base64_encode($password), ['235']); } smtp_command($socket, 'MAIL FROM:<' . $mailFrom . '>', ['250']); smtp_command($socket, 'RCPT TO:<' . $mailTo . '>', ['250', '251']); smtp_command($socket, 'DATA', ['354']); $encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?='; $messageLines = [ 'From: ' . $mailFrom, 'To: ' . $mailTo, 'Subject: ' . $encodedSubject, 'MIME-Version: 1.0', 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: base64', '', chunk_split(base64_encode($body)), ]; $message = implode("\r\n", $messageLines); $message = preg_replace('/^\./m', '..', $message); smtp_command($socket, $message . "\r\n.", ['250']); smtp_command($socket, 'QUIT', ['221']); } finally { fclose($socket); }
}
function notify_if_ips_changed(array $config, array $fetchData, string $plainIpText): string
{ $oldSnapshot = read_last_snapshot(); $newHash = hash('sha256', $plainIpText); $oldHash = (string) ($oldSnapshot['hash'] ?? ''); save_last_snapshot($plainIpText, $fetchData); if ($oldHash === '') { return '首次建立 IP 基准,未发送变化通知'; } if (hash_equals($oldHash, $newHash)) { return 'IP 未变化,未发送邮件'; } if (empty($config['mail_notify_enabled'])) { return 'IP 已变化,但邮件通知未开启'; } $subject = 'EdgeOne 回源 IP 已变化'; $body = build_ip_change_message($oldSnapshot, $plainIpText, $fetchData); smtp_send_mail($config, $subject, $body); return 'IP 已变化,邮件通知已发送';
}
$config = read_config();
$message = '';
$error = '';
$fetchData = null;
$plainIpText = '';
$notifyMessage = '';
$csrfToken = create_csrf_token();
$setupKey = empty($config) ? get_setup_key() : '';
try { $cronToken = clean_text((string) ($_GET@['cron'] ?? '')); if ($cronToken !== '') { header('Content-Type: text/plain; charset=utf-8'); if (empty($config['cron_token']) || !hash_equals((string) $config['cron_token'], $cronToken)) { http_response_code(403); echo '定时任务令牌错误'; exit; } $fetchData = fetch_edgeone_origin_ips($config); $includeIpv6 = !empty($config['include_ipv6']); write_ip_file($fetchData, (string) ($config['output_file'] ?? DEFAULT_OUTPUT_FILE), $includeIpv6); $plainIpText = build_plain_ip_text($fetchData, $includeIpv6); $notifyMessage = notify_if_ips_changed($config, $fetchData, $plainIpText); echo $plainIpText . PHP_EOL . PHP_EOL . '# ' . $notifyMessage; exit; } if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') { check_csrf_token(); $action = (string) ($_POST@['action'] ?? ''); if ($action === 'unlock_setup') { if (!empty($config)) { throw new RuntimeException('配置已存在,请直接登录'); } $inputSetupKey = clean_text((string) ($_POST@['setup_key'] ?? '')); if ($inputSetupKey === '' || !hash_equals($setupKey, $inputSetupKey)) { throw new RuntimeException('安装保护码错误'); } $_SESSION['edgeone_setup_unlocked'] = true; header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); exit; } if ($action === 'login') { $password = (string) ($_POST@['password'] ?? ''); if (empty($config['password_hash']) || !password_verify($password, (string) $config['password_hash'])) { throw new RuntimeException('登录密码错误'); } $_SESSION['edgeone_logged_in'] = true; header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); exit; } if ($action === 'logout') { unset($_SESSION['edgeone_logged_in']); unset($_SESSION['edgeone_setup_unlocked']); header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?')); exit; } if ($action === 'save_config') { $isFirstSetup = empty($config); if ($isFirstSetup && !is_setup_unlocked()) { throw new RuntimeException('请先输入安装保护码'); } if (!$isFirstSetup && !is_logged_in()) { throw new RuntimeException('请先登录后再修改配置'); } $secretId = clean_text((string) ($_POST@['secret_id'] ?? '')); $secretKeyInput = clean_text((string) ($_POST@['secret_key'] ?? '')); $zoneId = clean_text((string) ($_POST@['zone_id'] ?? '')); $apiHost = validate_api_host((string) ($_POST@['api_host'] ?? 'teo.tencentcloudapi.com')); $outputFile = validate_output_file((string) ($_POST@['output_file'] ?? DEFAULT_OUTPUT_FILE)); $includeIpv6 = !empty($_POST@['include_ipv6']); $newPassword = (string) ($_POST@['new_password'] ?? ''); $mailNotifyEnabled = !empty($_POST@['mail_notify_enabled']); $mailTo = validate_mail_address((string) ($_POST@['mail_to'] ?? ''), '收件邮箱'); $mailFrom = validate_mail_address((string) ($_POST@['mail_from'] ?? ''), '发件邮箱'); $smtpHost = clean_text((string) ($_POST@['smtp_host'] ?? '')); $smtpPort = validate_smtp_port((string) ($_POST@['smtp_port'] ?? '465')); $smtpSecure = validate_smtp_secure((string) ($_POST@['smtp_secure'] ?? 'ssl')); $smtpUser = clean_text((string) ($_POST@['smtp_user'] ?? '')); $smtpPassInput = clean_text((string) ($_POST@['smtp_pass'] ?? '')); if ($secretId === '') { throw new RuntimeException('SecretId 不能为空'); } if ($zoneId === '') { throw new RuntimeException('EdgeOne 站点 ID 不能为空'); } if ($isFirstSetup && $secretKeyInput === '') { throw new RuntimeException('首次配置必须填写 SecretKey'); } if ($isFirstSetup && strlen($newPassword) < 8) { throw new RuntimeException('首次配置请设置至少 8 位登录密码'); } if (!$isFirstSetup && $secretKeyInput === '') { $secretKeyInput = (string) ($config['secret_key'] ?? ''); } if ($secretKeyInput === '') { throw new RuntimeException('SecretKey 不能为空'); } if ($newPassword !== '' && strlen($newPassword) < 8) { throw new RuntimeException('新登录密码至少 8 位'); } if ($mailNotifyEnabled) { if ($mailTo === '' || $mailFrom === '' || $smtpHost === '') { throw new RuntimeException('开启邮件通知后,SMTP 地址、发件邮箱、收件邮箱必须填写'); } } if (!$isFirstSetup && $smtpPassInput === '') { $smtpPassInput = (string) ($config['smtp_pass'] ?? ''); } $config = [ 'secret_id' => $secretId, 'secret_key' => $secretKeyInput, 'zone_id' => $zoneId, 'api_host' => $apiHost, 'output_file' => $outputFile, 'include_ipv6' => $includeIpv6, 'mail_notify_enabled' => $mailNotifyEnabled, 'mail_to' => $mailTo, 'mail_from' => $mailFrom, 'smtp_host' => $smtpHost, 'smtp_port' => $smtpPort, 'smtp_secure' => $smtpSecure, 'smtp_user' => $smtpUser, 'smtp_pass' => $smtpPassInput, 'password_hash' => $newPassword !== '' ? password_hash($newPassword, PASSWORD_DEFAULT) : (string) ($config['password_hash'] ?? ''), 'cron_token' => (string) ($config['cron_token'] ?? bin2hex(random_bytes(24))), 'saved_at' => date('Y-m-d H:i:s'), ]; save_config($config); $_SESSION['edgeone_logged_in'] = true; $message = '配置已保存,之后不用重复填写密钥'; } if ($action === 'fetch_now') { if (!is_logged_in()) { throw new RuntimeException('请先登录'); } $fetchData = fetch_edgeone_origin_ips($config); $includeIpv6 = !empty($config['include_ipv6']); write_ip_file($fetchData, (string) ($config['output_file'] ?? DEFAULT_OUTPUT_FILE), $includeIpv6); $plainIpText = build_plain_ip_text($fetchData, $includeIpv6); $notifyMessage = notify_if_ips_changed($config, $fetchData, $plainIpText); $message = '获取成功,IP 列表已更新。' . $notifyMessage; } if ($action === 'test_mail') { if (!is_logged_in()) { throw new RuntimeException('请先登录'); } $body = implode(PHP_EOL, [ '这是一封 EdgeOne 回源 IP 获取工具的测试邮件。', '', '如果你收到这封邮件,说明 SMTP 配置可以正常发送。', '', '发送时间:' . date('Y-m-d H:i:s'), '', '技术支持 一秒互联公司 www.yimiaonet.com', ]); smtp_send_mail($config, 'EdgeOne 邮件通知测试', $body); $message = '测试邮件已发送,请检查收件邮箱'; } }
} catch (Throwable $throwable) { $error = $throwable->getMessage();
}
$hasConfig = !empty($config);
$canViewConfig = (!$hasConfig && is_setup_unlocked()) || ($hasConfig && is_logged_in());
$cronUrl = '';
if ($hasConfig && !empty($config['cron_token'])) { $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $hostName = (string) ($_SERVER['HTTP_HOST'] ?? '你的域名'); $path = strtok((string) ($_SERVER['REQUEST_URI'] ?? '/index.php'), '?'); $cronUrl = $scheme . '://' . $hostName . $path . '?cron=' . rawurlencode((string) $config['cron_token']);
}
?>
<!doctype html>
<html lang="zh-CN">
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php echo page_html(APP_TITLE); ?></title> <style> :root { --bg: #f4f7fb; --panel: #ffffff; --text: #172033; --muted: #667085; --line: #d9e1ef; --blue: #1f6feb; --blue-dark: #1659c7; --red: #c2410c; --green: #157347; } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--text); font-family: Arial, "Microsoft YaHei", sans-serif; font-size: 15px; line-height: 1.6; } .page { width: min(1040px, calc(100% - 32px)); margin: 32px auto; } .topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 18px; } h1 { margin: 0; font-size: 26px; line-height: 1.25; } .sub { margin: 6px 0 0; color: var(--muted); } .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 22px; margin-bottom: 18px; box-shadow: 0 14px 40px rgba(20, 30, 55, 0.08); } .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } label { display: block; margin-bottom: 6px; font-weight: 700; } input, select, textarea { width: 100%; border: 1px solid var(--line); border-radius: 6px; padding: 11px 12px; color: var(--text); background: #fff; font: inherit; outline: none; } textarea { min-height: 220px; resize: vertical; font-family: Consolas, "Courier New", monospace; } input:focus, select:focus, textarea:focus { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(31, 111, 235, 0.12); } .hint { margin-top: 6px; color: var(--muted); font-size: 13px; } .section-title { margin: 22px 0 12px; padding-top: 18px; border-top: 1px solid var(--line); font-size: 18px; } .actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-top: 18px; } button, .button { border: 0; border-radius: 6px; background: var(--blue); color: #fff; padding: 10px 16px; font: inherit; font-weight: 700; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; min-height: 42px; } button:hover, .button:hover { background: var(--blue-dark); } .button-secondary { background: #eef3fb; color: var(--text); } .button-secondary:hover { background: #e1e9f6; } .notice { padding: 12px 14px; border-radius: 6px; margin-bottom: 18px; border: 1px solid transparent; } .notice-ok { color: var(--green); background: #ecfdf3; border-color: #bbf7d0; } .notice-error { color: var(--red); background: #fff7ed; border-color: #fed7aa; } .stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; } .stat { border: 1px solid var(--line); border-radius: 8px; padding: 14px; background: #fbfdff; } .stat strong { display: block; font-size: 22px; line-height: 1.2; } .stat span { color: var(--muted); font-size: 13px; } .checkline { display: flex; gap: 8px; align-items: center; margin-top: 8px; } .checkline input { width: 18px; height: 18px; } .footer { color: var(--muted); text-align: center; padding: 18px 0 8px; } .footer a { color: var(--blue); text-decoration: none; } @media (max-width: 760px) { .page { width: min(100% - 20px, 1040px); margin-top: 18px; } .topbar, .grid { grid-template-columns: 1fr; display: grid; } .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } } </style>
</head>
<body>
<main class="page"> <div class="topbar"> <div> <h1><?php echo page_html(APP_TITLE); ?></h1> <p class="sub">填写一次腾讯云配置,之后直接获取最新 EdgeOne 回源 IP。</p> </div> <?php if ($hasConfig && is_logged_in()) : ?> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="logout"> <button class="button-secondary" type="submit">退出登录</button> </form> <?php endif; ?> </div> <?php if ($message !== '') : ?> <div class="notice notice-ok"><?php echo page_html($message); ?></div> <?php endif; ?> <?php if ($error !== '') : ?> <div class="notice notice-error"><?php echo page_html($error); ?></div> <?php endif; ?> <?php if (!$hasConfig && !is_setup_unlocked()) : ?> <section class="panel"> <h2>首次安装保护</h2> <p class="sub">为了避免别人打开页面后抢先配置,请先输入服务器本地生成的安装保护码。</p> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="unlock_setup"> <label for="setup_key">安装保护码</label> <input id="setup_key" name="setup_key" type="password" autocomplete="off" required> <div class="hint">保护码文件位置:<?php echo page_html(SETUP_KEY_FILE); ?>,用宝塔文件管理打开即可查看。</div> <div class="actions"> <button type="submit">进入首次配置</button> </div> </form> </section> <?php endif; ?> <?php if ($hasConfig && !is_logged_in()) : ?> <section class="panel"> <h2>登录管理页</h2> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="login"> <label for="password">登录密码</label> <input id="password" name="password" type="password" autocomplete="current-password" required> <div class="actions"> <button type="submit">登录</button> </div> </form> </section> <?php endif; ?> <?php if ($canViewConfig) : ?> <section class="panel"> <h2><?php echo $hasConfig ? '配置管理' : '首次配置'; ?></h2> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="save_config"> <div class="grid"> <div> <label for="secret_id">腾讯云 SecretId</label> <input id="secret_id" name="secret_id" value="<?php echo page_html((string) ($config['secret_id'] ?? '')); ?>" required> </div> <div> <label for="secret_key">腾讯云 SecretKey</label> <input id="secret_key" name="secret_key" type="password" autocomplete="new-password" placeholder="<?php echo $hasConfig ? '不修改请留空' : '首次配置必须填写'; ?>"> </div> <div> <label for="zone_id">EdgeOne 站点 ID</label> <input id="zone_id" name="zone_id" value="<?php echo page_html((string) ($config['zone_id'] ?? '')); ?>" placeholder="例如:zone-xxxx" required> </div> <div> <label for="api_host">腾讯云接口</label> <select id="api_host" name="api_host"> <?php $apiHost = (string) ($config['api_host'] ?? 'teo.tencentcloudapi.com'); ?> <option value="teo.tencentcloudapi.com" <?php echo $apiHost === 'teo.tencentcloudapi.com' ? 'selected' : ''; ?>>中国站 teo.tencentcloudapi.com</option> <option value="teo.intl.tencentcloudapi.com" <?php echo $apiHost === 'teo.intl.tencentcloudapi.com' ? 'selected' : ''; ?>>国际站 teo.intl.tencentcloudapi.com</option> </select> </div> <div> <label for="output_file">IP 列表保存路径</label> <input id="output_file" name="output_file" value="<?php echo page_html((string) ($config['output_file'] ?? DEFAULT_OUTPUT_FILE)); ?>" required> <div class="hint">这个文件只保存 IP,不保存密钥。</div> </div> <div> <label for="new_password"><?php echo $hasConfig ? '新登录密码' : '设置登录密码'; ?></label> <input id="new_password" name="new_password" type="password" autocomplete="new-password" placeholder="<?php echo $hasConfig ? '不修改请留空' : '至少 8 位'; ?>"> <div class="hint">用于保护这个管理页面。</div> </div> </div> <label class="checkline"> <input type="checkbox" name="include_ipv6" value="1" <?php echo !empty($config['include_ipv6']) ? 'checked' : ''; ?>> <span>同时保存 IPv6 网段</span> </label> <h3 class="section-title">邮件通知</h3> <label class="checkline"> <input type="checkbox" name="mail_notify_enabled" value="1" <?php echo !empty($config['mail_notify_enabled']) ? 'checked' : ''; ?>> <span>IP 网段有变化时发送邮件通知</span> </label> <div class="grid"> <div> <label for="mail_to">收件邮箱</label> <input id="mail_to" name="mail_to" type="email" value="<?php echo page_html((string) ($config['mail_to'] ?? '')); ?>" placeholder="例如:admin@example.com"> </div> <div> <label for="mail_from">发件邮箱</label> <input id="mail_from" name="mail_from" type="email" value="<?php echo page_html((string) ($config['mail_from'] ?? '')); ?>" placeholder="通常填写 SMTP 邮箱"> </div> <div> <label for="smtp_host">SMTP 地址</label> <input id="smtp_host" name="smtp_host" value="<?php echo page_html((string) ($config['smtp_host'] ?? '')); ?>" placeholder="例如:smtp.qq.com"> </div> <div> <label for="smtp_port">SMTP 端口</label> <input id="smtp_port" name="smtp_port" value="<?php echo page_html((string) ($config['smtp_port'] ?? '465')); ?>" inputmode="numeric"> </div> <div> <label for="smtp_secure">SMTP 加密方式</label> <?php $smtpSecure = (string) ($config['smtp_secure'] ?? 'ssl'); ?> <select id="smtp_secure" name="smtp_secure"> <option value="ssl" <?php echo $smtpSecure === 'ssl' ? 'selected' : ''; ?>>SSL,常用端口 465</option> <option value="tls" <?php echo $smtpSecure === 'tls' ? 'selected' : ''; ?>>TLS,常用端口 587</option> <option value="none" <?php echo $smtpSecure === 'none' ? 'selected' : ''; ?>>不加密,少数内网邮箱使用</option> </select> </div> <div> <label for="smtp_user">SMTP 账号</label> <input id="smtp_user" name="smtp_user" value="<?php echo page_html((string) ($config['smtp_user'] ?? '')); ?>" placeholder="通常是完整邮箱"> </div> <div> <label for="smtp_pass">SMTP 密码或授权码</label> <input id="smtp_pass" name="smtp_pass" type="password" autocomplete="new-password" placeholder="<?php echo $hasConfig ? '不修改请留空' : '邮箱服务商提供的授权码'; ?>"> <div class="hint">QQ 邮箱、企业邮箱等一般要填“授权码”,不是登录密码。</div> </div> </div> <div class="actions"> <button type="submit">保存配置</button> <?php if ($hasConfig) : ?> <span class="hint">配置保存时间:<?php echo page_html((string) ($config['saved_at'] ?? '未知')); ?></span> <?php endif; ?> </div> </form> </section> <?php if ($hasConfig) : ?> <section class="panel"> <h2>获取 IP</h2> <form method="post"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="fetch_now"> <div class="actions"> <button type="submit">立即获取最新 IP</button> <?php if ($cronUrl !== '') : ?> <a class="button button-secondary" href="<?php echo page_html($cronUrl); ?>" target="_blank" rel="noopener">打开计划任务链接</a> <?php endif; ?> </div> </form> <form method="post" class="actions"> <input type="hidden" name="csrf_token" value="<?php echo page_html($csrfToken); ?>"> <input type="hidden" name="action" value="test_mail"> <button class="button-secondary" type="submit">发送测试邮件</button> </form> <?php if ($cronUrl !== '') : ?> <label for="cron_url" style="margin-top:16px;">宝塔计划任务 URL</label> <input id="cron_url" value="<?php echo page_html($cronUrl); ?>" readonly onclick="this.select()"> <div class="hint">宝塔计划任务可以用 URL 访问,定时执行后会自动更新保存路径里的 IP 文件。</div> <?php endif; ?> </section> <?php endif; ?> <?php endif; ?> <?php if (is_array($fetchData)) : ?> <section class="panel"> <h2>本次获取结果</h2> <div class="stats"> <div class="stat"> <strong><?php echo count($fetchData['ipv4']); ?></strong> <span>IPv4 数量</span> </div> <div class="stat"> <strong><?php echo count($fetchData['ipv6']); ?></strong> <span>IPv6 数量</span> </div> <div class="stat"> <strong><?php echo page_html((string) $fetchData['source']); ?></strong> <span>数据来源</span> </div> <div class="stat"> <strong><?php echo page_html((string) ($fetchData['version'] ?: '无')); ?></strong> <span>版本</span> </div> </div> <label for="ip_text">直接复制到防火墙白名单的 IP 网段</label> <textarea id="ip_text" readonly onclick="this.select()"><?php echo page_html($plainIpText); ?></textarea> <div class="hint">如果你的宝塔防火墙支持批量导入,可以直接复制上面的内容。</div> </section> <?php endif; ?> <footer class="footer"> 技术支持 <a href="https://www.yimiaonet.com" target="_blank" rel="noopener">一秒互联公司 www.yimiaonet.com</a> </footer>
</main>
</body>
</html>

 

最后更新:2026-08-04 19:24:48
原文地址:https://www.yimiaonet.com/beijing/345.html
上一篇 2026年100款AI工具深度详解|每款用途、落地效果、适配人群全拆解(实操落地版)
下一篇 Skill 是什么?怎么创建?怎么使用?一文详解
电话咨询

开源产品中心

免费下载 · 开源可商用 · 社区长期维护

ERP进销存系统 V6

全开源无加密,企业自用无忧

免费下载

ERP进销存系统 V7

全开源无加密,企业自用无忧

免费使用

所有开源产品均可无限制商用,定制开发请联系专属客服

开源产品
获取报价
在线客服
加入社群