当前位置: 代码迷 >> 综合 >> linux SSH免密登陆,并执行批量任务
  详细解决方案

linux SSH免密登陆,并执行批量任务

热度:72   发布时间:2023-10-22 12:36:57.0

 

 

一、本机生成RSA公钥

[root@Zabbix ~]#  ssh-keygen -t rsa

可以设置密码,也可以一路enter,直到执行完成

[root@host16 ~]# 
[root@host16 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): y
Enter passphrase (empty for no passphrase):   #可以是空
Enter same passphrase again: 
Your identification has been saved in y.
Your public key has been saved in y.pub.
The key fingerprint is:
18:53:4c:35:9b:de:8e:b7:22:ea:f6:49:90:6a:3b:0a root@host16.6
The key's randomart image is:
+--[ RSA 2048]----+
|       oo.o      |
|       ..  +     |
|      o   o      |
|       = . .     |
|      + S . .    |
|     . .   o     |
|E   o   . . o    |
| . ......... .   |
|  ...+ooo. ..    |
+-----------------+
[root@host16 ~]# 执行完成

 

Enter file in which to save the key (/root/.ssh/id_rsa) #密钥存放的地方

二、复制SSH密钥到其他需要本台主机免密登陆的主机

[root@Zabbix ~]# ssh-copy-id  root@192.168.16.5

如果希望设置SSH连接持久化

[root@Zabbix ~]# ssh -MNf root@192.168.16.5

三、测试成果

[root@Zabbix ~]# ssh root@192.168.16.5
Last login: Sun Jan 17 18:47:07 2021 from 192.168.16.6
[root@host16 ~]# 

至此,设置完毕。

尝试进行批量操作,将远程主机reboot

#!/bin/bash
for ip in "192.168.16.5" "192.168.16.7" "192.168.16.8" "192.168.16.9"
dossh root@$ip "reboot"
done

完成。