expect程序交互学习

一、初级语法学习

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值