Сборник примеров программ на bash
fping_chk
Быстрая групповая проверка хостов на доступность
#!/bin/bash
attempts=$(($2+1))
## all working nodes
# {3..19} {22..24} {27..28} {30..38}
declare -a sc613='2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 22 23 24 27 28 30 31 32 33 34 35 36 37 38'
# {3..19} {22.24}
declare -a sc619='3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 22 23 24'
function check_613() {
echo 'Проверка доступности хостов сети '$ip_h 'из '$(uname -n)
for (( count=1; count < $attempts; count++ )); do
echo '-----------[ step' $count'/'$(($attempts-1))' ]' $(date +%d.%m.%y) $(date +%H:%M) '---------'
for ip in $sc613; do
if ! [[ $(fping -qa ${ip_h}.${ip}) ]]; then
echo ${ip_h}.${ip} is dead!
fi
done
done
}
function check_619() {
echo 'Проверка доступности хостов сети '$ip_h 'из '$(uname -n)
for (( count=1; count < $attempts; count++ )); do
echo '-----------[ step' $count'/'$(($attempts-1))' ]' $(date +%d.%m.%y) $(date +%H:%M) '---------'
for ip in $sc619; do
if ! [[ $(fping -qa ${ip_h}.${ip}) ]]; then
echo ${ip_h}.${ip} is dead!
fi
done
done
}
function usage() {
echo 'Укажите номер VLAN (613 или 619) и кол-во попыток!'
}
if [ $# != 2 ]; then
usage
else
case $1 in
613)
ip_h="10.55.126"
check_613;;
619)
ip_h="172.17.5"
check_619;;
*)
usage;;
esac
fi
bulk_tune
Групповое выполнение сценариев на удаленных серверах.
Пример запуска: ./bulk_tune
#!/bin/bash
scope=$2
case $scope in
all)
declare -a srvl=(cmp01 cmp02 cmp03 cph01 cph02 cph03 mon01 mon02 ctl01 ctl02 ctl03 s3f01 s3f02 s3f03);;
ceph)
declare -a srvl=(cph01 cph02 cph03);;
s3)
declare -a srvl=(s3f01 s3f02 s3f03);;
ctl)
declare -a srvl=(ctl01 ctl02 ctl03);;
*)
;;
esac
echo ${srvl[@]}
if [ $# != 2 ]; then
echo "payload OR scope not defined!"; exit 0
else
for srv in ${srvl[@]}; do
echo $srv
ssh $srv 'bash -s' < $1;
done
fi
psi_go
Прогон сценариев ПСИ scmd - номер команды, с которой начинаем выполнение, можно задать, как параметр командной строки. В файл .psi_cmd.lst необходимо добавить все запускаемые команды - по одной на строку.
#!/bin/bash
# psi_go: Прогон сценариев ПСИ
# created during 21.01.2023
# aizaro@mail.ru
if [[ -z $1 ]]; then scmd=0; else scmd=$1; fi
declare -a psicmd
# filling command stack from file
readarray -t psicmd < .psi_cmd.lst
sumop=${#psicmd[@]} ## total operations
#for pp in ${psicmd[*]}; do echo $pp; done
function msg1() {
echo -e '\nВыполняем команду'$1
}
function msg2() {
echo -e 'Результат выполнения команды: \n'
}
function step_mark() {
read -p ':---------------->'
}
for (( step=$scmd; step < $sumop; step++ )); do
msg1
echo '# '$step': '${psicmd[$step]}
step_mark
msg2
#${psicmd[$step]} > /tmp/result_psi ## not worked with for
echo ${psicmd[$step]} > /tmp/psi_cmd && /bin/bash /tmp/psi_cmd
cat /tmp/result_psi
done
ssl_scan
Скрипт отобразит наиболее важные детали SSL-сертификата:
server.company.com:443 ; SSL ; CN: (CN сертификата SSL) ; Subject (Subject сертификата SSL) ; Issuer: (Issuer сертификата SSL) ;
notBefore: (Дата создания SSL-сертификата) ; notAfter: (Дата истечения срока действия SSL-сертификата) ;
DaysUntilExpiration: (Дни, оставшиеся до истечения срока действия SSL-сертификата) ; Errors: (Любые ошибки, связанные с SSL-сертификатом)
#!/bin/bash
export delim=" ; "
serverport=${1}
export serverport
echo "#${serverport}"
date_today=$(date +%F)
datediff() {
d1=$(date -d "$1" +%s)
d2=$(date -d "$2" +%s)
echo $(( (d1 - d2) / 86400 )) days
}
export -f datediff
sslscan() {
local sp=${1}
tls_content=$(echo "Q" | openssl s_client -showcerts -connect ${serverport} 2>&1)
if [[ "$?" == 0 ]]; then
tls_errors=$(echo "${tls_content}" | grep -i error )
tls_cert_subject=$(echo "${tls_content}" | openssl x509 -noout -subject )
tls_cert_issuer=$(echo "${tls_content}" | openssl x509 -noout -issuer )
tls_cert_cn=$(echo "${tls_content}" | openssl x509 -noout -subject | sed -e "s/.*CN=\([^\/]*\).*/\1/" )
tls_cert_dates=$(echo "${tls_content}" | openssl x509 -noout -dates )
tls_cert_notafter_date=$(echo "${tls_cert_dates}" | grep notAfter |sed -e "s/notAfter=//" | tr -d '\n')
tls_cert_notbefore_date=$(echo "${tls_cert_dates}" | grep notBefor |sed -e "s/notBefore=//" | tr -d '\n')
tls_cert_datediff=$(datediff "${tls_cert_notafter_date}" "${date_today}")
echo -n "${serverport} ${delim} SSL"
echo -n " ${delim} CN:"
echo -n " ${tls_cert_cn}"
echo -n " ${delim} Subject:"
echo -n " ${tls_cert_subject}"
echo -n " ${delim} Issuer:"
echo -n " ${tls_cert_issuer}"
echo -n " ${delim} notBefore:"
echo -n " ${tls_cert_notbefore_date}"
echo -n " ${delim} notAfter:"
echo -n " ${tls_cert_notafter_date}"
echo -n " ${delim} DaysUntilExpiration:"
echo -n " ${tls_cert_datediff}"
echo -n " ${delim} Errors:"
echo -n " ${tls_errors}"
echo
else
tls_errors=$(echo "${tls_content}" | tr '\n' '/' | tr ' ' '_' )
status="ERROR: ${tls_errors}"
echo -n "${serverport} ${delim} ${status}"
echo
fi
}
export -f sslscan
timeout 3 bash -c "sslscan ${serverport}"
if [[ $? != 0 ]]; then
echo -n "${serverport} ${delim} ERROR: CONNECTION_TIMED_OUT"
echo
fi
lxc_bak
Резервное копирование LXC-контейнера
#!/bin/bash
for cc in $(lxc-ls -1 --active); do
lxc-stop -n $cc
tar cvfj /home/user/backup/lxc/${cc}-$(date +%y%m%d%H).tbz /var/lib/lxc/$cc
lxc-start -n $cc
done
watcher
Контроль сервиса и перезапуском
# cat /usr/local/bin/watcher
#!/bin/bash
SRV=$1
MIG=$(date +%y%m%d%H%M)
function srv_start() {
if ! [[ -z $(pgrep certbot) ]]; then
echo "Certbot lanched now"
for PCB in $(pgrep certbot); do
kill -9 $PCB
done
fi
/usr/sbin/service $SRV start
echo ${MIG}: ${SRV} restart >> /var/log/${SRV}/restart.log
}
if [ $# = 0 ]; then
echo 'Usage '${0}' <service_name>'; exit 0
fi
if [ -e /run/${SRV}.pid ]; then
echo ${SRV}: state OK
else
srv_start
fi