# ansible 远程命令

**命令格式**

```bash
ansible <hostgroup> -m <module> -a <command>
```

* hostgroup：执行的主机，支持单个IP，多个IP（用，隔开），定义的主机组
* module：ansible 支持的模块
* command：模块中对应的命令

```bash
[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
```

```bash
ansible-doc <module> : ansible官方使用手册
```

**ping模块**

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

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

**command模块**&#x20;

远程执行linux命令

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

**shell模块**

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

```bash
[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
```

```bash
ansible testhost -m shell -a "/tmp/test.sh"
```

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lack.gitbook.io/operation-and-maintenance/zi-dong-hua-yun-wei/ansible-yuan-cheng-ming-ling.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
