-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-everywhere.sh
More file actions
89 lines (73 loc) · 2.15 KB
/
run-everywhere.sh
File metadata and controls
89 lines (73 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/bin/bash
# A list of servers, one per line.
SERVER_LIST='/servers'
# Options for the ssh command.
SSH_OPTIONS='-o ConnectTimeout=2'
usage() {
# Display the usage and exit.
echo "Usage: ${0} [-nsv] [-f FILE] COMMAND" >&2
echo 'Executes COMMAND as a single command on every server.' >&2
echo " -f FILE Use FILE for the list of servers. Default: ${SERVER_LIST}." >&2
echo ' -n Dry run mode. Display the COMMAND that would have been executed and exit.' >&2
echo ' -s Execute the COMMAND using sudo on the remote server.' >&2
echo ' -v Verbose mode. Displays the server name before executing COMMAND.' >&2
exit 1
}
# Make sure the script is not being executed with superuser privileges.
if [[ "${UID}" -eq 0 ]]
then
echo 'Do not execute this script as root. Use the -s option instead.' >&2
usage
fi
# Parse the options.
while getopts f:nsv OPTION
do
case ${OPTION} in
f) SERVER_LIST="${OPTARG}" ;;
n) DRY_RUN='true' ;;
s) SUDO='sudo' ;;
v) VERBOSE='true' ;;
?) usage ;;
esac
done
# Remove the options while leaving the remaining arguments.
shift "$(( OPTIND - 1 ))"
# If the user doesn't supply at least one argument, give them help.
if [[ "${#}" -lt 1 ]]
then
usage
fi
# Anything that remains on the command line is to be treated as a single command.
COMMAND="${@}"
# Make sure the SERVER_LIST file exists.
if [[ ! -e "${SERVER_LIST}" ]]
then
echo "Cannot open server list file ${SERVER_LIST}." >&2
exit 1
fi
# Expect the best, prepare for the worst.
EXIT_STATUS='0'
# Loop through the SERVER_LIST
for SERVER in $(cat ${SERVER_LIST})
do
if [[ "${VERBOSE}" = 'true' ]]
then
echo "${SERVER}"
fi
SSH_COMMAND="ssh ${SSH_OPTIONS} ${SERVER} ${SUDO} ${COMMAND}"
# If it's a dry run, don't execute anything, just echo it.
if [[ "${DRY_RUN}" = 'true' ]]
then
echo "DRY RUN: ${SSH_COMMAND}"
else
${SSH_COMMAND}
SSH_EXIT_STATUS="${?}"
# Capture any non-zero exit status from the SSH_COMMAND and report to the user.
if [[ "${SSH_EXIT_STATUS}" -ne 0 ]]
then
EXIT_STATUS=${SSH_EXIT_STATUS}
echo "Execution on ${SERVER} failed." >&2
fi
fi
done
exit ${EXIT_STATUS}