配置ssh无密码登录服务器

Configure the ssh certificate login server

Posted by alovn on April 22, 2019

ssh 是一个专为远程登录会话和其他网络服务提供安全性的协议。 默认ssh连接是需要密码认证的,可以通过添加rsa认证避免密码输入。服务端上存放公钥,客户端保留私钥。

创建公钥

1
[root@s1001]# ssh-keygen -t rsa

执行后,默认会在~/.ssh/目录下生成 id_rsa 和 id_rsa.pub 文件

上传公钥

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@s1001]# ssh-copy-id [email protected]

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 's1002.lab.org' can't be established.
Are you sure you want to continue connecting (yes/no)? yes
/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
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

通过这个命令会把上面步骤生成的公钥 id_rsa.pub 文件上传到 s1002.lab.org 这台服务器下 /root/.ssh/authorized_keys

配置私钥

默认将id_rsa放入ssh客户端机器的 ~/.ssh/目录下即可。

如果客户端机器有多个ssh证书文件的话,需要配置 ~/.ssh/config(不存在的话需要创建):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Host github
  HostName github.com
  User [email protected]
  IdentityFile ~/.ssh/github/github_rsa

Host s1001
  HostName s1001.lab.org
  User root
  IdentityFile ~/.ssh/lab/id_rsa

Host s1002
  HostName s1002.lab.org
  User root
  IdentityFile ~/.ssh/lab/id_rsa

然后只需要 ssh [email protected] 就可以登录了。