20.27 分发系统介绍

分发系统介绍

expect可以让我们实现自动登录远程机器,并且可以实现自动远程执行命令。当然若是使用不带密码的密钥验证同样可以实现自动登录和自动远程执行命令。但当不能使用密钥验证的时候,我们就没有办法了。所以,这时候只要知道对方机器的账号和密码就可以通过expect脚本实现登录和远程命令。

 


20.28 expect脚本远程登录

expect脚本远程登录

安装:yum install -y expect

进入sbin目录创建1.expect文件,将以下内容复制到1.expect里面:

blob.png 

 

 

赋予1.expect权限:

chmod a+x 1.expect 

 

自动远程登录脚本:

 

 #! /usr/bin/expect

set host "172.16.17.70"

set passwd "123456a"

spawn ssh [email protected]$host

expect {

"yes/no" { send "yes\r"; exp_continue}

"assword:" { send "$passwd\r" }

}

interact

blob.png 

 


20.29 expect脚本远程执行命令


expect脚本远程执行命令

进入sbin目录创建2.expect文件,将以下内容复制到2.expect里面:

blob.png 

 

 

自动远程登录后,执行命令并退出:

 

#!/usr/bin/expect

set user "root"

set passwd "123456a"

spawn ssh [email protected]

 

 

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"

blob.png 

 

 

赋予权限:

chmod a+x 2.expect 

blob.png 

 

 

执行./2.expect命令进入了172.16.17.70机器并执行了两条命令后退出:

blob.png 

 

 

可以检查一下70的机器,文件和内容都生成了:

blob.png 



 20.30 expect脚本传递参数

expect脚本传递参数

进入sbin目录创建3.expect文件,将以下内容复制到3.expect里面:

 

赋予权限:

blob.png 

 

 

传递参数

 

#!/usr/bin/expect

 

set user [lindex $argv 0]

set host [lindex $argv 1]

set passwd "123456a"

set cm [lindex $argv 2]

spawn ssh [email protected]$host

 

 

expect {

"yes/no" { send "yes\r"}

"password:" { send "$passwd\r" }

}

expect "]*"

send "$cm\r"

expect "]*"

send "exit\r"

 

blob.png 

 

 

执行命令./3.expect root 172.16.17.70 ls ,登录上70的机器并执行ls命令:

blob.png 

 

 

(多个参数命令: ./3.expect root 172.16.17.70 "ls;w;vmstat 1"

blob.png