shell项目-分发系统-expect讲解
yum install -y expect
1. 自动远程登录
#! /usr/bin/expect
set host "192.168.133.132"
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes
"; exp_continue}
"assword:" { send "$passwd
" }
}
interact
2. 自动远程登录后,执行命令并退出
#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.133.132
expect {
"yes/no" { send "yes
"; exp_continue}
"password:" { send "$passwd
" }
}
expect "]*"
send "touch /tmp/12.txt
"
expect "]*"
send "echo 1212 > /tmp/12.txt
"
expect "]*"
send "exit
"
3. 传递参数
#!/usr/bin/expect
set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "123456"
set cm [lindex $argv 2]
spawn ssh $user@$host
expect {
"yes/no" { send "yes
"}
"password:" { send "$passwd
" }
}
expect "]*"
send "$cm
"
expect "]*"
send "exit
"
4. 自动同步文件
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.133.132:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes
"}
"password:" { send "$passwd
" }
}
expect eof
5. 指定host和要同步的文件
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av $file root@$host:$file
expect {
"yes/no" { send "yes
"}
"password:" { send "$passwd
" }
}
expect eof