ssh key一键自动化生成公钥私钥,并自动分发上百服务器免密码交互

题记:由于工作需要管理大量服务器,所以需要配公钥实现免密登录。

ssh批量分发可以一键执行这个操作,但是使用ssh分发服务还需要对各个服务器进行.ssh/id_dsa.pub公钥上传,密码验证。所以需要配合expect实现ssh免密码登陆。

在编写脚本之前,请先安装yum install expect -y

 1.编写服务器免交互生成公钥、私钥

[root@web ~]$ vim ssh-keygen.exp
#!/usr/bin/expect
#set enter "
"
spawn ssh-keygen -t dsa
expect {
        "*(/root/.ssh/id_dsa)" {send "

";exp_continue}
        "*(empty for no passphrase)" {send "

";exp_continue}
        "*again" {send "

"}
}
expect eof

2.编写批量分发公钥到各个服务器,并免密钥认证

[root@web ~]$ vim fenfa_sshkey.sh 
#!/bin/sh
expect ssh-keygen.exp &>/dev/null
. /etc/init.d/functions
for ip in 132 133
do
 #expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 192.168.59.$ip  >/dev/null 2>&1
 expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 192.168.59.$ip &>/dev/null
 if [ $? -eq 0 ];then
    action "192.168.59.$ip" /bin/true
 else
    action "192.168.59.$ip" /bin/false
 fi
done
[root@web ~]$ vim 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.0.0.142:/etc/hosts
#spawn scp -P52113 $file os_admin@$host:$dir
#spawn ssh-copy-id -i  $file "-p 52113 os_admin@$host"
spawn ssh-copy-id -i  $file "-p 22 root@$host"
expect {
        "yes/no"    {send "yes
";exp_continue}
        "*password" {send "$password
"}
}
expect eof
原文地址:https://www.cnblogs.com/yihr/p/7173044.html