我们通过Shell可以实现简单的控制流功能,如:循环、判断等。但是对于需要交互的场合则必须通过人工来干预,有时候我们可能会需要实现和交互程序如telnet服务器等进行交互的功能。而Expect就使用来实现这种功能的工具。
Expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。
// 示例:为map用户生成动态密码,用于临时登录使用
<?php
$newpasswd = strtoupper(dechex(rand(100000000, 900000000)));
$sys = ‘/home/mars/app/dms/script/reset_passwd.sh ‘ . $newpasswd;
exec($sys, $result);
?>
reset_passwd.sh
============================
#!/home/tools/bin/64/expect -f
#登录信息
set ipaddr “xxx-mars.com”
set user “root”
set passwd “roo原密码”
#要修改的用户及新密码
set mdy_user “map”
set mdy_passwd [lrange $argv 0 0]
#登录并执行shell指令
spawn ssh $user@$ipaddr
expect {
“yes/no” { send “yes\r”; exp_continue}
“password:” { send “$passwd\r” }
}
expect “]# ”
send “touch ~/a.txt\r”
send “echo ‘$mdy_passwd’ | passwd $mdy_user –stdin\r”
send “exit\r”
expect eof
exit

Happy New Year.