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

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

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

 

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

 

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

1
2
3
4
5
6
7
8
9
10
[root@web ~]$ vim ssh-keygen.exp
#!/usr/bin/expect
#set enter "\n"
spawn ssh-keygen -t dsa
expect {
        "*(/root/.ssh/id_dsa)" {send "\n\r";exp_continue}
        "*(empty for no passphrase)" {send "\n\r";exp_continue}
        "*again" {send "\n\r"}
}
expect eof

 

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

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
[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\n"
 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\r";exp_continue}
        "*password" {send "$password\r"}
}
expect eof

 

posted @   HR·  阅读(1646)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示