Scrip.sh
Jump to navigation
Jump to search
#!/bin/sh
# <<srv1> <srv2>... <srvN>|all> "codeFile"
[ $# -lt 2 ] &&exit
# initialisation des variables
baseDir="$(realpath "$(dirname $0)"/..)"
cacheFile=/tmp/"$(basename $0)"$$
# ssh parameters
sshUser="$(cat "${baseDir}"/env/sshUser )"
sshKey="${baseDir}"/env/sshKey-"${sshUser}"
sshOpt='-l '"${sshUser}"' -i '"${sshKey}"
# bash colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
# stock code en cache avec des accès limités
cat "${@: -1}" >"${cacheFile}"
chmod 500 "${cacheFile}"
chown infocepo: "${cacheFile}"
# store script
nameBase="$(cat ${cacheFile} |tr -c '[:alnum:]' '_' |cut -c 1-68 |tr -s '_' |sed -r 's#_$##' )"-$(md5sum ${cacheFile} |cut -c 1-2 )
cat "${cacheFile}" |gzip >"${baseDir}"/log/script-"${nameBase}".sh.gz
hostList=$(hostList.sh "${@:1:$(($# -1))}")
# execute code
## max jobs
echo 16 >"${cacheFile}"-count
#for hostName in $hostList ;do
echo "${hostList}" |shuf |while read hostName ;do
cachePath="${baseDir}"/log/old/${hostName}-"${nameBase}"-$(date '+%Y%m%d')
rm -f "${cachePath}".err
if [ -z "$(find "${cachePath}".gz -mmin -1 2>/dev/null )" ] ;then
(count=$(cat "${cacheFile}"-count)
echo $(($count - 1)) >"${cacheFile}"-count
cat "${cacheFile}" |\
ssh -oStrictHostKeyChecking=no -o ConnectTimeout=3 -o ConnectionAttempts=2 $sshOpt "${hostName}" "cat ->/tmp/out$$ &&(
chmod 500 /tmp/out$$
sudo -n /bin/su -c 'timeout --signal=9 600 bash /tmp/out'$$ 2>/tmp/out$$.err >/tmp/out$$2
errCode=\$? ;if [ ! -s /tmp/out$$2 ] &&[ \$errCode -eq 1 ] ;then
timeout --signal=9 600 bash /tmp/out$$ 2>/tmp/out$$.err >/tmp/out$$2
fi
cat /tmp/out$$2
cat /tmp/out$$.err >&2
rm -f /tmp/out$$*
)" 2>"${cachePath}".err |\
gzip >"${cachePath}".gz
count=$(cat "${cacheFile}"-count)
echo $(($count + 1)) >"${cacheFile}"-count)&
fi
while [[ "$(cat "${cacheFile}"-count)" -le 0 ]] ;do
sleep 0.1
done
done |tee /dev/null
# display result
for hostName in $hostList ;do
cachePath="${baseDir}"/log/old/${hostName}-"${nameBase}"-$(date '+%Y%m%d')
if [[ ! -z "$(find "${cachePath}".gz )" ]] ;then
if [ -z "$(zcat "${cachePath}".gz )" ] ;then
rm -f "${cachePath}".gz
else
echo "== ${hostName} =="
zcat "${cachePath}".gz
fi
fi
done
# display errors
for hostName in $hostList ;do
cachePath="${baseDir}"/log/old/${hostName}-"${nameBase}"-$(date '+%Y%m%d')
if [ ! -z "$(find "${cachePath}".err 2>/dev/null )" ] ;then
if [ -z "$(cat "${cachePath}".err )" ] ;then
rm -f "${cachePath}".err
else
#cat "${cachePath}".err |cut -c 1-128 |sed 's#^#\\033[0;31m[W]'"${NC}"'['${hostName}']:#' >&2
v1=$(cat "${cachePath}".err |awk '!seen[$0]++' |cut -c 1-128 |sed 's#^#\\033[0;31m[W]\\033[0m['${hostName}']:#')
>&2 echo -e "$v1"
fi
fi
done
# clean cache
rm -rf /tmp/"$(basename $0)"$$* 2>/dev/null