SSH公钥认证登录
概述:
SSH登录的认证方式分为两种,一种是使用用户名密码的方式,另一种就是通过公钥认证的方式进行访问,
用户名密码登录的方式没什么好说的,本文主要介绍通过公钥认证的方式进行登录。
思路:
在客户端生成公钥和私钥,将公钥上传至服务器上后进行无密码访问。
环境:
客户机:192.168.129.129
服务机:192.168.129.128
步骤:
(1)在客户端生成公钥与私钥
root@kali2:~/.ssh# ssh-keygen -t 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: e9:66:e1:c9:51:9e:cb:1e:ec:07:8c:e9:9a:a5:19:ff root@kali2 The key's randomart image is: +---[RSA 2048]----+ | | | | | . | | + . | | S+o | | +o*o. | | ..O =. | | X.o .. | | =...E. | +-----------------+
(2)查看已生成的公钥私钥
root@kali2:~/.ssh# ls -l total 12 -rw------- 1 root root 1679 Jul 19 03:45 id_rsa -rw-r--r-- 1 root root 392 Jul 19 03:45 id_rsa.pub -rw-r--r-- 1 root root 444 Jul 19 03:31 known_hosts
(3)将公钥id_rsa.pub发送到服务器上
root@kali2:~/.ssh# scp -r /root/.ssh/id_rsa.pub root@192.168.129.128:/root/.ssh root@192.168.129.128's password: id_rsa.pub 100% 392 0.4KB/s 00:00
(4)进入服务器的/root/.ssh目录下,将id_rsa.pub内容重定向到同目录下的文件authorized_keys里
[root@localhost .ssh]# ls id_rsa.pub known_hosts [root@localhost .ssh]# touch authorized_keys [root@localhost .ssh]# ls authorized_keys id_rsa.pub known_hosts [root@localhost .ssh]# cat id_rsa.pub >> ./authorized_keys [root@localhost .ssh]# ls -l total 12 -rw-r--r--. 1 root root 392 Jul 19 15:54 authorized_keys -rw-r--r--. 1 root root 392 Jul 19 15:50 id_rsa.pub -rw-r--r--. 1 root root 177 Jul 19 14:41 known_hosts
(5) 此时在客户机访问服务机可不输入密码了
root@kali2:~/.ssh# ssh 192.168.129.128 Last failed login: Tue Jul 19 15:35:25 CST 2016 from 192.168.129.129 on ssh:notty There was 1 failed login attempt since the last successful login. Last login: Tue Jul 19 15:33:54 2016 from 192.168.129.129 [root@localhost ~]#
注意事项:
在使用公钥认证之前,先检查一下服务器的ssh配置文件/etc/ssh/sshd_config
RSAAuthentication yes # 启用 RSA 认证,默认为yes
PubkeyAuthentication yes # 启用公钥认证,默认为yes
如果安全性要求高,修改一下服务器的配置文件/etc/sshd/sshd_config,
禁用密码登录,只能通过公钥方式登录。
PasswordAuthentication no