頻繁登錄Linux服務器時,使用ssh <username>@<host>
的方式登錄,但是每次都需要輸入密碼是件很麻煩的事。我們還可以使用私鑰/公鑰對的方式在免密碼登錄服務器。
首先需要在遠程服務器中安裝ssh-server
服務,才可以使用ssh登錄。如果沒有的話可以使用命令直接安裝ssh-server
,可以以Ubuntu為例安轉ssh-server
:
sudo apt-get install openssh-server
生成私鑰/公鑰對
使用命令ssh-kengen
可以生成私鑰/公鑰對,私鑰/公鑰對的生成算法有兩種RSA和DSA。
RSA是非對稱加密算法,可以用來加密和簽名
DSA(Digital Signature Algorithm)只可以用來數字簽名的算法
這里使用RSA算法生成私鑰/公鑰對。需要確認.ssh
目錄是否存在,如果不存在的話創建該目錄:
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.localThe key's randomart image is:+---[RSA 1024]----+|*+*BB+o ||**oBoo ||B+ o@ . ||o++=.*.. ||. =o+oo+S || + =. ..o . || . o . E || || |+----[SHA256]-----+
其中-b
的參數是用來設置私鑰的長度1024的長度已經可以滿足我們對于安全的需求了,不輸入任何文件名會在.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 keysuser@host's password:Number of key(s) added: 1Now 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>
直接登錄服務器了,不需要再輸入密碼了。
其他
1.如果公鑰丟失的情況,可以使用私鑰再次生成公鑰,使用私鑰生成公鑰的命令
ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub
2.使用ssh-copy-id
上傳公鑰到服務器之后,公鑰是存放在服務器的~/.ssh/authorized_keys
中。它的存在格式是一行一個公鑰,也可以手動把公鑰的內容直接復制到服務器的authorized_keys中。使用命令cat id_rsa.pub
可以獲取到公鑰的內容。