Linux – ssh to multiple hosts and sudo multiple commands

bashlinuxmac-osxsudo

I need to loop through and ssh to multiple hosts and run a series of commands on each.

something like:

for i in $(jot -w '%02.0f' 14 1)
>do ssh user@host$i sudo -i "command1; command2; command3"
>done

but I can't get it to work correctly. I've seen various things on The Google like sudo sh -c, piping to sudo, etc, but can't figure it out.

  • I'm ssh'ing as a regular user that can sudo with no password (ssh as root not enabled)
  • command1 not returning 0 should not prevent command2 from running, etc, hence ;
  • I'm running the loop from a mac, hence jot -w, which is roughly equivalent to seq -f in linux
  • ssh'ing to CentOS 5.4
  • I'd like it to run with root's $PATH so I don't have to specify the full path to the commands, but it's not totally necessary

thanks in advance!

Best Answer

I find that getting the quoting correct is pretty annoying. Instead I tend to just pass commands to bash on the remote host through a pipe instead. This way you don't have to worry about getting the escaping right in your ssh command line. Just pass into the pipe exactly what you would type if you were connected interactively.

CMDS="sudo bash -c '/usr/bin/id; /usr/bin/id; '/usr/bin/id"
for i in 0 1; do
  echo $CMDS | ssh -t host$i bash
done

Which returns

uid=0(root) gid=0(root) groups=0(root)
uid=0(root) gid=0(root) groups=0(root)
uid=0(root) gid=0(root) groups=0(root)
Related Topic