1 expect可用于自动化脚本的书写

yum -y install expect即可下载

2 脚本ssh.exp

#此行用于解释器,这样意味着你可以./ssh.exp了,或者不写这行直接/usr/bin/expect ssh.exp也行

这里我要说一句很重要的话:expect很看重空格,即所谓的格式,expect有debug功能,具体可以man expect,expect需要您有耐心才能玩好,磨刀不误砍柴工



#!/usr/bin/expect -f


#设置参数的方法是使用set,如果想获取命令行参数,则使用[ index $argv 0 ]表示获取第一个参数

set ip "localhost"

set passwd "liuliancao"

set timeout 10


#生成一个进程

spawn ssh liuliancao@$ip

expect "(yes/no)?" {send "yes\r";exp_continue}  #如果遇到了(yes/no)?这样的字符串就输入yes和换行符号,继续后面的expect,注意{前面有个空格,expect后面有个空格

expect "password:" {send "$passwd\r";interact} #如果遇到了password:这样的字符串就输入用户秘密,并保持交互

3 脚本ssh_without_passwd.exp

#!/usr/bin/expect -f
set ip [ lindex $argv 0 ]
set passwd [ lindex $argv 1 ]
spawn ssh-copy-id -i /root/.ssh/id_rsa  root@$ip
expect "yes/no" {send "yes\r";exp_continue}
expect "password:" {send "$passwd\r"}


interact


4 生成一个脚本judge.exp

#!/usr/bin/expect   
set timeout  60
set ip [lindex $argv 0]
set password [lindex $argv 1]
set port [lindex $argv 2]
spawn  ssh -p $port  root@$ip
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "$password\r"}
}
interact

改天我再补出其他写法