I am trying to write a bash script which will take the input in form of arguments and execute certain commands (provided as arguments) on the remote hosts which will be provided via txt file
For eg: there is text file /var/tmp/hosts.txt which have hostnames which we will be executing a set of commands. When I run the script (command.sh) I should be able to run commands on the remote hosts provided in the hosts.txt file
For instance: Hosts file - hosts.txt and Command to be executed is:
lscpu | grep "Model name" | cut -d: -f2 | awk '{$1=$1};1'
I should be able to execute in this way:
command.sh -f hosts.txt -c "lscpu | grep "Model name" | cut -d: -f2 | awk '{$1=$1};1'"
and it should run the command provided in the -c
argument on hosts xyz after doing an ssh
I was able to get single line commands working (whoami
, hostname date .. ) but when it comes to combination of commands, I failed to achieve that because it takes them as different set of arguments.
\#!/bin/bash
usage () {
echo "Usage: $0 \<Hostfile\>"
exit -1
}
id="rm08397"
while getopts ":c:f:" option; do
case "$option" in
f) file_arg=$OPTARG ;;
c) command_arg="$OPTARG" ;;
esac
done
if \[ "$file_arg" != "" \]; then
HOSTFILE="$2"
fi
if \[ $command_arg != "" \]; then
cmd="$command_arg"
else
cmd=$4
fi
for host in `cat $HOSTFILE`
do
echo -n "$host#"
ssh $id@$host $cmd
done