分发系统介绍
expect可以让我们实现自动登录远程机器,并且可以实现自动远程执行命令。当然若是使用不带密码的密钥验证同样可以实现自动登录和自动远程执行命令。但当不能使用密钥验证的时候,我们就没有办法了。所以,这时候只要知道对方机器的账号和密码就可以通过expect脚本实现登录和远程命令。
首先安装expect
yum install -y expect
示例1 自动远程登陆机器
编辑脚本
vim
test1.expect
写入如下的内容
#! /usr/bin/expect
set host "192.168.133.132"
set passwd "passwd"
spawn ssh root@$host
expect {
#当提示语句出现yes/no 输入yes然后继续
"yes/no" { send "yes\r"; exp_continue}
#当提示语句出现password 输入密码
"assword:" { send "$passwd\r" }
}
interact
执行脚本之前需要加上权限
chmod a+x test1.expect
./test1.expect
示例2 自动执行命令
编辑脚本
vim
test2.expect
写入如下的内容
#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.133.132
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "touch /tmp/12.txt\r"
expect "]*"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"
执行脚本之前需要加上权限
chmod a+x test2.expect
./
test2.expect
示例3 expect脚本传递参数
编辑脚本
vim
test3.expect
写入如下的内容
#!/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\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
执行脚本之前需要加上权限
chmod a+x test3.expect
执行脚本,输入用户,主机名以及命令
[root@lz01 sbin]# ./test3.expect root 192.168.177.200 "ls;w"
spawn ssh root@192.168.177.200
root@192.168.177.200's password:
Last login: Wed Apr 25 23:05:13 2018 from 192.168.177.100
[root@lz02 ~]# ls;w
1.txt anaconda-ks.cfg awk grep log logs pack.txt sed spilt temp zx
23:07:54 up 2:03, 3 users, load average: 0.08, 0.03, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 192.168.177.1 21:57 1:10m 0.03s 0.03s -bash
root pts/1 192.168.177.1 22:03 24:02 0.08s 0.08s -bash
root pts/2 192.168.177.100 23:07 0.00s 0.04s 0.00s w