SSH設置密鑰對實現免密碼連接

SSH密鑰對讓您無需輸入密碼就能登錄到SSH伺服器,而且還能有效的防止遠程主機密碼泄漏以及被暴力破解。

步驟一 使用ssh-keygen在客戶機上生成SSH密鑰

命令用法

ssh-keygen [-t 密鑰種類] [-b 加密位數]

如果不指定密鑰種類的話,默認為2048位的RSA加密,為了安全點還是加到4096位吧。

舉例說明

[root: ~]# ssh-keygen -t rsa -b 4096 #生成一個4096位的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:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx root@CentOSThe keys randomart image is:+--[ RSA 4096]----+| Eo+. || *.o || . o O + || . o B + o || . * o S || . o o || . o || . . || ... |+-----------------+#創建密鑰對完成

步驟二 使用ssh-copy-id 把公鑰上傳到遠程主機上。

命令用法

ssh-copy-id <用戶名@主機>

舉例說明

[root: ~]# ssh-copy-id root@10.16.1.2

/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 keysPassword:Number of key(s) added: 1Now try logging into the machine, with: "ssh root@10.16.1.2"and check to make sure that only the key(s) you wanted were added.

注意:默認伺服器上的 .ssh/authorized_keys 文件存儲著合法客戶機的公鑰,如果客戶機的私鑰泄漏,應該在該文件里刪除私鑰泄漏的客戶機公鑰。

步驟三 設置伺服器

1. 確保~/.ssh目錄中的所有內容沒有對其他用戶賦予寫、執行許可權。

如果別的用戶有了對這個目錄的寫許可權,那麼他們就可以自由地往裡面添加自己的公鑰,然後自由地登錄您的賬戶了!顯然不能這樣。sshd有個自我保護的功能,當這個目錄對其他用戶賦予寫許可權時,公鑰認證將不能進行。

[root: ~]# chmod -R 600 ~/.ssh

2. 允許公鑰登錄,禁止密碼登錄。

編輯/etc/ssh/sshd_config,檢查並設置以下選項。

PubkeyAuthentication yes

AuthorizedKeysFile .ssh/authorized_keys

PasswordAuthentication no

步驟四 享受免密碼連接的快感

[root: ~]# ssh root@10.16.1.2Last login: Tue May 9 21:45:31 2017 from 10.16.1.1[root: ~]#

現在不用輸密碼就能直接登錄了。既方便又安全,爽吧!

推薦閱讀:

平時寫linux下c有哪些好用的查函數軟體?
Linux下C/C++動態庫在運行時是怎樣載入進來的?
信號(signal)和異常(exception)存在哪些異同?
有哪些對樹莓派的有趣改造和擴展應用?
Linux 系統有哪些自殺命令?

TAG:Linux | macOS | Linux运维 |