天天看点

设置 ssh 使用public key 免密码登录

第一步,生成自己公钥, 私钥

1:  ssh-keygen -t rsa      
2:         
3:  root@yjlml:~# ssh-keygen -t rsa      
4:  Generating public/private rsa key pair.      
5:  Enter file in which to save the key (/root/.ssh/id_rsa):       
6:  Enter passphrase (empty for no passphrase):       
7:  Enter same passphrase again:       
8:  Your identification has been saved in /root/.ssh/id_rsa.      
9:  Your public key has been saved in /root/.ssh/id_rsa.pub.      
10:  The key fingerprint is:      
11:  3e:6e:d9:12:7c:f8:6f:18:f6:65:cb:6e:16:4f:83:43 root@yjlml      
12:  The key's randomart image is:      
13:  +--[ RSA 2048]----+      
14:  |                 |      
15:  |                 |      
16:  |                 |      
17:  |             E   |      
18:  |       .S.  . .  |      
19:  |       .+ +  o+..|      
20:  |        oB + +.=.|      
21:  |       .+.+ o = .|      
22:  |       ... o.+.  |      
23:  +-----------------+      

中间连续按几次回车, 使用默认文件名, 并不输入密码。

二, 把你的公钥,拷贝到远程机器的  “~/.ssh/authorized_keys” 文件中。

刚才生成的公钥在: ~/.ssh/id_rsa.pub,  里面是文本,直接复制出来,粘贴到远程的“~/.ssh/authorized_keys” 文件中即可。 如果没有这个文件,自己新建一个。

这个文件可以保存多个公钥,只需要连续放在里面就可以了。

拷贝的方法有很多。自己想办法。

拷贝完成之后,重启一下ssh服务。

service ssh  restart

然后测试是否成功:

1:  root@yjlml:~# ssh root@190.***.***.***  -p 22   ls      

这里故意指定了一个端口22, 其实可以省略的。如果你的ssh端口不是22可以这样指定。

这句话是在远程执行一个 命令 ls, 看能不能执行成功。

如果能看到ls的结果。那就是成功了。

三, 错误处理

如果访问不成功,请检查远程机器的 “/etc/ssh/sshd_config ”文件:

找到其中的这一段。

6:  RSAAuthentication yes      
7:  PubkeyAuthentication yes      
8:  #AuthorizedKeysFile    %h/.ssh/authorized_keys      
设置 ssh 使用public key 免密码登录

注意,必须开启 公钥认证, 检查公钥文件。

改完之后,重启远程ssh服务: service ssh  restart

欢迎大家访问我的个人独立博客: http://byneil.com

来自 Neil的博客 http://byNeil.com