我寫了一個可以執行多個指令的 script。這個 script 會將每個指令的輸出以陣列形式回傳,並以「指令」作為索引。
注意:ssh2_cmd() 不適用於多個指令,因此請使用 ssh2_shell()。請注意不同作業系統的換行字元。我在每個指令的結尾使用了「\n」,但也許可以使用其他選項,例如「<br>、; 等等)。
$connection = ssh2_connect($input_host_ip, 22);
if (false === $connection) {
error_log("ERROR 函式 SSH_UMTELECOM:連線失敗!\n",3,$log_file);
exit();
}else{
if($debugar){error_log("SSH_UMTELECOM: 連線至 $input_host_ip 成功!\n",3,$log_file);}
$auth = @ssh2_auth_password($connection, $user, $pass);
if (false === $auth) {
error_log("錯誤 函式 SSH_UMTELECOM: 在 $input_host_ip 上驗證失敗 (使用者: $user)!\n",3,$log_file);
exit();
}else{
if($debugar){error_log("SSH_UMTELECOM: 在 $input_host_ip 上驗證成功!\n",3,$log_file);}
error_log("開始串流: $connection\n",3,$log_file);
$output_array = array();
$shell = ssh2_shell($connection, 'vt100');
foreach($input_cmd as $cmd){
if($debugar){error_log("shell: $cmd\n",3,$log_file);}
$output_stream = ""; # 清空變數,供每次互動使用
fwrite($shell, "$cmd\n"); # 每個指令結束時別忘了加上 "\n"
#stream_set_blocking($shell, true); # 無法運作,會無限期等待
sleep(2); # 適用於高延遲網路的 2 秒延遲
while($output_streams = fgets($shell)){
$output_stream .= $output_streams;
flush();# 清空內容,供下次互動使用
}
$output_array[] = $output_stream; # 將每個回傳值與其對應的指令彙整在一起
}
fclose($shell); # 從 shell 正常登出
}# if false === $auth 結束
}# if false === $conenection 結束