003.SSH密钥对登陆

一 需求背景

  • master:172.24.8.30
  • client-01:172.24.8.31
  • client-01:172.24.8.32
  • client-01:172.24.8.33

在master上ssh登录client任何一台都不需要输入密码。

二 步骤

2.1 创建密钥对

ssh-master创建密钥对:

  • 私钥文件:id_rsa
  • 公钥文件:id_rsa.pub

2.2 上传公钥

将ssh-master创建的公钥id_rsa.pub上传至所有client。

2.3 导入公钥

在ssh-client将公钥导入至[需要登陆的用户家目录]/.ssh/authorized_keys

2.4 密钥登陆

master管控机直接使用密钥登陆client机器。

提示:使用ssh公钥登陆需满足至少下面两个条件:

  • .ssh目录的权限必须是700
  • .ssh/authorized_keys文件权限必须是600

三 配置实例

3.1 创建密钥

  1 [root@master ~]# ssh-keygen -t rsa
  2 
  3 Generating public/private rsa key pair.
  4 
  5 Enter file in which to save the key (/root/.ssh/id_rsa):
  6 
  7 #输出密钥保存路径,通常为默认,即/root/.ssh/id_rsa
  8 
  9 Enter passphrase (empty for no passphrase):
 10 
 11 #生成此公钥的密码,用于反向打开密钥,通常为空
 12 
 13 Enter same passphrase again:
 14 
 15 #再次确认
 16 
 17 Your identification has been saved in /root/.ssh/id_rsa.
 18 
 19 Your public key has been saved in /root/.ssh/id_rsa.pub.
 20 
 21 The key fingerprint is:
 22 
 23 06:b9:c7:41:6c:32:98:40:29:35:7b:29:7a:41:6e:7b [email protected]
 24 
 25 …………
 26 
 27 [root@master ~]# cd /root/.ssh/
 28 
 29 [root@master .ssh]# ll
 30 
 31 total 12K
 32 
 33 -rw-------. 1 root root 1.7K Aug 27 05:42 id_rsa #私钥文件
 34 
 35 -rw-r--r--. 1 root root 395 Aug 27 05:42 id_rsa.pub #公钥文件
 36 
 37 -rw-r--r--. 1 root root 176 Aug 27 04:30 known_hosts #已知的主机公钥清单

上传及导入公钥————方法A:

A-3.2 上传公钥

  1 [root@master .ssh]# scp id_rsa.pub [email protected]:/root/
  2 
  3 [root@master .ssh]# scp id_rsa.pub [email protected]:/root/
  4 
  5 [root@master .ssh]# scp id_rsa.pub [email protected]:/root/
  6 
  7 id_rsa.pub

A-3.3 导入公钥

  1 [root@client01 ~]# mkdir /root/.ssh #默认此目录不存在,需要手动创建
  2 
  3 [root@client01 ~]# cat id_rsa.pub >> /root/.ssh/authorized_keys
  4 
  5 #通过读取方式[也可以cp或mv]导入密钥
  6 
  7 [root@client01 ~]# cd /root/.ssh/
  8 
  9 [root@client01 .ssh]# chmod 600 authorized_keys
 10 
 11 #将此文件的权限改为600,其他用户都没有任何权限

上传及导入公钥————方法B:

B-3.2 创建目录

  1 [root@client01 ~]# mkdir /root/.ssh

注意:三个client都需要创建。

B-3.3 复制并导入公钥至client

  1 [root@master ~]#
  2 
  3 scp -p /root/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys
  4 
  5 scp -p /root/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys
  6 
  7 scp -p /root/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys

3.4 修改配置

  1 [root@client01 ~]# vi /etc/ssh/sshd_config
  2 
  3 RSAAuthentication yes #打开RSA认证
  4 
  5 PubkeyAuthentication yes #开启使用公钥认证
  6 
  7 AuthorizedKeysFile .ssh/authorized_keys #公钥保存位置
  8 
  9 PasswordAuthentication no #禁止使用密码验证登陆

注意:一般不需要操作,默认即可实现登录,若有其他报错则需要此操作。

3.5 登陆验证

  1 [root@master ~]# ssh 172.24.8.31
  2 
  3 Last login: Sat Jul 15 19:36:51 2017 from 172.24.8.1

猜你喜欢

转载自www.cnblogs.com/itzgr/p/9888752.html