search by tags

for the user

adventures into the land of the command line

ssh for loops

this is a handy trick i learned from a guy named marcus. it’s a quick and dirty way to do stuff quickly across many hosts in a once off kind of scenario. you’d need to have your ssh keys set up on the remote hosts already for it to be truly effective, which you could even have this do for you as well

$ hostlist="host1 host2 host3"
$ for host in $hostlist; do
> ssh-copy-id -i ~/.ssh/id_rsa.pub host
> echo "host = $host"
> done

you can copy files across

$ hostlist="host1 host2 host3"
$ for host in $hostlist; do
> scp some.file $host:/var/tmp/
> echo "host = $host"
> done

and execute commands quietly (-q) without having to get to a terminal on the remote host (-t). the -t also has the benefit of hiding any passwords you may be prompted to input, such as for sudo

$ hostlist="host1 host2 host3"
$ for host in $hostlist; do
> ssh -qt $host "sudo ls -l /var/tmp/some.file"
> echo "host = $host"
> done

thanks marcus!