文章目录
- 一、初级语法学习
- 二、例子
一、初级语法学习
1.使用expect进行ssh另一台机器
[root@localhost ~]# yum install -y expect #先安装expect
[root@localhost ~]# vim expect1.sh
#!/usr/bin/expect
spawn ssh root@192.168.68.244
expect {
"yes/no" {send "yes\r";exp_continue} #捕获yes/no,然后输出yes
"password:" {send "root\r"} #捕获password然后输入密码“root”
}
interact
2.ip和密码由用户传参登录另一台机器
[root@localhost ~]# vim expect2.sh
#!/usr/bin/expect
set ip [ lindex $argv 0 ]
set pass [ lindex $argv 1]
set timeout 5
spawn ssh root@$ip
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "$pass\r"}
}
interact
[root@localhost ~]# expect -f expect2.sh 192.168.68.244 root #执行
二、例子
1.A机器远程登录到B机器进行操作
[root@localhost ~]# vim expect3.sh
#!/usr/bin/expect
set ip 192.168.68.244
set pass root
set timeout 5
spawn ssh root@$ip
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "$pass\r"}
}
expect "#"
send "rm -rf /tmp/*\r"
send "touch /tmp/file{1..3}\r"
send "date\r"
send "exit\r"
expect eof
[root@localhost ~]# chmod +x expect3.sh
[root@localhost ~]# ./expect3.sh
2.控制多台机器创建用户
第一步:先将需要创建用户的机器的ip和密码写在ip.txt
[root@localhost ~]# echo 192.168.68.244 root > ip.txt
第二步:开始编写脚本
[root@localhost ~]# vim expect4.sh
#!/bin/bash
while read ip pass
do
/usr/bin/expect <<-END &>/dev/null
spawn ssh root@$ip
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "$pass\r"}
}
expect "#" { send "useradd yy1;rm -rf /tmp/*;exit\r" }
expect eof
END
done < /root/ip.txt
[root@localhost ~]# chmod +x expect4.sh
[root@localhost ~]# ./expect4.sh