侧边栏壁纸
  • 累计撰写 223 篇文章
  • 累计创建 205 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

ansible 远程执行命令

zhanjie.me
2018-08-03 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

ansible 远程执行命令

​ ​ 更改配置文件

​ ​ 建立一个主机组,可以针对这一整个组去执行命令

[root@server ~]# vim /etc/ansible/hosts

[testhosts]

127.0.0.1

#192.168.56.128           //IP和域名选填一种

client.test.com      

​ ​ 远程执行一个命令:

[root@server ~]# ansible testhosts -m command -a 'w'



192.168.56.128 | SUCCESS | rc=0 >>

 23:03:41 up 13:29,  2 users,  load average: 0.00, 0.00, 0.00

USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT

root     pts/0    192.168.56.1     22:12    9:43   0.03s  0.03s -bash

root     pts/1    server.test.com  23:03    0.00s  0.04s  0.00s /bin/sh -c LANG



127.0.0.1 | SUCCESS | rc=0 >>

 23:03:34 up 13:28,  2 users,  load average: 0.08, 0.02, 0.01

USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT

root     pts/0    192.168.56.1     22:12    1.00s  0.49s  0.26s /usr/bin/python

root     pts/3    localhost        23:03    0.00s  0.03s  0.00s /bin/sh -c LANG


[root@server ~]# ansible testhosts -m command -a 'hostname'

192.168.56.128 | SUCCESS | rc=0 >>

client



127.0.0.1 | SUCCESS | rc=0 >>

server

​ ​ 这样就可以批量执行命令了。这里的testhosts为主机组名,-m后边是模块名字,-a后面是命令。也可以直接写一个ip,针对某一台机器来执行命令。

[root@server ~]# ansible 192.168.56.128 -m command -a 'hostname'

192.168.56.128 | SUCCESS | rc=0 >>

client

[root@server ~]# ansible client.test.com -m command -a 'hostname'

client.test.com | SUCCESS | rc=0 >>

client

​ ​ 注意:有可能遇到错误:"msg":"Aborting,target uses selinux but python bindings (libselinux-python) aren't installed!"

​ ​ ​ ​ 解决:yum install -y libselinx-python

​ ​ 还有一个模块shell同样能实现远程执行命令

[root@server ~]# ansible client.test.com -m shell -a 'hostname'

client.test.com | SUCCESS | rc=0 >>

client

​ ​ command模块与shell模块的区别:

[root@server ~]# ansible client.test.com -m command -a 'cat /etc/passwd|grep root'

client.test.com | FAILED | rc=1 >>

cat: /etc/passwd|grep: 没有那个文件或目录

cat: root: 没有那个文件或目录



[root@server ~]# ansible client.test.com -m shell -a 'cat /etc/passwd|grep root'

client.test.com | SUCCESS | rc=0 >>

root:x:0:0:root:/root:/bin/bash

operator:x:11:0:operator:/root:/sbin/nologin

​ ​ shell的作用是远程执行一个脚本,也能执行这种管道符式的组合命令

0

评论区