Alex Brown Alex Brown - 5 months ago 9
Linux Question

how to send different commands to multiple hosts to run programs in Linux

I am an R user. I always run programs on multiple computers of campus. For example, I need to run 10 different programs. I need to open PuTTY 10 times to log into the 10 different computers. And submit each of programs to each of 10 computers (their OS is Linux). Is there a way to log in 10 different computers and send them command at same time? I use following command to submit program

nohup Rscript L_1_cc.R > L_1_sh.txt

nohup Rscript L_2_cc.R > L_2_sh.txt

nohup Rscript L_3_cc.R > L_3_sh.txt

Answer

First set up ssh so that you can login without entering a password (google for that if you don't know how). Then write a script to ssh to each remote host to run the command. Below is an example.

#!/bin/bash

host_list="host1 host2 host3 host4 host5 host6 host7 host8 host9 host10"

for h in $host_list
do
    case $h in
        host1)
            ssh $h nohup Rscript L_1_cc.R > L_1_sh.txt
            ;;
        host2)
            ssh $h nohup Rscript L_2_cc.R > L_2_sh.txt
            ;;
        esac
done

This is a very simplistic example. You can do much better than this (for example, you can put the ".R" and the ".txt" file names into a variable and use that rather than explicitly listing every option in the case).