expect具有非交互式功能
yum -y install expect
mkpasswd -l 20 #<==生成隨機字符串,-l參數指定生成字符串的長度
非交互密鑰分發
添加用戶(所有機器)
useradd jiege1
echo 123456|passwd --stdin jiege1
id jiege1
10創建密鑰對
su - jiege1
ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa>/dev/null 2>&1
10一鍵分發公鑰expect腳本沒指定主機
vim fenfa_sshkey.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 [email protected]:/etc/hosts
#spawn scp -P6666 $file jiege1@$host:$dir
spawn ssh-copy-id -i $file "-p6666 jiege1@$host"
expect {
"yes/no" {send "yes\r";exp_continue}
"*password" {send "$password\r"}
}
expect eof
exit -onexit {
send_user"jiege say good bye to you!\n"
}
expect fenfa_sshkey.exp .ssh/id_dsa.pub 192.168.169.11
#需手動輸入公鑰和ip,但是不用手動輸yes和密碼了(expect非交互式功能)可以把fenfa_sshkey.exp寫入腳本一鍵實現集羣通過主服務器ssh免密登入
批量寫入多臺主機
vim fenfa_sshkey.sh
#!/bin/sh
. /etc/init.d/functions
for ip in 11 12 13 14 15
do
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 192.168.169.$ip >/dev/null 2>&1
if [ $? -eq 0 ];then
action "$ip" /bin/true
else
action "$ip" /bin/false
fi
done
注意此腳本要和fenfa_sshkey.exp一個目錄