使用ssh-keygen和ssh-copy-id使用SSH免密码登录

ssh-keygen   产生公钥与私钥

ssh-copy-id   将本机的公钥复制到远程机器的authorized_keys文件中,

ssh-copy-id   也会给远程主机的用户主目录(home)和~/.ssh, ~/.ssh/authorized_keys设置合适的权限

1、用ssh-keygen 在本地主机上创建公钥和私钥

# ssh-keygen

# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ylo/.ssh/id_rsa): mykey
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in mykey.
Your public key has been saved in mykey.pub.
The key fingerprint is:
SHA256:GKW7yzA1J1qkr1Cr9MhUwAbHbF2NrIPEgZXeOUOz3Us ylo@klar
The key's randomart image is:
+---[RSA 2048]----+
|.*++ o.o.        |
|.+B + oo.        |
| +++ *+.         |
| .o.Oo.+E        |
|    ++B.S.       |
|   o * =.        |
|  + = o          |
| + = = .         |
|  + o o          |
+----[SHA256]-----+
#

公钥文件保存在 ~/.ssh/mykey.pub    私钥保存在 ~/.ssh/mykey

2、用ssh-copy-id将本地公钥复制到远程主机

# ssh-copy-id –i ~/.ssh/mykey.pub   user@remote-host

user@local-host$ ssh-copy-id -i ~/.ssh/mykey.pub remote-host
user@remote-host's password:
Now try logging into the machine, with "ssh 'remote-host'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.

ssh-copy-id 将key写到远程主机 ~/.ssh/authorized_key文件中

3.直接登录远程主机

# ssh remote-host

ssh 不再询问密码

参考网址:

https://www.ssh.com/ssh/copy-id

http://www.cnblogs.com/chuanheng/p/ssky_keygen.html

原文地址:https://www.cnblogs.com/walkman-sky/p/8600427.html