ssh訪問可以通過兩種形式進行登錄:
- 安全密碼認證:登錄username@remotehost,輸入對應username的密碼,該密碼會被加密發給remotehost,接下來,remotehost會從密碼數據庫中進行匹配,如果成功,則登錄成功。
- 密鑰訪問:localhost通過ssh-keygen來生成公鑰密鑰對,如果他想訪問一個remotehost,則只需要將公鑰添加到remotehost的~/.ssh/authorized_keys中,接下來,當localhost通過ssh登錄username@remotehost時,remotehost會生成一個隨機數,通過autrorized_keys中的公鑰們生成一系列數值發給localhost,localhost會通過自己的私有密鑰解密發過來的一系列數值(當然,只有用對應的公鑰生成的數值纔會被正常解密),隨後,localhost將解密後的數值發回去,remotehost若發現發回來的數值是原先產生的隨機數時,便會允許該localhost訪問。當然,如果localhost生成的rsa密鑰是需要密碼的話,接下來還要輸入該密碼。
接下來,我就來舉例如何通過ssh密鑰實現自動訪問。
- 配置localhost:如果還沒有密鑰公鑰對生成,則先用ssh-keygen指令生成一個密鑰對。
- wenry@MyHome:~$ssh-keygen -t rsa
- Generating public/private rsa key pair.
- Enter file in which to save the key (/home/wenry/.ssh/id_rsa):
- Created directory '/home/wenry/.ssh'.
- Enter passphrase (empty for no passphrase):
- Enter same passphrase again:
- Your identification has been saved in /home/wenry/.ssh/id_rsa.
- Your public key has been saved in /home/wenry/.ssh/id_rsa.pub.
- The key fingerprint is:
- 0f:c5:e1:e9:b1:a4:f2:e0:ee:9f:0a:bc:c7:c8:c8:b9 wenry@MyHome
- The key's randomart image is:
- +--[ RSA 2048]----+
- | . |
- | o o |
- | B |
- | = o |
- | o S o |
- | . . + o |
- | . +oo. . . |
- | + o+o . |
- | E..o+oo |
- +-----------------+
在輸入ssh-keygen指令後,只需要連續輸入三個回車鍵,就可以生成不需要密碼的密鑰公鑰對了,從而實現自動訪問。
- 配置remotehost:將localhost的id_rsa.pub內容附加到remotehost的/home/username/.ssh/authorized_keys中。
這樣配置之後,就可以在localhost上ssh username@hostname,無需密碼直接訪問了。