一个expect使用的例子程序
[root@dba-server01 tftpboot]# less expect-ssh.exp
//提示用法
proc usage {} {
puts stderr "usage: $::argv0 username password hostip"
exit 1
}
proc connect {pass} {
expect {
"(yes/no)?" {
send "yes\n"
expect "*password:" {
send "$pass\n"
expect {
"*#" {
return 0
}
}
}
}
"*password:" {
send "$pass\n"
expect {
"*#" {
return 0
}
}
}
}
return 1
}
if {$argc != 3} { usage }
set username [lindex $argv 0]
set password [lindex $argv 1]
set hostip [lindex $argv 2]
spawn ssh ${username}@${hostip}
//这里表示如果连接不成功则返回!
if {![connect $password]} {
exit 1
}
send "touch /home/oracle/test.txt\n"//注意转移回车的使用,以免和exit指令连在一起.这里是目标机要执行的指令.
send "exit\n"
expect eof
参见http://www.cnblogs.com/super119/archive/2010/12/18/1909977.html