方法一: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