安全警示:Telnet 明文傳輸,**生產環境務必改用 SSH (phpseclib/ssh2)**。本類僅供受控內網、教學、 legacy 維護使用。
<?php
/**
* PHP Telnet 客戶端
* 支援:協議握手 (IAC DO/DONT/WILL/WONT)、登錄認證、命令執行、輸出捕獲、超時控制
*/
class TelnetClient
{
private ?resource $socket = null;
private string $host;
private int $port = 23;
private float $timeout = 10.0; // 連接/讀寫超時 (秒)
private float $cmdDelay = 0.2; // 命令間延遲 (秒)
private string $prompt = ''; // 命令提示符正則
private array $options = []; // 協議選項狀態
private string $buffer = ''; // 讀取緩衝
// Telnet 協議常量
private const IAC = 255; // Interpret As Command
private const DONT = 254;
private const DO = 253;
private const WONT = 252;
private const WILL = 251;
private const SB = 250; // Subnegotiation Begin
private const SE = 240; // Subnegotiation End
// 常見選項
private const OPT_ECHO = 1;
private const OPT_SUPPRESS_GA = 3;
private const OPT_TERMINAL_TYPE = 24;
private const OPT_WINDOW_SIZE = 31;
private const OPT_LINEMODE = 34;
public function __construct(string $host, int $port = 23, float $timeout = 10.0)
{
$this->host = $host;
$this->port = $port;
$this->timeout = $timeout;
}
/** 設置命令提示符正則 (用於判斷命令結束) */
public function setPrompt(string $regex): self
{
$this->prompt = $regex;
return $this;
}
/** 設置命令發送間隔 */
public function setCmdDelay(float $seconds): self
{
$this->cmdDelay = $seconds;
return $this;
}
/** 連接並完成 Telnet 協議握手 */
public function connect(): bool
{
$this->socket = @stream_socket_client(
"tcp://{$this->host}:{$this->port}",
$errno, $errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
stream_context_create(['socket' => ['so_timeout' => $this->timeout * 1000000]])
);
if (!$this->socket) {
throw new RuntimeException("連接失敗 [$errno]: $errstr");
}
stream_set_timeout($this->socket, (int)$this->timeout, (int)(($this->timeout - (int)$this->timeout) * 1e6));
stream_set_blocking($this->socket, true);
// 協議握手交互
$this->negotiateOptions();
return true;
}
/** 處理 Telnet 選項協商 */
private function negotiateOptions(): void
{
// 發送我們支持的選項 (WILL ECHO, WILL SUPPRESS_GA, DO TERMINAL_TYPE, DO WINDOW_SIZE)
$initCmds = chr(self::IAC) . chr(self::WILL) . chr(self::OPT_ECHO) .
chr(self::IAC) . chr(self::WILL) . chr(self::OPT_SUPPRESS_GA) .
chr(self::IAC) . chr(self::DO) . chr(self::OPT_TERMINAL_TYPE) .
chr(self::IAC) . chr(self::DO) . chr(self::OPT_WINDOW_SIZE);
fwrite($this->socket, $initCmds);
// 讀取並回應服務端協商
$this->readAndNegotiate(2.0); // 等待 2 秒收集協商數據
}
/** 讀取數據並自動回應協商命令 */
private function readAndNegotiate(float $duration): string
{
$start = microtime(true);
$data = '';
while (microtime(true) - $start < $duration) {
$chunk = fread($this->socket, 4096);
if ($chunk === '' || $chunk === false) break;
$data .= $chunk;
// 處理 IAC 序列
$data = $this->processIAC($data);
// 如果已收到提示符,可提前返回
if ($this->prompt && preg_match($this->prompt, $data)) break;
}
$this->buffer .= $data;
return $data;
}
/** 解析並回應 IAC 命令 */
private function processIAC(string $data): string
{
$result = '';
$len = strlen($data);
for ($i = 0; $i < $len; $i++) {
$byte = ord($data[$i]);
if ($byte !== self::IAC) {
$result .= $data[$i];
continue;
}
if ($i + 1 >= $len) break; // 不完整序列
$cmd = ord($data[++$i]);
if ($cmd === self::IAC) { // 轉義 IAC
$result .= chr(self::IAC);
continue;
}
if ($i + 1 >= $len) break;
$opt = ord($data[++$i]);
// 根據命令類型回應
$response = '';
switch ($cmd) {
case self::DO:
// 服務端請求我們啟用選項
if (in_array($opt, [self::OPT_TERMINAL_TYPE, self::OPT_WINDOW_SIZE])) {
$response = chr(self::IAC) . chr(self::WILL) . chr($opt);
$this->options[$opt] = true;
} else {
$response = chr(self::IAC) . chr(self::WONT) . chr($opt);
}
break;
case self::DONT:
$response = chr(self::IAC) . chr(self::WONT) . chr($opt);
$this->options[$opt] = false;
break;
case self::WILL:
// 服務端願意啟用選項
if (in_array($opt, [self::OPT_ECHO, self::OPT_SUPPRESS_GA])) {
$response = chr(self::IAC) . chr(self::DO) . chr($opt);
$this->options[$opt] = true;
} else {
$response = chr(self::IAC) . chr(self::DONT) . chr($opt);
}
break;
case self::WONT:
$response = chr(self::IAC) . chr(self::DONT) . chr($opt);
$this->options[$opt] = false;
break;
case self::SB:
// 子協商: IAC SB OPT ... IAC SE
// 簡單跳過到 SE
while ($i + 1 < $len) {
if (ord($data[$i]) === self::IAC && ord($data[$i+1]) === self::SE) {
$i += 2;
break;
}
$i++;
}
continue 2; // 跳過外層循環
}
if ($response) fwrite($this->socket, $response);
}
return $result;
}
/** 登錄認證 */
public function login(string $username, string $password, float $loginTimeout = 10.0): bool
{
// 等待登錄提示
$this->waitFor('/(login|username|user name)[: ]*$/i', $loginTimeout);
$this->write($username . "\n");
// 等待密碼提示
$this->waitFor('/password[: ]*$/i', $loginTimeout);
$this->write($password . "\n");
// 等待 Shell 提示符
$output = $this->waitFor($this->prompt ?: '/[$#>] $/', $loginTimeout);
// 判斷登錄失敗
if (preg_match('/(incorrect|failed|invalid|denied)/i', $output)) {
$this->disconnect();
throw new RuntimeException("登錄失敗: $output");
}
return true;
}
/** 發送命令並獲取輸出 (不含提示符) */
public function exec(string $command, float $timeout = 30.0): string
{
$this->write($command . "\n");
usleep($this->cmdDelay * 1e6);
return $this->waitFor($this->prompt ?: '/[$#>] $/', $timeout);
}
/** 發送原始數據 */
public function write(string $data): int
{
return fwrite($this->socket, $data);
}
/** 等待匹配正則 (含提示符) */
public function waitFor(string $pattern, float $timeout = 10.0): string
{
$start = microtime(true);
$output = '';
while (microtime(true) - $start < $timeout) {
$chunk = fread($this->socket, 4096);
if ($chunk === '' || $chunk === false) {
usleep(10000); // 10ms
continue;
}
$chunk = $this->processIAC($chunk);
$output .= $chunk;
if (preg_match($pattern, $output)) {
// 移除末尾提示符
return preg_replace($pattern, '', $output);
}
}
throw new RuntimeException("等待超時 ($timeout 秒),模式: $pattern\n已收到: " . substr($output, -200));
}
/** 斷開連接 */
public function disconnect(): void
{
if ($this->socket) {
@fwrite($this->socket, "exit\n");
@fclose($this->socket);
$this->socket = null;
}
}
/** 析構函數自動斷開 */
public function __destruct()
{
$this->disconnect();
}
}
<?php
require 'TelnetClient.php';
$devices = [
['ip' => '192.168.1.1', 'user' => 'admin', 'pass' => 'cisco123', 'prompt' => '/[#>] ?$/'],
['ip' => '192.168.1.2', 'user' => 'admin', 'pass' => 'huawei123', 'prompt' => '/[#>] ?$/'],
['ip' => '192.168.1.10', 'user' => 'root', 'pass' => 'juniper', 'prompt' => '/[>%] ?$/'],
];
foreach ($devices as $dev) {
try {
$telnet = new TelnetClient($dev['ip'], 23, 15);
$telnet->setPrompt($dev['prompt']);
$telnet->connect();
$telnet->login($dev['user'], $dev['pass']);
// 進入特權模式 (Cisco)
if (str_contains($dev['prompt'], '#')) {
$telnet->exec('enable');
$telnet->exec('cisco123'); // enable 密碼
}
// 關閉分頁
$telnet->exec('terminal length 0');
// 獲取配置
$config = $telnet->exec('show running-config');
// 保存
$filename = "backup/{$dev['ip']}_" . date('Ymd_His') . ".cfg";
file_put_contents($filename, $config);
$telnet->disconnect();
echo "✅ {$dev['ip']} 備份成功: $filename\n";
} catch (Throwable $e) {
echo "❌ {$dev['ip']} 失敗: " . $e->getMessage() . "\n";
}
}
IAC DO/DONT/WILL/WONT 協商選項:回顯、抑制前進、終端類型、窗口大小、行模式等Telnet 無消息幀,**無法像 SSH 通道那樣明確區分命令輸出結束**。依賴:
/[$#>] $/, /[>%] ?$/)usleep) 兜底| 方案 | 協議 | 安全性 | PHP 支持 | 適用場景 |
|---|---|---|---|---|
| 本類 | Telnet | ❌ 明文 | 原生 Socket | 受控內網 Legacy 設備 |
| phpseclib Net/SSH2 | SSH-2 | ✅ 加密 | 純 PHP、無擴展依賴 | **首選**:現代設備、跨平台、Composer 安裝 |
| ssh2 擴展 (PECL) | SSH-2 | ✅ 加密 | C 擴展、高性能 | 高併發、長連接、需 libssh2 |
| Expect (Tcl/Shell) | Telnet/SSH | 視協議 | 外部進程 | 複雜交互腳本、非 PHP 環境 |
composer require phpseclib/phpseclib
use phpseclib\Net\SSH2;
$ssh = new SSH2('192.168.1.1');
if (!$ssh->login('admin', 'cisco123')) exit('登錄失敗');
$ssh->write("terminal length 0\n");
$output = $ssh->read('/[#>] /');
$config = $ssh->exec('show running-config');
file_put_contents('backup.cfg', $config);
PHP 實現 Telnet 客戶端核心在於:**Socket 連接 + IAC 協議協商 + 提示符驅動的命令執行循環**。本類提供了完整的協商處理、登錄流程、命令執行、超時控制,可直接用於網絡設備自動化運維。**強烈建議新項目使用 SSH (phpseclib)**,僅在設備不支持 SSH 時作為最後手段使用 Telnet。