linux centos设置密钥并且使用密钥登录

来源:互联网 发布:开淘宝店挣钱么 编辑:程序博客网 时间:2024/06/05 02:15

服务器端生产密钥(一直默认回车就好,当然你也可以重新命名):
[root@localhost ~]# ssh-keygen -t rsa

然后会在 root目录下自动生产.ssh目录和公钥(id_rsa.pub)私钥(id_rsa)
[root@localhost ~]# cd /root/.ssh
[root@localhost .ssh]# ll
total 8
-rw——- 1 root root 1675 Jun 8 19:09 id_rsa
-rw-r–r– 1 root root 408 Jun 8 19:09 id_rsa.pub

新建一个公钥文件,设置权限为600
[root@localhost .ssh]# touch authorized_keys
[root@localhost .ssh]# chmod 600 authorized_keys

将公钥拷贝到authorized_keys
[root@localhost .ssh]# cat id_rsa.pub >> authorized_keys

修改配置
[root@localhost /]# vi /etc/ssh/sshd_config
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
重启服务(只有root有权限)
[root@localhost /]# service sshd restart

将私钥拷贝到我们的客户端(可以使用filezilla,如果用的是MobaXterm连接服务器的,直接就有文件处理的功能,我用的时候CRT)

用客户端登录,如果你用的是CRT或者 YUTT什么的可能会包下面这个错。
Public-key authentication with the server for user root failed. Please verify username and public/private key pair.

解决:http://blog.csdn.net/u014803081/article/details/72911036

到现在,可以用密钥登录,但是密码还是能登录,所以要去掉密码登录。
修改配置(普通用户)PermitRootLogin yes
[root@localhost /]# vi /etc/ssh/sshd_config
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
重启服务(只有root有权限)
[root@localhost /]# service sshd restart
修改配置(root用户)
[root@localhost /]# vi /etc/ssh/sshd_config
PermitRootLogin no
重启服务(只有root有权限)
[root@localhost /]# service sshd restart

到这里,看起来是好了,其实没有。我们会发现root禁止了;其他用户密码不能登录而且密钥也不能登录,这是因为刚才密钥文件只生成在root用户下,所以要拷贝到其他用户下面(创建用户的指令,在指定目录下创建一个名为ydh的用户:useradd -d /home/ydh -m ydh,我已经有一个service用户了,就不用再建了)
[root@localhost ~]# cp -rf .ssh /home/service
到service目录下,将文件权限修改
[root@localhost ~]# cd /home/service
[root@localhost service]# chown service:service -R .ssh
这样service就能用密钥登录了。

这样做是比较麻烦的,我们可以刚开始的时候就直接用service操作。

原创粉丝点击