一个简单的expect脚本

上一篇 / 下一篇  2011-08-27 23:53:00 / 个人分类:Shell学习

 昨天才看了expect资料,下午工作不忙写了个脚本改密码的,代替passwd交互。
  1. #!/usr/bin/expect--

  2. settimeout 30
  3. setname[lindex $argv 0]
  4. setpw[lindex $argv 1]
  5. log_user 0
  6. spawn passwd $name
  7. for{seti 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字样的就输出修改成功,然后退出脚本。

 

 

  1. #!/usr/bin/expect--

  2. settimeout 30
  3. setname[lindex $argv 0]
  4. setpw[lindex $argv 1]
  5. log_user 0
  6. spawn passwd $name
  7. expect{
  8.     "password"{send"$pw\r";exp_continue}
  9.     "su"{puts"Password updated successfully"}
  10. }
  11. expect eof

[解析]

  这个脚本更简单利用了"exp_continue",匹配到password字样的就发送密码然后再返回到花括号开始重新执行,到了第3次匹配不到password字样了,匹配了su ,然后输出到屏幕。


TAG:

abinNO1的个人空间 引用 删除 abinNO1   /   2013-03-20 21:28:08
自动scp一个文件到远程服务器,此处的exp_continue意思是继续执行下面的匹配,可以换成expect eof表示匹配结束符。
#!/usr/bin/expect
if {$argc!=4} {
        send_user "Usage: $argv0 {file_name} {ipaddress} {path} {password}\n"
        exit
}
set file [lindex $argv 0]
set ip [lindex $argv 1]
set path [lindex $argv 2]
set password [lindex $argv 3]
spawn /usr/bin/scp -r $file root@$ippath
expect {
        "(yes/no)?"
        {
        send "yes\r"
        expect "*assword:*"
        send "$password\r"
        exp_continue
        }
        "*assword:*"
        {
        send "$password\r"
        exp_continue
        }
}
abinNO1的个人空间 引用 删除 abinNO1   /   2011-09-21 21:13:10
http://www.linuxsir.org/main/?q=node/134
eval的作用
abinNO1的个人空间 引用 删除 abinNO1   /   2011-09-20 09:17:00
http://blog.csdn.net/unbutun/article/details/6448413
awk用法小结
abinNO1的个人空间 引用 删除 abinNO1   /   2011-09-20 09:16:06
http://blog.csdn.net/unbutun/article/details/5615626
内核堆栈起始与结束
abinNO1的个人空间 引用 删除 abinNO1   /   2011-09-14 16:12:18
http://www.cnblogs.com/kevin-wu/archive/2006/11/27/574369.html
close_wait状态生成的起因。
abinNO1的个人空间 引用 删除 abinNO1   /   2011-09-07 19:46:33
http://topic.csdn.net/u/20071121/16/47FB018D-3AD6-4A5B-8E74-2838BBD70DB9.html
vi高亮显示
abinNO1的个人空间 引用 删除 abinNO1   /   2011-09-07 11:11:45
http://topic.csdn.net/u/20100709/23/2FCF2E53-68D7-4CE3-AA04-9088A4ADD7E9.html
shell变量
abinNO1的个人空间 引用 删除 abinNO1   /   2011-09-06 21:09:06
http://bbs.chinaunix.net/thread-2319120-1-1.html大赛
abinNO1的个人空间 引用 删除 abinNO1   /   2011-08-31 20:53:33
http://topic.csdn.net/u/20070302/11/8D39802A-17B3-42B2-81EC-8F547811A728.html#r_39510541
linux学习笔记
 

评分:0

我来说两句

Open Toolbar