一、生成密鑰
[root@master ~]# ssh-keygen
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:pvR6iWfppGPSFZlAqP35/6DEtGTvaMY64otThWoBTuk root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
| . o. |
|.o . . |
|+. o . . o |
| Eo o . + |
| o o..S. |
| o ..oO.o |
| . . ..=*oo |
| ..o *=@+ . |
| .oo=+@+.o.. |
+----[SHA256]-----+
生成之后會在用戶的根目錄生成一個 “.ssh”的文件夾,進入“.ssh”會生成以下幾個文件
authorized_keys id_rsa id_rsa.pub known_hosts
authorized_keys:存放遠程免密登錄的公鑰,主要通過這個文件記錄多台機器的公鑰
id_rsa : 生成的私鑰文件
id_rsa.pub : 生成的公鑰文件
know_hosts : 已知的主機公鑰清單
如果希望ssh公鑰生效需滿足至少下面兩個條件:
1) .ssh目錄的權限必須是700
2) .ssh/authorized_keys文件權限必須是600
二、遠程免密登錄
1.原理:
- 客戶端向服務器端發出連接請求
- 服務器端向客戶端發出自己的公鑰
- 客戶端使用服務器端的公鑰加密通訊密鑰然后發給服務器端
- 如果通訊過程被截獲,由於竊聽者即使獲知公鑰和經過公鑰加密的內容,但不擁有私 鑰依然無法解密(RSA算法)
- 服務器端接收到密文后,用私鑰解密,獲知通訊密鑰
2.常用以下幾種方法:
2.1通過ssh-copy-id的方式
[root@master ~]# ssh-copy-id -i root@slave1
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.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@worker1's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@worker1'"
and check to make sure that only the key(s) you wanted were added.
2.2通過scp將內容寫到對方的文件中
[root@test .ssh]# scp -p ~/.ssh/id_rsa.pub root@192.168.80.11:/root/.ssh/authorized_keys
root@192.168.80.11's password:
id_rsa.pub 100% 408 0.4KB/s 00:00
[root@test .ssh]#
[root@test .ssh]#
[root@test .ssh]#
[root@test .ssh]# ssh root@192.168.80.11
Last login: Mon Oct 10 01:27:02 2016 from 192.168.80.10
[root@localhost ~]#
或者
scp ~/.ssh/id_rsa.pub root@<remote_ip>:pub_key //將文件拷貝至遠程服務器
$ cat ~/pub_key >>~/.ssh/authorized_keys //將內容追加到authorized_keys文件中, 不過要登錄遠程服務器來執行這條命令