使用expect批量分发ssh公钥

2022-01-25 19:13:43

1、在源主机生成秘钥对:

$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:IG7JHBm5+IW+T8fd72XnGwaeWB/+z/PoBthuNF4gxkw root@node1
The key's randomart image is:
+---[RSA 2048]----+
|    ..           |
|    .o    E      |
|   .+o.  +       |
|  .+o+..  = .    |
|   o*.  S. + + . |
|   .o  . ...O * .|
|     .. o .=.* =+|
|    .. .    +.oB+|
|     ..    . +=.@|
+----[SHA256]-----+

2、编写 expect 脚本:

$ cat /scripts/ssh_copy_id.ex 
#!/usr/bin/expect
set timeout 10
set user_hostname [lindex $argv 0]
set password [lindex $argv 1]

spawn ssh-copy-id $user_hostname
    expect {
        "(yes/no)?"
        {
            send "yes\n"
            expect "*assword:" { send "$password\n"}
        }
        "*assword:"
        {
            send "$password\n"
        }
    }
expect eof

3、测试单机分发:

$ expect ssh_copy_id.ex root@10.0.1.202 root1234
spawn ssh-copy-id root@10.0.1.202
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@10.0.1.202's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@10.0.1.202'"
and check to make sure that only the key(s) you wanted were added.

4、编写批量分发脚本:

$ cat ssh_copy_id_batch.sh
#!/bin/sh
#
# 密码
pass='root1234'
# 要分发公钥的主机
ip_arr=(10.0.1.{202..204})
# 本机公钥中的用户名 + 主机名
user_host=`awk '{print $3}' ~/.ssh/id_rsa.pub`

for ip in ${ip_arr[*]};do
        # 执行分发操作
        expect ssh_copy_id.ex root@${ip} $pass &> /dev/null
        # 检查是否分发成功
        ssh $ip "grep "$user_host" ~/.ssh/authorized_keys" >&/dev/null
        # 输出分发结果
        [ $? -eq 0 ] && echo "${ip} added." || echo "${ip} failed."
done

5、测试批量分发:

$ bash ssh_copy_id_batch.sh 
10.0.1.202 added.
10.0.1.203 added.
10.0.1.204 added.