except 配合 shell实现公钥分发脚本

新建 alvin 用户,设置登录密码为:123456
切换到 alvin 下面,创建dsa 密钥
以上实现方法省略


# 使用expect 编写交互式登录
[root@backup ~]# yum install expect -y

[root@backup ~]# which expect
/usr/bin/expect
------------------------------------------
[root@backup scripts]# cat fenfa_sshkey.exp

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

#define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password "123456"

#spawn scp /etc/hosts root@10.89.7.10:/etc/hosts
#spawn scp /-P52113 $file tornado@$host:$dir
#spawn ssh-copy-id -i $fiel "-p 52113 tornado@$host"

spawn ssh-copy-id -i $file "-p 22 alvin@$host"
expect {
"yes/no" {send "yes
";exp_continue}
"*password" {send "$password
"}
}
expect eof

#script usage
#expect fenfa_sshkey.exp file host dir
#example
#./fenfa_sshkey.exp /etc/hosts 10.89.7.10 /etc/hosts

  -------------------------------------------------------

[root@backup scripts]# cat fenfa_sshkey.sh

#! /bin/sh
. /etc/init.d/functions
#for ip in `cat iplist`
for ip in 10 11 12
do
#expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub $ip >/dev/null
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 10.89.7.$ip

if [ $? -eq 0 ];then
action "$ip" /bin/true
else
action "$ip" /bin/false
fi
done

  

[root@backup scripts]#
---------------------------------------
分发机上执行:
[alvin@backup scripts]$ sh fenfa_sshkey.sh
spawn ssh-copy-id -i /home/alvin/.ssh/id_dsa.pub -p 22 alvin@10.89.7.10
alvin@10.89.7.10's password:
Now try logging into the machine, with "ssh '-p 22 alvin@10.89.7.10'", and check in:

.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

10 [ OK ]
spawn ssh-copy-id -i /home/alvin/.ssh/id_dsa.pub -p 22 alvin@10.89.7.11
ssh: connect to host 10.89.7.11 port 22: No route to host
expect: spawn id exp4 not open
while executing
"expect eof"
(file "fenfa_sshkey.exp" line 21)
11 [FAILED]
spawn ssh-copy-id -i /home/alvin/.ssh/id_dsa.pub -p 22 alvin@10.89.7.12
alvin@10.89.7.12's password:
Now try logging into the machine, with "ssh '-p 22 alvin@10.89.7.12'", and check in:

.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

12 [ OK ]
[alvin@backup scripts]$ ssh -p22 10.89.7.12 uptime
15:30:21 up 1 day, 6:21, 1 user, load average: 0.00, 0.00, 0.00
[alvin@backup scripts]$ ssh -p22 10.89.7.10 uptime
15:30:30 up 1 day, 6:21, 1 user, load average: 0.00, 0.00, 0.00
[alvin@backup scripts]$

#验证

[alvin@linux-node2 ~]$ echo IP="`ifconfig eth0|awk -F '[ :]+' 'NR==2 {print $4}'`"
IP=10.89.7.10

[alvin@linux-node2 ~]$ ll .ssh/
total 4
-rw------- 1 alvin alvin 602 Sep 15 15:48 authorized_keys

原文地址:https://www.cnblogs.com/ahtornado/p/9651295.html