知识点032-expect 分发安装脚本,以及安装服务

 

方法一:linux

系统环境:  4台服务器 web

系统版本:  CentOS release 6.9 (Final)shell

10.0.0.62  m01       分发服务器
10.0.0.63  web       网页服务器
10.0.0.64  nfs         网络传输共享服务器
10.0.0.65  backup  备份服务器bash

 

1.编写一个.exp的脚本服务器

#!/usr/bin/expect
if { $argc !=2 } {
 send_user "usage: expect fenfa_sshkey.exp file host\n"
 exit
}

#define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password "123456"
#spawn scp /etc/hosts root@172.16.1.41:/etc/hosts
spawn ssh-copy-id -i $file "-p 22 root@$host"
expect {
        "yes/no"    {send "yes\r";exp_continue}
        "*password" {send "$password\r"}
}
expect cof
exit -onexit {
        send_user " say good bye to you!\n"
}
 
#expect fenfa_sshkey.exp file host dir
#expect fenfa_sshkey.exp ~/hosts 10.0.0.63:~

2.编写一个.sh 的脚本网络

#!/bin/sh
. /etc/init.d/functions
#1.product key pair
ssh-keygen  -t  dsa -P '' -f ~/.ssh/id_dsa >/dev/null  2>&1
if [ $? -eq 0 ];then
   action "create dsa $ip" /bin/true
else
   action "create dsa $ip" /bin/false
   exit 1
fi

#2.dis pub key
for ip in 63 64 65
do
expect /service/scripts/fenfa_sshkey.exp ~/.ssh/id_dsa.pub 10.0.0.$ip >/dev/null 2>&1
 if [ $? -eq 0 ];then
     action "$ip" /bin/true
 else
     action "$ip" /bin/false
 fi
done

3.想批量分发文件和安装软件直接在上面的脚本后面新添加如下命令便可,install.sh 脚本中能够编写你要安装的服务ssh

#3.dis fenfa scripts
for n in 63 64 65 
do
 scp -P 22 -rp /home/s-linuxad/scripts root@10.0.0.$n:~
done

#3.install service
for m in  63 64 65 
do
 ssh -t -p 22 root@10.0.0.$m sudo /bin/bash ~/home/scripts/install.sh
done

4.若是ssh链接比较慢的话,则修改 /etc/sshd/sshd_config  的配置文件 函数

UseDNS no  spa

而且在/etc/hosts 添加域名解析code

cat >>/etc/hosts <<EOF
10.0.0.62  m01
10.0.0.63  web
10.0.0.64  nfs
10.0.0.65  backup
EOF

方法二:

一、客户端须要统一的管理帐号xxx,密码尽可能复杂些,经过密码生成器生成(不建议用root)

二、在sudoer文件中配置管理帐号 :xxx ALL=(ALL) NOPASSWD:ALL

好了,接下来就是主角了。两个脚本(expect和shell)

expect 脚本:这是一个交互的脚本语言。

#!/usr/bin/expect

if { $argc !=2 } {

send_user "usege:expect fenfa_sshkey.exp file host" #这里是使用方法

exit

}

#define var

set file [lindex $argv 0] ##expect 变量的设置方法和shell不同。

set host [lindex $argv 1]

set password "密码" ##这里是管理帐号的密码,客户机都同样的。

spawn ssh-copy-id -i $file "管理帐号@$host" ##spawn后面跟执行的命令

expect { ##expect顾名思义是期待的意思

"yes/no" {send "yes";exp_continue} ##期待到yes/no,就发送yes,而后继续

"*password" {send "$password"}

}

expect eof

shell脚本:对上述脚本进行循环各个客户端机

#!/bin/bash

. /etc/init.d/functions

for ip in `cat iplist` #这里是单独一个文件保存被控端IP

do

expect fenfa_sshkey.exp ~/.ssh/id_rsa.pub $ip #执行上述exp脚本

if [ $? -eq 0 ];then #这是一个反馈意思上一条命令成功若是是0标识成功

action "$ip" /bin/true #那么就ok。这里action是一个function函数(开头引用的)

else

action "$ip" /bin/false

fi

done
相关文章
相关标签/搜索