Shell 之自动化部署 SSH 密钥认证

  • 本地生成密钥对
[root@ansible expect]# ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa >/dev/null 2>&1
  • 开发 Expect 脚本自动化交互分发公钥到所有服务器
#!/usr/bin/expect

if { $argc != 2 } {
    send_user "Usage: expect $argv0 file host\n"
    exit
}

set file [lindex $argv 0]
set host [lindex $argv 1]
set password "test"

spawn ssh-copy-id -i $file  root@$host

expect {
    "yes/no"    {send "yes\r";exp_continue}
    "*password" {send "$password\r"}
}

expect eof
  • 开发 Shell 脚本循环执行 Expect 脚本
#!/bin/bash
#Author:mcsiberiawolf
#Time:2019-02-13 10:57:07
#Name:cp_file.sh
#Version:V1.0
#Description: This is a test script.


for n in 2 3
do
    /usr/bin/expect /server/scripts/expect/cp_ssh_key.exp ~/.ssh/id_dsa.pub 192.168.7.$n
done

执行脚本

[root@ansible expect]# sh cp_ssh_key.sh   
spawn ssh-copy-id -i /root/.ssh/id_dsa.pub root@192.168.7.2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_dsa.pub"
The authenticity of host '192.168.7.2 (192.168.7.2)' can't be established.
ECDSA key fingerprint is SHA256:8i0BfjkyGGWFlNov4yZCOJTZ4KqohSkl2mLYVZUSH2c.
ECDSA key fingerprint is MD5:2f:c9:04:86:59:ee:0f:34:e1:fe:45:dd:53:a4:11:4b.
Are you sure you want to continue connecting (yes/no)? yes
/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@192.168.7.2's password: 

Number of key(s) added: 1

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

spawn ssh-copy-id -i /root/.ssh/id_dsa.pub root@192.168.7.3
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_dsa.pub"
The authenticity of host '192.168.7.3 (192.168.7.3)' can't be established.
ECDSA key fingerprint is SHA256:liJEjVGOj8RZNg72rK5Uk0WpvGHHosWYcmDMJuPHw7Y.
ECDSA key fingerprint is MD5:2c:90:13:d9:c5:c8:91:2d:db:0a:11:2f:2c:71:15:41.
Are you sure you want to continue connecting (yes/no)? yes
/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@192.168.7.3's password: 

Number of key(s) added: 1

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


参考文章

跟老男孩学Linux运维 Shell编程实战

posted @ 2019-02-13 11:40  McSiberiaWolf  阅读(816)  评论(0)    收藏  举报