ansible 远程命令

命令格式

ansible <hostgroup> -m <module> -a <command>
  • hostgroup:执行的主机,支持单个IP,多个IP(用,隔开),定义的主机组

  • module:ansible 支持的模块

  • command:模块中对应的命令

[root@localhost ~]# ansible 192.168.127.129 -m command -a "w"
192.168.127.129 | SUCCESS | rc=0 >>
 20:58:47 up 35 min,  2 users,  load average: 0.00, 0.01, 0.05
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.127.1    20:24   34:30   0.01s  0.01s -bash
root     pts/1    192.168.127.128  20:58    0.00s  0.13s  0.00s w
ansible-doc <module> : ansible官方使用手册

ping模块

测试客户端连接性的模块,没有对应的命令

[root@localhost ~]# ansible 192.168.127.129 -m ping
192.168.127.129 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

command模块

远程执行linux命令

[root@localhost ~]# ansible 192.168.127.129 -m command -a "echo 123"
192.168.127.129 | SUCCESS | rc=0 >>
123

shell模块

command模块,但它支持管道符和执行远程主机上的脚本

[root@localhost ~]# ansible 192.168.127.129 -m shell -a "ps aux|grep sshd"
192.168.127.129 | SUCCESS | rc=0 >>
root        782  0.0  0.4 112796  4324 ?        Ss   20:24   0:00 /usr/sbin/sshd -D
root        880  0.0  0.6 161400  6024 ?        Ss   20:24   0:00 sshd: root@pts/0
root       1657  2.0  0.5 159112  5944 ?        Ss   21:06   0:00 sshd: root@pts/1
root       1704  0.0  0.1 113172  1208 pts/1    S+   21:07   0:00 /bin/sh -c ps aux|grep sshd
root       1706  0.0  0.0 113172   188 pts/1    R+   21:07   0:00 /bin/sh -c ps aux|grep sshd
ansible testhost -m shell -a "/tmp/test.sh"

注意:这里的远程脚本需要有执行权限

最后更新于

这有帮助吗?