ansible远程执行命令
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更改配置文件
vi /etc/ansible/hosts //增加
127.0.0.1
172.7.15.111
说明:testhost为主机组名字,自定义的。下面两个ip为组内的机器ip。
1
2
3
4
# vim /etc/ansible/hosts
127.0.0.1
172.7.15.111
针对这个组执行操作(比如远程执行一个w命令)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# ansible testhosts -m command -a 'w'
172.7.15.111 | SUCCESS | rc=0 >>
00:32:39 up1:20,2 users,load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 172-7-15-100.lig 23:13 8:09 0.09s0.09s -bash
root pts/1 web9.gz.com 00:32 0.00s0.12s0.00s /bin/sh -c LANG
127.0.0.1 | SUCCESS | rc=0 >>
00:32:38 up1:21,4 users,load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 172-7-15-100.lig 23:13 1.00s0.21s0.01s ssh 127.0.0.1
root pts/1 localhost 00:28 1.00s0.05s0.01s ssh 127.0.0.1
root pts/2 localhost 00:30 1.00s0.77s0.54s /usr/bin/python
root pts/5 localhost 00:32 0.00s0.08s0.00s /bin/sh -c LANG
远程执行一个命令ls
1
2
3
4
5
6
7
8
9
10
# ansible testhosts -m command -a 'ls'
172.7.15.111 | SUCCESS | rc=0 >>
anaconda-ks.cfg
install.log
install.log.syslog
127.0.0.1 | SUCCESS | rc=0 >>
anaconda-ks.cfg
install.log
install.log.syslog
1
2
3
4
5
6
7
8
9
10
# ansible testhosts -m command -a 'hostname'
172.7.15.111 | SUCCESS | rc=0 >>
web10.gz.com
127.0.0.1 | SUCCESS | rc=0 >>
web9.gz.com
# ansible web10.gz.com -m command -a 'hostname'
web10.gz.com | SUCCESS | rc=0 >>
web10.gz.com
执行的过程难免加管道符
第一种方法不行第二种加个shell就哦了
1
2
3
4
5
6
7
8
9
# ansible web10.gz.com -m command -a 'cat /etc/passwd|grep root'
web10.gz.com | FAILED | rc=1 >>
cat: /etc/passwd|grep: 没有那个文件或目录
cat: root: 没有那个文件或目录
# ansible web10.gz.com -m shell -a 'cat /etc/passwd|grep root'
web10.gz.com | SUCCESS | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
如果有提示一下信息时,第一时间检查防火墙有没有关,密钥有没有配对
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# ansible testhosts -m command -a 'w'
The authenticity of host '172.7.15.106 (172.7.15.106)' can't be established.
RSA key fingerprint is 67:31:c8:49:f6:17:59:88:e3:4a:61:a8:2b:44:20:55.
Are you sure you want to continue connecting (yes/no)? 172.7.15.111 | UNREACHABLE! => {
"changed": false,
"msg": "SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue",
"unreachable": true
}
172.7.15.106 | UNREACHABLE! => {
"changed": false,
"msg": "SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue",
"unreachable": true
}
页:
[1]