4.3 利用ssh-keygen设置SSH无密码登录

线上的AWS云计算平台基于自动化运维的原则,Ansible也被部署在跳板机上,关于跳板机的介绍请大家参考第3章的内容,这里不再重复。其物理拓扑图如图4-2所示。

阅读 ‧ 电子书库

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

图4-2 跳板机物理拓扑图

为了方便自动化运维,在Ansible跳板机上用ssh-keygen设置SSH无密码登录其他客户端机器是很有必要的,具体操作步骤如下。

1)首先用命令生成一对密钥,命令如下:

ssh-keygen -t rsa

命令显示结果如下所示:

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa): (回车)

Created directory '/root/.ssh'.

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:

60:7b:a4:80:de:0d:55:d7:14:ee:39:fa:fd:c0:4a:cc root@Ansiable.example.com

The key's randomart image is:

+--[ RSA 2048]----+

| ... .oo. |

| . . . .. |

| . o o . . |

| . . = = . . |

| . . + S + |

| . + o |

| . E o |

| o o . |

| o ...|

+-----------------+

2)然后用ssh-copy-id命令将公钥分别下发到client1和client2机器上,命令如下:

ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.205

client1机器结果如下:

The authenticity of host '192.168.1.205 (192.168.1.205)' can't be established.

RSA key fingerprint is 8d:72:e5:fa:5a:c6:c1:e2:e1:00:bc:8d:6a:6f:2b:3a.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added '192.168.1.205' (RSA) to the list of known hosts.

root@192.168.1.205's password:

Now try logging into the machine, with "ssh 'root@192.168.1.205'", and check in:

.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

需要说明的是,第一次运行时,要先输入一下“yes”进行公钥验证,后续无需再次输入。

ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.206

client2机器结果如下:

The authenticity of host '192.168.1.206 (192.168.1.206)' can't be established.

RSA key fingerprint is 8d:72:e5:fa:5a:c6:c1:e2:e1:00:bc:8d:6a:6f:2b:3a.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added '192.168.1.206' (RSA) to the list of known hosts.

root@192.168.1.206's password:

Now try logging into the machine, with "ssh 'root@192.168.1.206'", and check in:

.ssh/authorized_keys

上面的步骤执行完毕以后,可以分别执行下面的命令进行验证:

ssh 192.168.1.205

ssh 192.168.1.206

因为这里本身就是以root账户执行操作的,所以无需以root@192.168.1.205的命令来执行,如果能直接以无密码进入目标主机就说明公钥分发成功,整个配置过程是没有问题的。

如果是AWS EC2机器,那么默认是不允许root连接的(只允许具有sudo权限的ec2-user用户),因此操作起来稍微麻烦一些(copy模块的用法下面会有介绍)。先查看当前用户,命令如下:

$ whoami

ec2-user

然后以ec2-user用户的身份执行Ansible命令,如下:

$ansible bidder -m copy -a "src=/usr/local/src/nagios-server.sh dest=/tmp/ owner=root group=root mode=0644 force=yes" --sudo

这里稍微说明下,因为之前已经调试好了nagios-server.sh,是利用root用户来进行调试的,所以这里需要加上--sudo,ec2-user用户是具有sudo权限的。

阅读 ‧ 电子书库

注意

最后的--sudo并非是-sudo,此处要么用-s,要么用--sudo,不然命令是会报错的。