//定義expect腳本 $expect_script = "spawn ping 127.0.0.1\n"; $expect_script .= "expect {\n"; $expect_script .= " \"(timeout)\" {\n"; $expect_script .= " exit 1\n"; $expect_script .= " }\n"; $expect_script .= " eof {}\n"; $expect_script .= "}\n"; $expect_script .= "exit 0\n"; //調用expect腳本 $output = ""; exec("expect -c '$expect_script'", $output); //輸出ping的結果 foreach ($output as $line) { echo "這個示例中,首先定義了一個expect腳本,用于調用ping命令并獲取輸出結果。然后使用exec函數調用expect并傳遞腳本內容作為參數。最后將獲取的輸出結果逐行輸出。 除了執行ping操作外,expect還可以用于執行一些需要交互操作的命令行工具,比如SSH、Telnet等。使用expect可以模擬用戶輸入密碼、執行命令并獲取輸出結果。如下面這個例子,使用expect和SSH協議連接到遠程服務器并執行命令:" . $line . "
"; }
//定義expect腳本 $expect_script = "spawn ssh user@server\n"; $expect_script .= "expect {\n"; $expect_script .= " \"password:\" {\n"; $expect_script .= " send \"my_password\n\"\n"; $expect_script .= " exp_continue\n"; $expect_script .= " }\n"; $expect_script .= " \">\" {\n"; $expect_script .= " send \"ls -la /home/user\n\"\n"; $expect_script .= " expect \">\"\n"; $expect_script .= " }\n"; $expect_script .= " eof {}\n"; $expect_script .= "}\n"; $expect_script .= "exit 0\n"; //調用expect腳本 $output = ""; exec("expect -c '$expect_script'", $output); //輸出命令執行結果 foreach ($output as $line) { echo "這個示例中,首先定義了一個expect腳本,用于連接到遠程服務器并執行命令。然后使用exec函數調用expect并傳遞腳本內容作為參數。最后將獲取的輸出結果逐行輸出。 總之,expect是一個非常強大的庫,可以使PHP獲得更廣泛的應用場景。當需要執行一些交互式命令時,使用expect可以很方便地模擬用戶的操作,獲取命令執行結果。" . $line . "
"; }