伺服器上傳大量資料時,TP-Link WR882N 路由器容易當機導致斷網。為解決此問題,可撰寫 PHP 腳本定期檢測網路連線,若連續多次無法存取指定網站,則自動登入路由器管理介面執行重啟。本文分享完整實作代碼,包含 cURL 模擬登入、解析 WAN IP 與觸發重啟功能。
Authorization: Basic base64_encode("admin:admin")。/userRpm/StatusRpm.htm,以正則表達式從 JavaScript 變數 wanPara 中提取 IP。/userRpm/SysRebootRpm.htm?Reboot=...,參數為 URL 編碼的「重啟系統」中文字串。<?php
class TpLinkWR882NManager
{
private string $host;
private string $username;
private string $password;
private string $baseUrl;
private resource $curl;
public function __construct(string $host = '192.168.1.1', string $username = 'admin', string $password = 'admin')
{
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->baseUrl = "https://{$host}";
$this->curl = curl_init();
$this->setupCurlDefaults();
}
private function setupCurlDefaults(): void
{
curl_setopt_array($this->curl, [
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
]);
}
private function getAuthHeader(): string
{
return 'Authorization: Basic ' . base64_encode("{$this->username}:{$this->password}");
}
private function request(string $path, array $extraHeaders = []): string
{
$headers = array_merge([
"Host: {$this->host}",
"Referer: {$this->baseUrl}/",
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Cookie: {$this->getAuthHeader()}",
"Connection: Close",
], $extraHeaders);
curl_setopt($this->curl, CURLOPT_URL, "{$this->baseUrl}{$path}");
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($this->curl);
if ($response === false) {
throw new \RuntimeException("cURL 錯誤: " . curl_error($this->curl));
}
return $response;
}
public function getWanIp(): ?string
{
$content = $this->request('/userRpm/StatusRpm.htm');
// 解析 wanPara 陣列,格式:wanPara=new Array("...", "...", "IP", ...);
if (preg_match('/wanPara\s*=\s*new\s+Array\((.+?)\);/s', $content, $matches)) {
$data = array_map('trim', explode(',', $matches[1]));
if (isset($data[2])) {
return trim($data[2], '"\'');
}
}
return null;
}
public function reboot(): bool
{
// 重啟參數為 URL 編碼的中文「重啟系統」
$rebootParam = urlencode('重啟系統'); // 實際抓包可能不同,需確認
$this->request("/userRpm/SysRebootRpm.htm?Reboot={$rebootParam}");
return true;
}
public function __destruct()
{
if (is_resource($this->curl)) {
curl_close($this->curl);
}
}
}
// 使用範例
try {
$router = new TpLinkWR882NManager('192.168.1.1', 'admin', 'your_password');
$wanIp = $router->getWanIp();
echo "目前 WAN IP: " . ($wanIp ?? '取得失敗') . "\n";
// 實際重啟請謹慎執行
// $router->reboot();
// echo "重啟指令已發送\n";
} catch (\Throwable $e) {
echo "錯誤: {$e->getMessage()}\n";
}
?>
iconv 轉換。admin/admin 極不安全,務必修改為強密碼,並限制管理介面僅允許內網存取。cron 或系統排程器,結合網路檢測(如 ping 或 curl 指定網站)實作完整自動重啟機制。此架構可擴展至:
透過 PHP cURL 模擬瀏覽器行為,即可實現路由器的自動化管理。本文提供的類別封裝了認證、請求與解析邏輯,具備良好擴展性。實際部署時請務必在受控環境測試,避免誤觸發重啟造成服務中斷。