# How do I run one command on many servers over SSH?

Run one command on many servers with an ssh loop, then in parallel with xargs -P. Use BatchMode and ConnectTimeout and keep each host's output and exit status.

Source: https://valakes.com/learn/run-command-on-many-servers/

Last updated: 2026-11-25

Put the host names in a file and run ssh -n -o BatchMode=yes -o ConnectTimeout=5 host command for each one, in a loop for a few servers or with xargs -P for many. Keep each host's output and exit status, so one host that fails never hides behind the others.

Commands checked on Ubuntu 24.04.5 LTS (the ubuntu:24.04@sha256:562111b88caa79c71391c0c4d3c2114a7d5c35915c20561fd893cb1e07929e6b container image), 25 November 2026.

Write the host names in a file, one per line, and run `ssh -n -o BatchMode=yes -o ConnectTimeout=5 host command` for each. A `while read` loop is enough for a handful of servers, and `xargs -P` runs several at once. Whichever you pick, store each host's output and exit status, because a host that fails must show up in the result.

The examples use four names. Three exist (`web-1`, `web-2` and `db-1`) and `web-9` does not, so you can see failures too. The `deploy` user and a key are set in `~/.ssh/config`, as described in [the config file article](https://valakes.com/learn/ssh-config-file/).

## The plain loop and the stdin trap

Make the list, then loop over it the obvious way:

```console
$ printf '%s\n' web-1 web-2 db-1 web-9 > hosts.txt
$ while read host; do ssh $host hostname; done < hosts.txt
web-1
```

Only `web-1` answered. ssh reads standard input to pass it to the remote command, and here its input is the host list, so the first ssh ate the other three names. The `-n` option, from the ssh manual, redirects stdin from `/dev/null`:

```console
$ while read host; do ssh -n $host hostname; done < hosts.txt
web-1
web-2
db-1
ssh: Could not resolve hostname web-9: Name or service not known
```

Now every name is tried. `web-9` has no address, so ssh printed an error for it, and the loop went on to the end of the list. A `for host in $(cat hosts.txt)` loop avoids the trap too, but it splits on any white space, so keep to plain host names.

## Make ssh safe to run without you

Two options belong on every ssh that runs in a loop, a script or a scheduled job.

`BatchMode=yes` turns off every question: password prompts and host key confirmation. If ssh would have to ask, it fails instead. The Ubuntu manual adds that it also sets the keep-alive interval to 300 seconds. This works only with key login, so set up keys first, as in [the SSH keys article](https://valakes.com/learn/ssh-keys/). Here is what a host key that is not known yet does under BatchMode (the extra options force the question):

```console
$ ssh -n -o BatchMode=yes -o ConnectTimeout=5 web-1 cat /opt/app/VERSION
1.4.2
$ ssh -n -o BatchMode=yes -o StrictHostKeyChecking=ask -o UserKnownHostsFile=/dev/null web-1 hostname
Host key verification failed.
```

`ConnectTimeout=5` gives ssh five seconds to connect and finish the handshake, instead of the default system TCP timeout. It does not limit the remote command. If a command may hang, run it under the coreutils `timeout` on the server. Against a host that does not answer, ssh gives up after that time and prints `Connection timed out`. That message depends on the network between you and the host, so this article does not run it in a container. In a loop it shows up as exit status 255, which the next section counts.

## Keep each host's answer and its status

ssh exits with the status of the remote command, or with 255 if ssh itself failed. That lets a loop tell "could not connect" from "connected, and the command failed". This loop prints one line per host and counts the failures:

```console
$ failed=0; while read host; do out=$(ssh -n -o BatchMode=yes -o ConnectTimeout=5 $host cat /opt/app/VERSION 2>&1) && echo "$host: $out" || { echo "$host FAILED: $out"; failed=$((failed+1)); }; done < hosts.txt; echo "failed on $failed hosts"
web-1: 1.4.2
web-2: 1.4.1
db-1 FAILED: cat: /opt/app/VERSION: No such file or directory
web-9 FAILED: ssh: Could not resolve hostname web-9: Name or service not known
failed on 2 hosts
```

You learn three things from it. `web-2` runs 1.4.1 where `web-1` runs 1.4.2. `db-1` has no `/opt/app/VERSION`, which is a failure of the command and not of the connection. `web-9` could not be reached. A loop that only prints the output would have left the last two as a blank line and an error you had to spot.

## Run on many hosts at once with xargs

A loop takes as long as the sum of all hosts. `xargs -P` runs several at the same time. To keep the output of the hosts apart, each run writes its own files:

```console
$ mkdir out
$ xargs -P 4 -n 1 sh -c 'ssh -n -o BatchMode=yes -o ConnectTimeout=5 "$1" cat /opt/app/VERSION > "out/$1.out" 2> "out/$1.err"; echo $? > "out/$1.rc"' sh < hosts.txt
```

`-n 1` hands one host name to each run and `-P 4` allows four runs at a time. The host arrives as `$1`, so it is never pasted into the shell text and a strange name cannot change the command. When the runs finish, read the results in the order of the list:

```console
$ for h in $(cat hosts.txt); do echo "$h rc=$(cat out/$h.rc) out=$(cat out/$h.out) err=$(cat out/$h.err)"; done
web-1 rc=0 out=1.4.2 err=
web-2 rc=0 out=1.4.1 err=
db-1 rc=1 out= err=cat: /opt/app/VERSION: No such file or directory
web-9 rc=255 out= err=ssh: Could not resolve hostname web-9: Name or service not known
$ grep -L '^0$' out/*.rc
out/db-1.rc
out/web-9.rc
```

`grep -L` lists the files that have no line with `0`, which are the hosts that failed. Without the files, the output of four hosts printed together arrives in whatever order they finish, and lines can mix.

Do not set `-P` to 0 for a long list. The sshd manual says its `MaxStartups` default is `10:30:100`: after ten connections that have not logged in yet, a share of new ones is refused. A bastion host that every connection passes through reaches that limit first.

## Why one failed host must not end the run

The xargs manual says that if any invocation exits with status 255, xargs stops at once and reads no more input. ssh uses 255 for its own errors, so a host that cannot be reached can stop the hosts after it. Put the missing host first:

```console
$ printf '%s\n' web-9 web-1 web-2 | xargs -I{} ssh -n -o BatchMode=yes {} hostname; echo "exit status: $?"
ssh: Could not resolve hostname web-9: Name or service not known
xargs: ssh: exited with status 255; aborting
exit status: 124
```

`web-1` and `web-2` never ran. xargs wrote one line to stderr and exited with 124. In a script whose errors go to a log file, nobody sees that line, and the run looks like a success that produced less output. The `sh -c '...; echo $? > ...'` wrapper above avoids this on purpose: its last command is `echo`, which exits 0, so xargs never sees the 255, and the status of each host is in its `.rc` file instead.

## Mistakes people make

You test the command on all hosts at once. A loop has no check and no confirmation. Run a command that only reads first, and run a command that changes something on one host before the rest.

You skip `BatchMode` and the loop works at your desk. In cron or a pipeline, a question has nobody to answer it.

You paste host names into a string for `sh -c`. A name that comes from a file or an inventory should arrive as an argument.

You run the loop in a session that can close. The loop ends with the connection. For a job that takes a long time, see [keeping commands running](https://valakes.com/learn/keep-commands-running/).

## In Valakes

If you would rather see the answer before anything runs, open the servers as panes of one tab and start a broadcast in Commands mode. Valakes checks the command for every host, shows a card with one row per host and its risk, and runs it only on the hosts you leave checked. A tab holds up to six panes. [Guide: How do I run the same command on several servers at once, safely?](https://valakes.com/guides/run-one-command-on-several-servers/)

[Read the docs: Panes and broadcast](https://docs.valakes.com/panes-and-broadcast/)

## Questions

### Why does my ssh loop stop after the first host?

ssh reads standard input, and in a while read loop that is your host list, so the first ssh swallows the rest of it. Add -n, which redirects stdin from /dev/null, or read the list with a for loop.

### What does exit status 255 mean?

ssh uses it for its own errors, such as a name that does not resolve, a refused login or a timeout. When the remote command runs, ssh exits with that command's status instead.

### How high can I set -P?

xargs runs one process at a time by default, and -P 0 runs as many as it can. The limit is usually the other side. The default MaxStartups of sshd is 10:30:100, which starts refusing a share of new unauthenticated connections once ten are waiting. Start with 4 to 8 and raise it while you watch the failures.

## References

- [ssh(1) on Ubuntu 24.04, the option -n and the exit status 255](https://manpages.ubuntu.com/manpages/noble/man1/ssh.1.html)
- [ssh_config(5) on Ubuntu 24.04, BatchMode and ConnectTimeout](https://manpages.ubuntu.com/manpages/noble/man5/ssh_config.5.html)
- [xargs(1) on Ubuntu 24.04, the options -n and -P and the exit status](https://manpages.ubuntu.com/manpages/noble/man1/xargs.1.html)
- [sshd_config(5) on Ubuntu 24.04, MaxStartups](https://manpages.ubuntu.com/manpages/noble/man5/sshd_config.5.html)
- [OpenSSH manual pages](https://www.openssh.org/manual.html)

## Related articles

- [How do I keep a command running after I close SSH?](https://valakes.com/learn/keep-commands-running/): Start it inside tmux (tmux new -s name, then Ctrl-b and d to leave). If tmux is not there, put nohup in front of the command and an ampersand after it. When a terminal closes, the programs started in it get a hangup signal and stop, and both tools get around that.
- [SSH config file (~/.ssh/config): examples that work](https://valakes.com/learn/ssh-config-file/): The file ~/.ssh/config stores the address, user, port and key of each server under a short name. After that, ssh app does the work of a long command.
- [How do I generate an SSH key and put it on a server?](https://valakes.com/learn/ssh-keys/): Run ssh-keygen -t ed25519, then ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host. The private key stays on your computer, the public key goes into ~/.ssh/authorized_keys on the server, and you log in without a password.
