Linux自动化工具之Ansible执行远程命令
2020-02-21自动化运维90root252°c
A+ A-ansible testhost -m command -a ‘w’ 这样就可以批量执行命令了,这里的testhost为主机组名,-m 后边是模块的名字,-a后面是命令,当然我们也可以直接写一个ip,针对某一台机器来执行命令 ansible 127.0.0.1 -m command -a ‘hostname’ 错误:”msg”:”Aborting,target user selinux but python bindings(libselinux-python)arenot installed!” 解决:yum install -y libselinux-python 还有一个模块就是shell同样也可以实现 ansible testhost -m shell -a ‘w’
一. Ansible更改配置文件
[[email protected] ~]# vim /etc/ansible/hosts [testhosts] 127.0.0.1 101.200.148.30
说明:testhost为主机组名字,自定义的。下面两个ip为组内的机器ip。
针对这个组执行操作(比如远程执行一个w命令)
[[email protected] ~]# ansible testhosts -m command -a 'w' 127.0.0.1 | SUCCESS | rc=0 >> 04:00:25 up 7:03, 3 users, load average: 0.09, 0.04, 0.05 USER TTY FROM [email protected] IDLE JCPU PCPU WHAT root pts/0 124.202.191.135 03:51 1.00s 0.00s 0.00s ssh 127.0.0.1 root pts/1 127.0.0.1 03:59 1.00s 0.66s 0.47s /usr/bin/python root pts/3 127.0.0.1 04:00 0.00s 0.07s 0.00s /bin/sh -c LANG 101.200.148.30 | SUCCESS | rc=0 >> 04:00:26 up 4:37, 2 users, load average: 0.00, 0.01, 0.05 USER TTY FROM [email protected] IDLE JCPU PCPU WHAT root pts/0 124.202.191.135 03:51 8:40 0.00s 0.00s -bash root pts/1 101.200.131.184 04:00 1.00s 0.08s 0.00s /bin/sh -c LANG
远程执行一个命令ls
[[email protected] ~]# ansible testhosts -m command -a 'ls' 101.200.148.30 | SUCCESS | rc=0 >> 127.0.0.1 | SUCCESS | rc=0 >>
远程执行一个hostname
[[email protected] ~]# ansible testhosts -m command -a 'hostname' 101.200.148.30 | SUCCESS | rc=0 >> web10.gz.com 127.0.0.1 | SUCCESS | rc=0 >> web9.gz.com
根据具体的机器执行
[[email protected] ~]# ansible 101.200.148.30 -m command -a 'hostname' 101.200.148.30 | SUCCESS | rc=0 >> web10.gz.com
执行的过程难免加管道符。 第一种方法不行第二种加个shell就哦了
[[email protected] ~]# ansible testhosts -m command -a 'cat /etc/passwd|grep root' 101.200.148.30 | FAILED | rc=1 >> cat: /etc/passwd|grep: No such file or directory cat: root: No such file or directory 127.0.0.1 | FAILED | rc=1 >> cat: /etc/passwd|grep: No such file or directory cat: root: No such file or directory [[email protected] ~]# ansible testhosts -m shell -a 'cat /etc/passwd|grep root' 101.200.148.30 | SUCCESS | rc=0 >> root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin 127.0.0.1 | SUCCESS | rc=0 >> root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin