简单3步设置SSH的免密码登陆

如果经常使用远程服务器,频繁输入密码是一件头疼的事情。利用公钥和私钥配对的方式,可以利用3个简单的步骤实现免密码登陆。

第0步:alias登陆信息

这步适用于连用户名和服务器名都懒得输入的人,或者管理多个远程服务器的人,简单的,在.bashrc或者.zshrc文件中添加如下alias(some_words请任意设置你喜欢的简写):

alias some_words='ssh user@remote_host'

第1步:公-私钥对生成

在你自己的电脑上用ssh-keygen生成公钥和私钥对:

user@local_host$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):[Enter key]
Enter passphrase (empty for no passphrase): [Press enter key]
Enter same passphrase again: [Pess enter key]
Your identification has been saved in /home/user/.ssh/id_rsa. [你的私钥]
Your public key has been saved in /home/user/.ssh/id_rsa.pub. [你的公钥]
The key fingerprint is:
33:b3:fe:af:95:95:18:11:31:d5:de:96:2f:f2:35:f9 user@local_host

第2步:上传公钥

将生成的公钥添加到远程服务器的~/.ssh/authorized_key目录下面:

user@local_host$ ssh-copy-id -i ~/.ssh/id_rsa.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.

第3步:享受无密码登陆

享受无密码登陆的快感。

user@local_host$ ssh remote-host
Last login: Sun Sep16 17:22:33 2015 from 192.168.1.2
[Note: SSH did not ask for password.]
user@remote_host$ [Note: You are on remote-host here]

但是如果出现如下信息,也不要惊慌:

@@@@WARNING: UNPROTECTED PRIVATE KEY FILE!@@@@
Permissions 0670 for '/home/user/.ssh/id_rsa' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "/home/user/.ssh/id_rsa": bad permissions

这表明你的私钥太容易被人修改了,简单的修改权限即可:

chmod 600 ~/.ssh/id_rsa

附加步骤-多个Key登陆不同服务器的管理

如果管理不同的服务器用于多个不同的key,那么就需要进行区分。首先生成key的时候进行区分:

Enter file in which to save the key (/home/user/.ssh/id_rsa): /home/user/.ssh/id_rsa_xxx #用xxx进行不同的key区分

然后查看系统ssh-key代理并添加所有的私钥到ssh-agent:

ssh-add -l
Could not open a connection to your authentication agent.
#该提示表示系统代理无任何key,执行如下操作
exec ssh-agent bash #bash换成zsh如果你用的话
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_xxx

在.ssh目录创建config文件(chmod 600)并写入配置:

vim ~/.ssh/config
# host1
Host host1
HostName ip or address
User username
IdentityFile ~/.ssh/id_rsa

# host2
Host host2  # 前缀名可以任意设置
HostName ip or adress #例如github.com
User username #例如git
IdentityFile ~/.ssh/id_rsa_xxx

最后测试是否可以连接:

ssh -T user@xxx.com        # 测试host1连接
ssh -T git@github.com    # 测试host2连接

最后就是愉快的工作了!


除非特别声明,文章均为牛会飞的博客原创,遵循署名-非商业使用-相同方式共享授权协议
转载请注明出处: https://blogfei.com/3-steps-to-get-ssh-login-without-password/

暂无评论