SSH密钥登录

密码登录不安全, 万一被爆破了呢? 要假设黑客无所不能(除了破解2048位的密钥,哈哈哈)!

如果你没有密码学的相关知识也没关系, 我可以大体举个例子说明以下. 所谓公钥, 相当于一把锁, 那么私钥呢, 就是打开这把锁的钥匙了, 而且, 这把锁的钥匙只有一个, 这把钥匙也只能打开这一把锁. 我们可以理解为,钥匙的复杂度很高很高, 高到无法破解. 解密的时候呢, 公钥那边给出一个问题, 这个问题只有私钥能够解开, 拥有私钥的你在本地把题目解开之后, 把结果发送给服务器, 服务器那边一看, 哟, 答对了, 放行! 然后你就成功登陆了.

(过程大概就是这个意思, 其中涉及到密码学公钥系统的知识, 我学的不好, 只能理解个大概, 所以各位看官也就听个大概吧, 小弟哪里讲的不对, 欢迎指正!)

第一步,创建私钥和公钥:

  1. root@key:~# ssh-keygen
  2. Generating public/private rsa key pair.
  3. Enter file in which to save the key (/root/.ssh/id_rsa):
  4. Created directory '/root/.ssh'.
  5. Enter passphrase (empty for no passphrase):
  6. Enter same passphrase again:
  7. Your identification has been saved in /root/.ssh/id_rsa.
  8. Your public key has been saved in /root/.ssh/id_rsa.pub.
  9. The key fingerprint is:
  10. 91:27:cf:01:0c:64:90:dc:08:d0:f6:fa:be:a8:88:91 root@key
  11. The key's randomart image is:
  12. +--[ RSA 2048]----+
  13. |.o.o.*+o. |
  14. | o +.. .o |
  15. | . . + o |
  16. | . * . |
  17. | . S o |
  18. | .. |
  19. |E . |
  20. |o. .. |
  21. |+...o. |
  22. +-----------------+
  23. root@key:~#

就一个命令(ssh-keygen).

然后你就得到了你的公钥和私钥:

  1. root@key:~# ls .ssh/
  2. id_rsa id_rsa.pub
  3. root@key:~#

其中公钥(.pub结尾的文件)可以随意分发, 但是私钥一定要保存好, 不能通过不安全的方式带到别处.(什么是不安全的方式? 看你的安全等级咯~)

第二步, 把公钥拷贝到远程主机

  1. jsmith@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host
  2. jsmith@remote-hosts password:
  3. Now try logging into the machine, with "ssh 'remote-host'",
  4. and check in: .ssh/authorized_keys to make sure we haven't
  5. added extra keys that you weren't expecting.

这样就把公钥拷贝上去啦, 然后确认自己是否可以免密码登陆服务器, 如果可以, 就进入第三步, 如果不行呢, 那就再复制一遍.

第三步, 关闭远程服务器的密码登陆

这一步可选, 但是我还是建议你这样做.

  1. root@key:~# cat /etc/ssh/sshd_config | grep "PasswordAuthentication yes"
  2. #PasswordAuthentication yes
  3. root@key:~#

把这里改成no,并取消注释, 重启ssh服务.

嗯… 如果你不想用ssh-copy-id的话, 直接把公钥复制到远程主机的~/.ssh/authorized_keys这个文件里也是可以的,但是要保证一字不差哟~而且这种方法很方便, 如果你有多台主机, 就可以写一个脚本自己写入公钥, 改写端口, 以及禁止密码登录.