分发系统介绍、 expect脚本远程登录、远程执行命令、传递参数

一、分发系统介绍

当我们要上线一个新代码的时候,如果机器少,我们的工作量不会很大,很容易完成,如果设备很多,有几十台,上百台的话,那我们的工作量会非常大,而且也不规范,这时,我们就可以用可以用开源的软件,expect脚本语言,进行实现分发系统的功能。

二、 expect脚本远程登录

1、expect脚本远程登录
2、安装:yum install -y expect
3、写一个expect的自动远程登录脚本
内容如下:

 #! /usr/bin/expect
set host "192.168.1.31" #这是expect的变量,它和shell不同的是变量前面要加set
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue} #第一次登录会提示yes或者是no,send是发送。\r是回车。
"assword:" { send "$passwd\r" }
}
interact   # 需要停留在远程的机器上,不需要退出。

4、给脚本权限:chmod a+x 1.expect
5、执行:./1.expect

三、 expect脚本远程执行命令

1、自动远程登录后,执行命令并退出
增加脚本如下内容:

#!/usr/bin/expect
set user "root"
set passwd "123456"
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"

2、执行脚本
./2.expect
3、 回车退出
4、重新执行自动登录脚本
5、./1.expect
6、查看远程创建的文件
7、ls -l /tmp/2018.txt

四、expect脚本传递参数

1、传递参数
vi 3.expect
增加如下脚本内容:

#!/usr/bin/expect

set user [lindex $argv 0] #把第一个参数的值赋给user
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"

2、给权限;
chmod a+x 3.expect
3、执行
./3.expect root 192.168.1.31 "ls;w;vmstat 1" #当有多个命令 需要用双引号 作为一个参数传进去
4、查看
ls;w;vmstat 1

猜你喜欢

转载自blog.51cto.com/10690709/2147512
今日推荐