1、比如下面脚本用来做ssh无密码登陆,自动输入确认yes和密码信息,用户名,密码,hostname通过参数来传递
2、ssh.exp Python代码 #!/usr/bin/expect set timeout 10 set username [lindex $argv 0] set password [lindex $argv 1] set hostname [lindex $argv 2] spawn ssh-copy-id -i .ssh/id_rsa.pub $username@$hostname expect "yes/no" send "yes\r" expect "password:" send "$password\r" expect eof 执行脚本./ssh.exp root pasword hostname1
3、expect接收参数的方式和bash脚本的方式不太一样,bash是通过$0 ... $n 这种方式,而expect是通过set <变量名称> [lindex $argv <param index>],例如set username [lindex $argv 0]
4、其中expect为expect脚本解释器,因此你的电脑上必须安装expect;script.exp为脚本文件;argv1,argv2为传递到脚本文件的参数。#!/usr/bin/expectfor {set i 0} {$i < $argc} {incr i} {puts "arg $i: [lindex $argv $i]"}[yellia .script]$ ./echo.exp 11 22 33执行结果为:arg 0: 11arg 1: 22arg 2: 33如果你想获得当前执行脚本的名称,那么可以访问argv0
5、获取函数的参数expect 和shell一样提供了很多command,并且expect的大多数功能都是以command的方式实现的,例如控制结构(if/for/while/switch)。函数的功能是通过proc命令提供的。proc printParam {name sex} {puts "name: $name"puts "sex: $sex"}调用时必须传递对应个数的参数,否则会报错。