在通過(guò)SSH訪問(wèn)服務(wù)器時(shí),使用SSH密鑰進(jìn)行認(rèn)證是尤其重要的。這樣做為服務(wù)器增加了額外的保護(hù),確保只有那些擁有密鑰的人才能訪問(wèn)服務(wù)器。
在本地機(jī)器上運(yùn)行下面命令以生成SSH密鑰:
ssh-keygen -t rsa
你會(huì)看到下面的輸出,詢問(wèn)要將密鑰寫(xiě)到哪一個(gè)文件里,并且設(shè)置一個(gè)密碼:
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): my_key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in my_key.
Your public key has been saved in my_key.pub.
The key fingerprint is:
SHA256:MqD/pzzTRsCjZb6mpfjyrr5v1pJLBcgprR5tjNoI20A
完成之后,就得到兩個(gè)文件:
my_key/p>
p>my_key.pub
接下來(lái)把my_key.pub拷貝到~/.ssh/authorized_key中
cp my_key.pub ~/.ssh/authorized_keys
然后使用下面命令將密鑰上傳到服務(wù)器:
scp -P16543 authorized_keys user@yourserver-ip:/home/user/.ssh/
至此,你就可以從這臺(tái)本地機(jī)器上無(wú)密碼地訪問(wèn)服務(wù)器了。
關(guān)閉SSH的密碼認(rèn)證
既然已經(jīng)有了SSH密鑰,那么關(guān)閉SSH的密碼認(rèn)證就會(huì)更安全了。再次打開(kāi)并編輯sshd_config,按如下設(shè)置:
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no