Linux免密登錄


一、生成免密登錄公鑰

ssh-keygen -t rsa

如下:

[root@VM-0-9-centos /]# ssh-keygen -t rsa
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:ZyZSw/Ciok0MqO1My3qgo9K9ONQBxkEkz8tymflz82Q root@VM-0-9-centos
The key's randomart image is:
+---[RSA 2048]----+
|.++.  .          |
|.++    +         |
|o.o.  . =        |
|.= =.. o .       |
|o &.... S +      |
|.@.+.  . =       |
|o+*.o o E        |
|+.+..o =         |
|=o....  .        |
+----[SHA256]-----+

注意:如果每生成過此公鑰,只需一路回車即可。

二、查看公鑰

公鑰的路徑:

Enter file in which to save the key (/root/.ssh/id_rsa):

即:/root/.ssh

[root@VM-0-9-centos /]# cd /root/.ssh/
[root@VM-0-9-centos .ssh]# ls
authorized_keys  id_rsa  id_rsa.pub
[root@VM-0-9-centos .ssh]#
authorized_keys:存放遠程免密登錄的公鑰,主要通過這個文件記錄多台機器的公鑰
id_rsa: 生成的私鑰文件
id_rsa.pub: 生成的公鑰文件
know_hosts: 已知的主機公鑰清單

如果希望ssh公鑰生效需滿足至少下面兩個條件:
1) .ssh目錄的權限必須是700
2) .ssh/authorized_keys文件權限必須是600

三、實現遠程免密登錄

在本地(或服務器A)上實現免密登錄服務器B,需要將本地(或服務器A)的公鑰(/root/.ssh/id_rsa.pub文件內容)配置到服務器B的/root/.ssh/authorized_keys里即可,多個公鑰注意換行。

四、配置方式

4.1 通過ssh-copy-id的方式

ssh-copy-id -i ~/.ssh/id_rsa.pub <username@romte_ip>

如下:

liumeng@liumengdeMacBook-Pro .ssh % ssh-copy-id -i ~/.ssh/id_rsa.pub root@106.53.***.***
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/liumeng/.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@106.53.***.***'s password:

Number of key(s) added:        1

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

4.2 SCP方式

scp -p ~/.ssh/id_rsa.pub root@<remote_ip>:/root/.ssh/authorized_keys

如下:

liumeng@liumengdeMacBook-Pro .ssh % scp -P 22 ~/.ssh/id_rsa.pub root@106.53.***.***:/root/.ssh/authorized_keys
root@106.53.***.***'s password:
id_rsa.pub                                                                                                                                             100%  588     7.8KB/s   00:00
liumeng@liumengdeMacBook-Pro .ssh %

4.3 通過Ansible實現批量免密

將需要做免密操作的機器hosts添加到/etc/ansible/hosts下

4.4 手動復制粘貼

將本地id_rsa.pub文件的內容拷貝至遠程服務器的~/.ssh/authorized_keys文件中。

結束!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM