免密登录
1.首先创建本机的公钥和私钥,使用命令ssh-keygen。
默认生成的公钥名为id_rsa.pub ,私钥名为id_rsa。当然也可以通过参数 -t 来指定名称,如:ssh-keygen -t rsa
kobe@kobedeMacBook-Pro ~ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/kobe/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/kobe/.ssh/id_rsa.
Your public key has been saved in /Users/kobe/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:iaU1FUOUMKgOfdF3PAJcSEXW74FRJS3GUCiLu4CiATg kobe@kobedeMacBook-Pro.local
The key's randomart image is:
+---[RSA 2048]----+
| ==X@=.*+o.|
| o ++=.B +..|
|. . . .+o = * . |
|E . o .=.o. . o |
|.. o oo S. . . |
|. . o . . . |
| o . . . |
|. . |
| |
+----[SHA256]-----+
2.使用ssh-copy-id <用户名@主机地址>来将公钥添加到目的主机,这里可以使用-i <公钥地址> 来指定使用本机的那个公钥,如:-i ~/.ssh/id_rsa.pub 。
✘ kobe@kobedeMacBook-Pro ~ ssh-copy-id -i /Users/kobe/.ssh/id_rsa.pub kobe@192.168.107.2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/kobe/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
kobe@192.168.107.2's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'kobe@192.168.107.2'"
and check to make sure that only the key(s) you wanted were added.
注意:
如果生成的公钥和私钥不是默认名id_rsa.pub和id_rsa,那么在使用ssh登录时,也需要指定私钥文件路径。例如:生成的文件为~/.ssh/github.rsa,那么登录时需要使用ssh -i ~/.ssh/github.rsa 用户名@主机地址
别名登录
使用vim ~/.ssh/config命令编辑文件,添加如下内容:
Host kobe_service
HostName 192.168.107.2
Port 22
User kobe
IdentityFile ~/.ssh/id_rsa.pub
IdentitiesOnly yes
使用ssh <Host>登录目的主机,这里使用ssh kobe_service就相当于执行ssh root@192.168.107.2。
注释:
HostName 指定登录的主机名或IP地址
Port 指定登录的端口号
User 登录用户名
IdentityFile 登录的公钥文件
IdentitiesOnly 只接受SSH key 登录