Ansible 批量管理linux机器

一、准备环境

机器:centos6.9

1、安装ansible

[root@localhost ~]# yum -y install ansible
Loaded plugins: fastestmirror
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: mirrors.btte.net
 * epel: mirrors.tuna.tsinghua.edu.cn
 * extras: mirrors.btte.net
 * updates: mirrors.tuna.tsinghua.edu.cn
Package ansible-2.3.1.0-1.el6.noarch already installed and latest version
Nothing to do

本机已经安装完ansible

2、批量配置免登录。

#!/usr/bin/expect
for p in $(cat /data/shell/list)
do
password=$(echo "$p"|cut -f1 -d":")
ip=$(echo "$p"|cut -f2 -d":")
expect -c "
spawn ssh-copy-id -i  root@$ip  
expect {  
\"*yes/no*\" {send \"yes\r\"; exp_continue}  
\"*password*\" {send \"$password\r\"; exp_continue}  
\"*Password*\" {send \"$password\r\";}  
}  
"  
done 

需要一个list文件,里面记录了需要更新的主机以及对应密码,格式如下:

123456:192.168.1.20  
345676:192.168.2.20

密码:主机名 ,以分号分隔。
expect命令如果没有的话,需要提前安装

运行脚本后,显示如下:

[root@localhost shell]# sh expect.sh 
spawn ssh-copy-id -i root@192.168.6.189
spawn ssh-copy-id -i root@192.168.6.89
The authenticity of host '192.168.6.89 (192.168.6.89)' can't be established.
RSA key fingerprint is 04:46:a5:a6:93:74:e1:d2:58:a1:3d:65:63:43:72:d8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.6.89' (RSA) to the list of known hosts.
root@192.168.6.89's password: 
Now try logging into the machine, with "ssh 'root@192.168.6.89'", and check in:

  .ssh/authorized_keys

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

spawn ssh-copy-id -i root@10.18.99.62
The authenticity of host '10.18.99.62 (10.18.99.62)' can't be established.
RSA key fingerprint is 04:46:a5:a6:93:74:e1:d2:58:a1:3d:65:63:43:72:d8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.18.99.62' (RSA) to the list of known hosts.
root@10.18.99.62's password: 
Now try logging into the machine, with "ssh 'root@10.18.99.62'", and check in:

  .ssh/authorized_keys

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

配置完毕。

二、配置ansible

1、编辑配置文件、添加用户组。

编辑 /etc/ansible/hosts
[all]
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
192.168.1.11

2、执行简单命令。

ansible all -m shell -a 'uptime'

192.168.1.3 | SUCCESS | rc=0 >>
 14:08:24 up 1 day, 22:26,  1 user,  load average: 0.06, 0.12, 0.13

192.168.1.2 | SUCCESS | rc=0 >>
 14:10:02 up 3 days,  3:36,  2 users,  load average: 0.04, 0.04, 0.05

3、成功执行命令并返回。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • root@softwareluke-Lenovo:/home/softwareluke# virt-manager...
    燕京博士阅读 4,030评论 0 0
  • ansible 系统架构 ansible简介ansible是新出现的自动化运维工具,ansible是一个配置管理和...
    运维阿文阅读 13,229评论 1 53
  • 阳光打在窗玻璃上 声势浩大却没声息 留下的痕迹很温暖 它闯过无垠虚空后 只为了与你的肌肤 来一次激情的碰触 无怨无...
    老爷爷不是我阅读 1,332评论 0 1
  • 糖月阳阅读 1,482评论 0 0