非交互分发ssh密钥工具expect使用
yum install -y expect
cd ~
cat >distribute_sshkey.exp<<'NYC'
#!/usr/bin/expect
#传递一个参数
if {$argc != 1} {
send_user "usage:expect distribute_sshkey.exp file host\n"
exit
}
#set file [lindex $argv 0]
set host [lindex $argv 0]
#此处设置密码
set passwd www.123.nyc
spawn ssh-copy-id $host
expect {
"(yes/no)" {send "yes\r";exp_continue}
"password:" {send "$passwd\r"}
}
expect eof
#以下可以忽略
exit -onexit {
send_user "OLDBOY say goodbey to you!\n"
}
NYC
###############################################################
cat >distribute_sshkey.sh<<'NYC'
#!/bin/bash
source /etc/init.d/functions
#根据/etc/hosts具体情获取的主机名或IP地址
hosts=$(awk 'NR>3 {print $2}' /etc/hosts)
for IP in $hosts
do
cd ~
expect distribute_sshkey.exp $IP &> /dev/null
if [ $? -eq 0 ];then
action "$IP" /bin/true
else
action "$IP" /bin/false
fi
done
NYC
##############################################################
#执行脚本
直接下载脚本使用
ssh-keygen -N '' -f ~/.ssh/id_rsa
yum install -y expect
wget --http-user=qwe --http-passwd=qwe http://61.160.213.184/dl/centos/distribute_sshkey.exp
wget --http-user=qwe --http-passwd=qwe http://61.160.213.184/dl/centos/distribute_sshkey.sh
注意NR取行的修改
bash distribute_sshkey.sh
分发hosts文件(重游NR的取行的修改)
for i in $(awk 'NR>7 {print $2}' /etc/hosts);do scp /etc/hosts $i:/etc;done