PHP 8.3.4 Released!

Expect の使用例

例1 Expect の使用例

この例ではリモートホストに SSH 経由で接続し、接続先の稼働時間を表示します。

<?php
ini_set
("expect.loguser", "Off");

$stream = fopen("expect://ssh root@remotehost uptime", "r");

$cases = array (
array (
0 => "password:", 1 => PASSWORD)
);

switch (
expect_expectl ($stream, $cases)) {
case
PASSWORD:
fwrite ($stream, "password\n");
break;

default:
die (
"リモートホストへの接続時にエラーが発生しました!\n");
}

while (
$line = fgets($stream)) {
print
$line;
}
fclose ($stream);
?>

次の例は、リモートホストに接続して インストールされている OS が 32 ビットか 64 ビットかを確認し、 それぞれのパッケージのアップデートを実行します。

例2 もうひとつの Expect の使用例

<?php
ini_set
("expect.timeout", -1);
ini_set("expect.loguser", "Off");

$stream = expect_popen("ssh root@remotehost");

while (
true) {
switch (
expect_expectl ($stream, array (
array (
"password:", PASSWORD), // SSH がパスワードを問い合わせます
array ("yes/no)?", YESNO), // SSH がホストエントリを保存するかどうかを問い合わせます
array ("~$ ", SHELL, EXP_EXACT), // シェルにたどり着きました!
))) {
case
PASSWORD:
fwrite ($stream, "secret\n");
break;

case
YESNO:
fwrite ($stream, "yes\n");
break;

case
SHELL:
fwrite ($stream, "uname -a\n");
while (
true) {
switch (
expect_expectl ($stream, array (
array (
"~$ ", SHELL, EXP_EXACT), // シェルにたどり着きました!
array ("^Linux.*$", UNAME, EXP_REGEXP), // uname -a の出力
), $match)) {
case
UNAME:
$uname .= $match[0];
break;

case
SHELL:
// アップデートの実行
if (strstr ($uname, "x86_64")) {
fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_64bit.rpm\n");
} else {
fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_32bit.rpm\n");
}
fwrite ($stream, "exit\n");
break
2;

case
EXP_TIMEOUT:
case
EXP_EOF:
break
2;

default:
die (
"エラーが発生しました!\n");
}
}
break
2;

case
EXP_TIMEOUT:
case
EXP_EOF:
break
2;

default:
die (
"エラーが発生しました!\n");
}
}

fclose ($stream);
?>
add a note

User Contributed Notes 1 note

up
4
David dkxl
11 years ago
If using the examples with telnet instead of ssh, note that telnet may need \r (Carriage Return) instead of \n (New Line)
To Top