頻繁登錄Linux服務器時,使用ssh <username>@<host>的方式登錄,但是每次都需要輸入密碼是件很麻煩的事。我們還可以使用私鑰/公鑰對的方式在免密碼登錄服務器。
首先需要在遠程服務器中安裝ssh-server服務,才可以使用ssh登錄。如果沒有的話可以使用命令直接安裝ssh-server,可以以Ubuntu為例安轉(zhuǎn)ssh-server:
sudo apt-get install openssh-server
生成私鑰/公鑰對
使用命令ssh-kengen可以生成私鑰/公鑰對,私鑰/公鑰對的生成算法有兩種RSA和DSA。
RSA是非對稱加密算法,可以用來加密和簽名
DSA(Digital Signature Algorithm)只可以用來數(shù)字簽名的算法
這里使用RSA算法生成私鑰/公鑰對。需要確認.ssh目錄是否存在,如果不存在的話創(chuàng)建該目錄:
mkdir ~/.ssh
chmod 700 ~/.ssh
然后生成私鑰/公鑰對:
ssh-keygen -b 1024 -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/user/.ssh/id_rsa.
Your public key has been saved in /Users/user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gh0yqSZhpP9ERlhFSKwgy3sTBZwPAT0InLBJ73zcNt8 user@user-ios.local
The key's randomart image is:
+---[RSA 1024]----+
|*+*BB+o |
|**oBoo |
|B+ o@ . |
|o++=.*.. |
|. =o+oo+S |
| + =. ..o . |
| . o . E |
| |
| |
+----[SHA256]-----+
其中-b的參數(shù)是用來設置私鑰的長度1024的長度已經(jīng)可以滿足我們對于安全的需求了,不輸入任何文件名會在.ssh目錄下得到兩個文件:id_rsa和id_rsa.pub。
上傳公鑰到對應的服務器
使用命令ssh-copy-id可以將認證文件加載到對應的服務器上:
ssh-copy-id -i ~/.ssh/id_rsa.pub <username>@<host>
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "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
user@host's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'user@host'"
and check to make sure that only the key(s) you wanted were added.
這里會要求我們輸入遠程服務器的密碼。
修改服務器的ssh配置文件
ssh-server配置文件位于:/etc/ssh/sshd_config中,需要設置ssh-server允許使用私鑰/公鑰對的方式登錄,打開配置文件:
vim /etc/ssh/sshd_config
增加設置:
RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys
然后重啟ssh-server:
sudo /etc/init.d/ssh restart
設置完成之后就可以使用命令ssh <username>@<host>直接登錄服務器了,不需要再輸入密碼了。
其他
- 如果公鑰丟失的情況,可以使用私鑰再次生成公鑰,使用私鑰生成公鑰的命令
ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub
- 使用
ssh-copy-id上傳公鑰到服務器之后,公鑰是存放在服務器的~/.ssh/authorized_keys中。它的存在格式是一行一個公鑰,也可以手動把公鑰的內(nèi)容直接復制到服務器的authorized_keys中。使用命令cat id_rsa.pub可以獲取到公鑰的內(nèi)容。