一、生成公钥
ssh-keygen命令会产生一对密钥,公钥以.pub为后缀,私钥没有.pub的后缀,通过其他的工具也可以,比如xshell的工具。
ssh-keygen #建立密钥对
# 输出
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): #密钥存放位置
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): #输入密钥密码(如果设置了,通过key登录也需要密码),或直接按 Enter 留空
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:
0f:d3:e7:1a:1c:bd:5c:03:f1:19:f1:22:df:9b:cc:08 root@host
公私钥的权限如下
ll id_rsa*
-rw-------. 1 root root 1766 Nov 3 16:55 id_rsa
-rw-r--r--. 1 root root 408 Nov 3 16:55 id_rsa.pub
二、 基于key认证登录
1、将公钥内容拷贝到目标机器 .ssh/authorized_keys
- 快速拷贝
ssh-copy-id -i .ssh/id_rsa.pub root@xx.xx.xx.xx
cat .ssh/authorized_keys
- 手动拷贝
如果本机就是目标服务器,直接追加公钥内容添加到 .ssh/authorized_keys 文件即可
cat id_rsa.pub >> authorized_keys
.ssh 目录的权限应该是700,authorized_keys是600
[root@host .ssh]$ chmod 600 authorized_keys
[root@host .ssh]$ chmod 700 ~/.ssh
2. 使用私钥登录
- 将私钥传至源服务器 /home/dba/.ssh目录
如果是在客户端生成的公私钥,该步可省略(因为已有私钥了)
mkdir -p .ssh && chmod 700 .ssh
mv id_rsa .ssh/ && chmod 600 .ssh/id_rsa
执行 ssh dba@xx.xx.xx.xx 时默认会用.ssh的私钥去登陆
如果创建key时指定了密码,用key登录也是需要密码的
ssh -i dba xx.xx.xx.xx
Enter passphrase for key 'dba':
Last login: Fri Nov 3 17:07:18 2017 from xx.xx.xx.xx
三、 图解原理
参考