免密登錄
1.首先創(chuàng)建本機的公鑰和私鑰,使用命令ssh-keygen。
默認生成的公鑰名為id_rsa.pub ,私鑰名為id_rsa耿眉。當然也可以通過參數(shù) -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
命令編輯文件铛纬,添加如下內(nèi)容:
Host kobe_service
HostName 192.168.107.2
Port 22
User kobe
IdentityFile ~/.ssh/id_rsa.pub
IdentitiesOnly yes
使用ssh <Host>
登錄目的主機,這里使用ssh kobe_service就相當于執(zhí)行ssh root@192.168.107.2唬滑。
注釋:
HostName 指定登錄的主機名或IP地址
Port 指定登錄的端口號
User 登錄用戶名
IdentityFile 登錄的公鑰文件
IdentitiesOnly 只接受SSH key 登錄