expect安装去测试

时间:2023-03-09 01:06:39
expect安装去测试

1.下载expect和tcl

下载地址:http://download.csdn.net/download/tobyaries/5754943

2.安装expect

tar -zxvf tcl8.4.11-src.tar.gz 
tar -zxvf expect-5.43.0.tar.gz 
cd tcl8.4.11/unix
 ./configure
make && make install

cd expect-5.43

./configure --with-tcl=/usr/local/lib/ --with-tclinclude=/data/software/tcl8.4.11

make && make install

3.脚本测试

  1. #!/usr/bin/expect -f
  2. set timeout 30
  3. set name [lindex $argv 0]
  4. set pw [lindex $argv 1]
  5. log_user 0
  6. spawn passwd $name
  7. for {set i 1} {$i < 3} {incr i} {
  8. expect "*password:" {send "$pw\r"}
  9. }
  10. expect "*successfully"
  11. send_user "Password updated successfully\n"
  12. expect eof

[解析]

很简单的程序,首先把第一个参数赋值给变量name作为用户名,把第二个参数赋值给pw作为密码。然后关闭标准输出,就是类似shell的 "> /dev/null",然后spawn开启子进程运行passwd程序,因为会重复输入2次密码,所以这里我们用到了TCL语法的for循环,执行2次密码输入。最后匹配到successfully字样的就输出修改成功,然后退出脚本。