一、生成公钥
# 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 [email protected]
The key‘s randomart image 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 [email protected] #可以快速实现条件1
cat .ssh/authorized_keys
ssh-dss AAAAB3NzaC1kc3MAAACBAOdfvdRTTDs74qKqQJl3iBcojGgJzpy2HA/mWqdqMlafst0MUHV9m2lgaEdRtZlcU+kxDSblgSrY6upZBk36N+BH/YKreem7E2WI/ufB5yemm4RtErJKLSJmvGjcPdRQ9RVpaDxzU16kiHqc+MKbtgM02RJ8xOjfV/Ohmzmq4tW1AAAAFQCQeZUBce7PljpqUiJ7dm5FayEDMwAAAIEAu182yDzNMprOO9hxO1vfWyBrdlceYujIP/RFMuWcOXBkq5PsUUZV8gvm3RY9oMWRaew/9qZrss2aufeEngiaTj9W4MIewA5V/Nzq4bVDJjsl4Hv1iWtAiikB4aTZXjRQaEQlfcEYvpzmS4+IEzbFOb2epkfXx2QFeuVfSHUlzvIAAACAQ5vZkUMH7VY5RKUYP0pPS1RDA9oKaviB2pKXL3SwP2eGeFOS+0l83gdBfEE5wnow4mGaeG2zkzR3oP5GyNO8VUo0wvl4qRxgxIHtS1225F0VcWvFoJKS65SS9Ps3wAOnizvff+tdaivUK2PiurONbRpxPPvkp6p8ZoWBBPUHLhs=
authorized_keys的权限应该是600的
# ll .ssh/
total 4
-rw-------. 1 root root 1383 Nov 3 17:20 authorized_keys
2、登陆的时候用私钥去登陆
ssh [-i ~/.ssh/id_dsa, ~/.ssh/id_rsa] [email protected] #默认会用.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