密钥形式登录的原理是:利用密钥生成器制作一对密钥——一只公钥和一只私钥。
将公钥添加到服务器的某个账户上,然后在客户端利用私钥即可完成认证并登录。这样一来,没有私钥,任何人都无法通过 SSH 暴力破解你的密码来远程登录到系统。
此外,如果将公钥复制到其他账户甚至主机,利用私钥也可以登录。
通过服务器来制作密钥对,一般这个服务器账户是你打算通过密钥登录的账号,执行
[~]# ssh-keygen #创建密钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/home/xx/.ssh/id_rsa): #默认就行,按enter
Created directory 'home/xx/.ssh'.
Enter passphrase (empty for no passphrase): #输入密钥锁码,或留空按enter
Enter same passphrase again: #再输一遍密钥锁码
Your identification has been saved in home/xx/.ssh/id_rsa. #私钥
Your public key has been saved in home/xx/.ssh/id_rsa.pub. #公钥
The key fingerprint is:
xxx
The key's randomart image is:
+--[ RSA 2048]----+
| o*. |
| o..+ |
|o . |
| + . |
| S |
| |
| |
| |
| |
+-----------------+
[~]#
密钥锁码在使用私钥时必须输入,这样就可以保护私钥不被盗用。当然,也可以留空,实现无密码登录。
现在,在 家目录中生成了一个 .ssh 的隐藏目录,内含两个密钥文件。id_rsa 为私钥,id_rsa.pub 为公钥。
通常使用root用户登录, 就是在**/root**目录下
键入以下命令,在服务器上安装公钥:
cd $HOME/.ssh
cat id_rsa.pub >> authorized_keys
如此便完成了公钥的安装。为了确保连接成功,请保证以下文件权限正确:
chmod 600 authorized_keys ; chmod 700 ~/.ssh
编辑 /etc/ssh/sshd_config 文件,进行如下设置:
vim /etc/ssh/sshd_config
# 启动ssh密钥登录
RSAAuthentication yes
PubkeyAuthentication yes
# 启动ssh密钥登录的快速脚本:
sudo sed -r -i '/RSAAuthentication/d' /etc/ssh/sshd_config
sudo sed -r -i '/PubkeyAuthentication/d' /etc/ssh/sshd_config
sudo sh -c "echo 'RSAAuthentication yes' >> /etc/ssh/sshd_config"
sudo sh -c "echo 'PubkeyAuthentication yes' >> /etc/ssh/sshd_config"
另外,请留意 root 用户能否通过 SSH 登录:
# root用户可以通过ssh登录(禁用改为no)
PermitRootLogin yes
# 阻止 root 用户通过 SSH 登录:
sudo sed -r -i '/PermitRootLogin/d' /etc/ssh/sshd_config
sudo sh -c "echo 'PermitRootLogin no' >> /etc/ssh/sshd_config"
当你完成全部设置,并以密钥方式登录成功后,再禁用密码登录:
# 允许密码登录(禁用改为no)
PasswordAuthentication yes
# 禁用密码登录的快速脚本:
sudo sed -r -i '/PasswordAuthentication/d' /etc/ssh/sshd_config
sudo sh -c "echo 'PasswordAuthentication no' >> /etc/ssh/sshd_config"
最后,重启 SSH 服务:
sudo service sshd restart
在新建/现有的会话中,依次点击:
1、连接
-用户身份验证
2、方法(M)
选为Pubilc Key
3、输入用户名。
4、在用户密钥栏,点击浏览(B)
选择你下载下来的密钥(id_rsa)。
确定连接即可。