一、生成公钥

# ssh-keygen -t rsa     ssh-keygen命令会产生一对密钥,公钥以.pub为后缀,私钥没有.pub的后缀,通过其他的工具也可以,比如用xshell的工具

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa): ./dba    

Enter passphrase (empty for no passphrase):           #是否给key指定密码,如果指定,用key登陆也需要密码

Enter same passphrase again: 

Your identification has been saved in ./dba.

Your public key has been saved in ./dba.pub.

The key fingerprint is:

SHA256:+WMNBvZ1Vs3Qlr6dqlHNpcMyRiBrwdJyDMGKNiNBCjk root@xxx.localdomain.com

The key's randomart p_w_picpath is:

+---[RSA 2048]----+

|oo   .o*o .   .++|

|E     + =+ .   o=|

|.o . . +=   o +..|

|. = .  o + o +oo.|

| o o    S + +.+o+|

|         o +.o +.|

|          +.. .  |

|         . ...   |

|           ..    |

+----[SHA256]-----+



私钥的权限是600的

# ll dba*

-rw-------. 1 root root 1766 Nov  3 16:55 dba

-rw-r--r--. 1 root root  408 Nov  3 16:55 dba.pub


基于key认证的条件:

1、将公钥拷贝到目标机器的.ssh/authorized_keys 中 


ssh-copy-id -i .ssh/id_rsa.pub  root@xx.xx.xx.xx #可以快速实现条件1


cat .ssh/authorized_keys 



authorized_keys的权限应该是600的

.ssh 目录的权限是700

# ll .ssh/

total 4

-rw-------. 1 root root 1383 Nov  3 17:20 authorized_keys



2、登陆的时候用私钥去登陆

ssh [-i ~/.ssh/id_dsa, ~/.ssh/id_rsa] root@xx.xx.xx.xx  #默认会用.ssh的私钥去登陆



3、如果制做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