配置ssh免密码登陆服务器

安素 2019年09月19日 27次浏览

免密登录的目的

有时候为了同步文件,或者执行远程命令时,需要脚本执行,但是登陆其他服务器需要输入密码才能执行,就需要配置面密码登录

ssh-keygen和ssh-copy-id实现免密登录

  • 首先,说明一下我们要做的是,A服务器的用户免密码登录B服务器 在不建立ssh信任关系的情况下,从A服务器登陆到B服务器是需要输入密码的
[root@ansu ~]# ssh root@10.43.0.32
root@10.43.0.32's password:
  • 现在我们在服务器A上使用ssh-keygen生成本机的私钥和公钥,输入ssh-keygen -t rsa 一路回车就可以了:
[root@ansu ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:WvYgA1u9dYQ2QNWw/gx+wDqH1KMkFpLdUdKG8HYcwJk root@dxhedugov-2
The key's randomart image is:
+---[RSA 2048]----+
|      .+*X=+.    |
|     o +E+*+.    |
|    + + =o=..    |
|     = o B .     |
|    . = S B      |
|     . X B *     |
|      . = + +    |
|         o .     |
|                 |
+----[SHA256]-----+
  • 查看当前用户目录下的文件夹,多出一个.ssh的隐藏文件夹,文件夹内有两个文件
[root@ansu ~]# ll -a ~/.ssh
总用量 12
drwx------. 2 root root   73 9月  19 11:17 .
dr-xr-x---. 4 root root  225 9月  19 11:10 ..
-rw-------. 1 root root 1679 9月  19 11:15 id_rsa
-rw-r--r--. 1 root root  398 9月  19 11:15 id_rsa.pub
  • 文件说明:
文件描述
id_rsa私钥文件
id_rsa.pub公钥文件
  • 接下来就是将公钥下发给服务器B,下发公钥,有两种方式,一种是使用ssh-copy-id,另一种是直接将公钥的字符串复制到~/.ssh/authorized_keys中.下面我们展示这两种的使用方式.
  1. ssh-copy-id
[root@ansu ~]# ssh-copy-id root@10.43.0.33
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.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
root@10.43.0.33's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@10.43.0.33'"
and check to make sure that only the key(s) you wanted were added.
  1. 先将公钥文件id_rsa.pub传输到服务器B上,然后将文件导入到~/.ssh/authorized_keys
[root@ansu ~]# cat ~/.ssh/id_rsa.pub | ssh -p 22 root@10.43.0.33 'cat >> ~/.ssh/authorized_keys'

另外需要注意,.ssh目录的权限为700,其下文件authorized_keys和私钥的权限为600。否则会因为权限问题导致无法免密码登录。我们可以看到登陆后会有known_hosts文件生成。