使用shell和expect一键批量分发SSH密钥脚本

这是一个无需做任何配置一键就实现批量分发密钥和文件的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/bin/bash
# this scripts comes from oldboy trainning's student.
# e_mail:[email protected]
# qqinfo:49000448
# function: remote dis ssh key.
# version:1.1
################################################
# oldboy trainning info.
# QQ 80042789 70271111
# site:http://www.etiantian.org
# blog:http://oldboy.blog.51cto.com
# oldboy trainning QQ group: 208160987 45039636
################################################
/etc/init.d/functions
file="$1"
remote_dir="$2"
if [[ $# -ne 2 ]];then
echo "usage:$0 argv2"
echo "must have one argvs"
exit
fi
function KNOWN_HOST_REBUILD()
{
#确保本机存在known_hosts列表
[ ! -e ~/.ssh/known_hosts ] && mkdir -p ~/.ssh/ && touch ~/.ssh/known_hosts
local i=$1
sed -i "/^${i} /d" ~/.ssh/known_hosts
expect -c "
spawn /usr/bin/ssh oldboy@${i} echo ok;
expect \"*yes/no)?\";
send \"yes\r\";
expect eof " >/dev/null 2>&1
return 0
[[ $? -ne 0 ]] && echo "$i know host rebuild fail,maybe the server connect error"
}
function PASS_PASSWD()
{
ip=$1
expect -c "
set timeout -1
spawn ssh-copy-id -i id_dsa oldboy@$ip
expect \"*password:\"
send \"oldboy123\r\"
expect eof" >/dev/null 2>&1
}
function FENFA_id_dsa()
{
for ip in `awk '/^[^#]/{print $1}' all_client.txt`
do
KNOWN_HOST_REBUILD $ip
PASS_PASSWD $ip
if [[ $? -eq 0 ]];then
action "$ip send id_dsa is successful" /bin/true
else
action "$ip send id_dsa is failed copied" /bin/false
fi
done
}
function FENFA_config()
{
for ip in `awk '/^[^#]/{print $1}' all_client.txt`
do
port=$(grep $ip all_client.txt|awk '{print $2}')
scp -P${port} -r -p ${file} oldboy@${ip}:~ >/dev/null 2>&1 && \
ssh -p${port} -t oldboy@$ip sudo rsync ~/`basename ${file}` $remote_dir >/dev/null 2>&1
if [[ $? -eq 0 ]];then
action "$ip send $file is successful!!" /bin/true
else
action "$ip send $file is failed!!" /bin/false
fi
done
}
FENFA_id_dsa
FENFA_config

 

 

你可能感兴趣的:(shell,expect,远程批量拷贝密钥)