From a8c75595aa08fe364d24a20dc9a2a58bb6dc3488 Mon Sep 17 00:00:00 2001 From: bartik Date: Fri, 22 Jul 2022 15:12:24 +0200 Subject: [PATCH 01/19] FIX Luis Reinoso from Chile --- check_sybase_ase.sh | 72 +++++++++++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 32 deletions(-) diff --git a/check_sybase_ase.sh b/check_sybase_ase.sh index 331dd5c..7bb30fb 100644 --- a/check_sybase_ase.sh +++ b/check_sybase_ase.sh @@ -9,6 +9,8 @@ # Version: 1.0, 30.11.2017 # Home page: https://www.bersler.com/blog/nagios-script-for-checking-sap-adaptive-server-enterprise-sybase-ase/ # +# FIX Luis Reinoso from Chile +# # Script for monitoring SAP (Sybase) Adaptive Server Enterprise (ASE) using Nagios # # @@ -37,14 +39,14 @@ SERVER= LOGIN= PASSWORD= CHARACTERSET=iso_1 -SYBASE=/opt/sybase +SYBASE=/sybase/* # variables NUMDATABASES=0 NUMPROCESSES=0 EXTRAINFO="" -while getopts "S:U:P:c:?" opt; do +while getopts "S:U:P:C:X:?" opt; do case $opt in S) SERVER=$OPTARG @@ -86,9 +88,26 @@ source $SYBASE/SYBASE.sh unset LANG +######################################################################## +#statistical information +out=`isql64 -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET -X << EOF | tail -n +4 +$PASSWORD +set nocount on +set transaction isolation level 0 +go +declare @databases int, @processes int +select @databases = count(*) from master..sysdatabases +select @processes = count(*) from master..sysprocesses where suid > 0 and spid <> @@spid +select @databases as databases, @processes as processes +go +EOF` + +NUMDATABASES=`echo "$out" | awk '{ print $1 }'` +NUMPROCESSES=`echo "$out" | awk '{ print $2 }'` + ######################################################################## #test connect -out=`isql -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET << EOF | tail -n +4 +out=`isql64 -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET -X << EOF | tail -n +4 $PASSWORD set nocount on go @@ -99,12 +118,12 @@ EOF` alive=`echo "$out" | grep "Adaptive Server Enterprise"` if [ -z "$alive" ]; then echo "ASE SERVER CRITICAL - Unable to connnect|databases=$NUMDATABASES processes=$NUMPROCESSES" - exit + exit 2 fi; ######################################################################## #log full -out=`isql -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET << EOF | tail -n +4 +out=`isql64 -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET -X << EOF | tail -n +4 $PASSWORD set nocount on set transaction isolation level 0 @@ -119,44 +138,31 @@ IFS=$'\n' for a in $out; do dbname=`echo "$a" | awk '{ print $1 }'` dbtype=`echo "$a" | awk '{ print $2 }'` - + DBerror=`echo "$a" | awk -F- '{ print "Problem "$1 }'` + if [ "$dbtype" == "tempdb" ]; then echo "ASE SERVER CRITICAL - log full in temporary db $dbname|databases=$NUMDATABASES processes=$NUMPROCESSES" - exit - fi + exit 2 + fi; if [ "$logfulldbs" == "" ]; then logfulldbs=$dbname else logfulldbs="$logfulldbs, $dbname" fi; + if [ "$dbname" == "Database" ]; then + logfulldbs=$DBerror + fi; numlogfulldbs=$((numlogfulldbs+1)) done; if [ ! -z "$logfulldbs" ]; then echo "ASE SERVER CRITICAL - log full in $numlogfulldbs dbs: $logfulldbs|databases=$NUMDATABASES processes=$NUMPROCESSES" - exit + exit 2 fi; -######################################################################## -#statistical information -out=`isql -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET << EOF | tail -n +4 -$PASSWORD -set nocount on -set transaction isolation level 0 -go -declare @databases int, @processes int -select @databases = count(*) from master..sysdatabases -select @processes = count(*) from master..sysprocesses where suid > 0 and spid <> @@spid -select @databases as databases, @processes as processes -go -EOF` - -NUMDATABASES=`echo "$out" | awk '{ print $1 }'` -NUMPROCESSES=`echo "$out" | awk '{ print $2 }'` - ######################################################################## #blocked processes -out=`isql -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET << EOF | tail -n +4 +out=`isql64 -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET -X << EOF | tail -n +4 $PASSWORD set nocount on set transaction isolation level 0 @@ -187,12 +193,12 @@ done; if [ ! -z "$blockedprocesses" ]; then echo "ASE SERVER CRITICAL - $numblockedprocesses blocked processes SPID: $blockedprocesses|databases=$NUMDATABASES processes=$NUMPROCESSES" - exit + exit 2 fi; ######################################################################## #long running transactions -out=`isql -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET << EOF | tail -n +4 +out=`isql64 -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET -X << EOF | tail -n +4 $PASSWORD set nocount on set transaction isolation level 0 @@ -215,13 +221,13 @@ done; if [ ! -z "$databasessuspended" ]; then echo "ASE SERVER CRITICAL - $numlongrunningtransactions long running transactions: $longrunningtransactions |databases=$NUMDATABASES processes=$NUMPROCESSES" - exit + exit 2 fi; ######################################################################## #free space -out=`isql -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET << EOF | tail -n +4 +out=`isql64 -U$LOGIN -S$SERVER -w500 -J$CHARACTERSET -X << EOF | tail -n +4 $PASSWORD set nocount on set transaction isolation level 0 @@ -289,8 +295,10 @@ done; if [ ! -z "$fulldb" ]; then if [ ! -z "$error" ]; then echo "ASE SERVER CRITICAL - $numfulldb space: $fulldb |databases=$NUMDATABASES processes=$NUMPROCESSES ${EXTRAINFO}" + exit 2 else echo "ASE SERVER WARNING - $numfulldb space: $fulldb |databases=$NUMDATABASES processes=$NUMPROCESSES ${EXTRAINFO}" + exit 1 fi; exit fi; @@ -298,4 +306,4 @@ fi; ######################################################################## #all is ok -echo "ASE SERVER OK |databases=$NUMDATABASES processes=$NUMPROCESSES ${EXTRAINFO}" +echo "ASE SERVER OK - Databases $NUMDATABASES - Processes $NUMPROCESSES - DB $(echo $SYBASE | awk -F/ '{print $NF}') |databases=$NUMDATABASES processes=$NUMPROCESSES ${EXTRAINFO}" From 8629d861975fca715513bc8d1e59807d0fe103ab Mon Sep 17 00:00:00 2001 From: bartik Date: Mon, 29 Aug 2022 14:08:24 +0200 Subject: [PATCH 02/19] Initial commit --- extract.sh | 182 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 extract.sh diff --git a/extract.sh b/extract.sh new file mode 100644 index 0000000..bb935c9 --- /dev/null +++ b/extract.sh @@ -0,0 +1,182 @@ +#!/bin/bash +export PS4='+(\D{%D %T} ${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' +set -euxo pipefail +# See https://launchpad.support.sap.com/#/notes/1473974 for more details (You need S-account to see) +# ARG_OPTIONAL_SINGLE([dir],[d],[Directory with extracted hostagent executables.],['/usr/sap/hostctrl/exe/']) +# ARG_OPTIONAL_SINGLE([share],[s],[SAP shared directory.],['/export/SAP/software/saphostagent/']) +# ARG_HELP([Configure autoupdate parameters for hostagent.],[Configure autoupdate parameters for hostagent.],[?],[]) +# ARG_OPTIONAL_SINGLE([download],[o],[Download directory with hostagent archive files.],['/export/SAP/software/download/']) +# ARG_VERSION_AUTO([1.0]) + +### START OF CODE GENERATED BY Argbash v2.9.0 one line above ### +# Argbash is a bash code generator used to get arguments parsing right. +# Argbash is FREE SOFTWARE, see https://argbash.io for more info +# Generated online by https://argbash.io/generate + +die() { + local _ret="${2:-1}" + test "${_PRINT_HELP:-no}" = yes && print_help >&2 + echo "$1" >&2 + exit "${_ret}" +} + +begins_with_short_option() { + local first_option all_short_options='ds?ov' + first_option="${1:0:1}" + test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0 +} + +# THE DEFAULTS INITIALIZATION - OPTIONALS +_arg_dir='/usr/sap/hostctrl/exe/' +_arg_share='/export/SAP/software/saphostagent/' +_arg_download='/export/SAP/software/download/' + +print_help() { + printf '%s\n' "Extract hostagent archives." + printf 'Usage: %s [-d|--dir ] [-s|--share ] [-?|--help] [-o|--download ] [-v|--version]\n' "$0" + printf '\t%s\n' "-d, --dir: Directory with extracted hostagent executables. (default: ''/usr/sap/hostctrl/exe/'')" + printf '\t%s\n' "-s, --share: SAP shared directory. (default: ''/export/SAP/software/saphostagent/'')" + printf '\t%s\n' "-?, --help: Prints help" + printf '\t%s\n' "-o, --download: Download directory with hostagent archive files. (default: ''/export/SAP/software/download/'')" + printf '\t%s\n' "-v, --version: Prints version" + printf '\n%s\n' "Extract hostagent archives." +} + +parse_commandline() { + while test $# -gt 0; do + _key="$1" + case "$_key" in + -d | --dir) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_dir="$2" + shift + ;; + --dir=*) + _arg_dir="${_key##--dir=}" + ;; + -d*) + _arg_dir="${_key##-d}" + ;; + -s | --share) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_share="$2" + shift + ;; + --share=*) + _arg_share="${_key##--share=}" + ;; + -s*) + _arg_share="${_key##-s}" + ;; + -\? | --help) + print_help + exit 0 + ;; + -\?*) + print_help + exit 0 + ;; + -o | --download) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_download="$2" + shift + ;; + --download=*) + _arg_download="${_key##--download=}" + ;; + -o*) + _arg_download="${_key##-o}" + ;; + -v | --version) + printf '%s %s\n\n%s\n' "" "1.0" 'Configure autoupdate parameters for hostagent.' + exit 0 + ;; + -v*) + printf '%s %s\n\n%s\n' "" "1.0" 'Configure autoupdate parameters for hostagent.' + exit 0 + ;; + *) + _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1 + ;; + esac + shift + done +} + +parse_commandline "$@" + +# OTHER STUFF GENERATED BY Argbash + +### END OF CODE GENERATED BY Argbash (sortof) ### ]) + +m_sapcar="${_arg_dir}SAPCAR" + +declare -A m_ver +declare -A m_sar +declare -A m_sarmap + +# Maps material number to directory +m_sarmap["80004822"]="Linux/x86_64/" +m_sarmap["80004831"]="Linux/ppc64le/" +m_sarmap["80004756"]="AIX/powerpc/" +m_sarmap["80004757"]="HP-UX/ia64/" +m_sarmap["80004758"]="HP-UX/pa-risc/" +m_sarmap["80004821"]="Linux/ia64/" +m_sarmap["80004759"]="Linux/ppc64be/" +m_sarmap["80004830"]="zseries/64/" +m_sarmap["80004829"]="OS400/64/" +m_sarmap["80004827"]="Solaris/sparc64/" +m_sarmap["80004826"]="Solaris/x86_64/" +m_sarmap["80004825"]="Windows/x86_64/" +m_sarmap["80004828"]="zOS/64/" + +removeold() { + echo "" >"${_arg_share}${m_sarmap[${1}]}.upgrading" + find "${_arg_share}${m_sarmap[${1}]}" \ + ! -name .upgrading \ + -type f \ + -regex ".*/${m_sarmap[${1}]}.*" \ + -exec rm -f '{}' \; + rm -f "${_arg_share}${m_sarmap[${1}]}.upgrading" +} + +extractnew() { + m_lines=$(find "${_arg_share}${m_sarmap[${1}]}" -type f | awk 'END {print NR}') + if [[ ${m_lines} == "0" ]]; then + echo "" >"${_arg_share}${m_sarmap[${1}]}.upgrading" + "${m_sapcar}" -xjf "${m_sar[${1}]}" -R "${_arg_share}${m_sarmap[${1}]}" -manifest SIGNATURE.SMF + #echo "1440random60" >"${_arg_share}${m_sarmap[${1}]}.delay" + echo "" >"${_arg_share}${m_sarmap[${1}]}.verify" + rm -f "${_arg_share}${m_sarmap[${1}]}.upgrading" + fi +} + +# Find the newest available saphostagent version +while IFS= read -r m_file; do + m_key="${m_file##*-}" + m_key="${m_key%.SAR}" + m_val="${m_file##*_}" + m_val="${m_val%-*}" + if [[ -n ${m_ver[${m_key}]:-} ]]; then + if [[ ${m_ver[${m_key}]} -lt ${m_val} ]]; then + m_ver["${m_key}"]="${m_val}" + m_sar["${m_key}"]="${m_file}" + fi + else + m_ver["${m_key}"]="${m_val}" + m_sar["${m_key}"]="${m_file}" + fi +done < <(find "${_arg_download}" -type f -regex ".*SAPHOSTAGENT[0-9][0-9]_[0-9][0-9]-[0-9]*\.SAR" 2>/dev/null) + +for i in "${!m_ver[@]}"; do + if [[ -f "${_arg_share}${m_sarmap[$i]}hostagent.mf" ]]; then + m_old=$(awk '/hostagent patch number:/ {c=$NF; gsub(/[^[:alnum:]]/,"",c); print c}' "${_arg_share}${m_sarmap[$i]}hostagent.mf") + if [[ ${m_ver[$i]} -gt ${m_old} ]]; then + removeold "${i}" + extractnew "${i}" + fi + else + removeold "${i}" + extractnew "${i}" + fi +done From 2432dd93b74b85c5eea1ae9c3146dccfa962ca9d Mon Sep 17 00:00:00 2001 From: bartik Date: Mon, 29 Aug 2022 14:14:21 +0200 Subject: [PATCH 03/19] Create host_profile --- host_profile | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 host_profile diff --git a/host_profile b/host_profile new file mode 100644 index 0000000..ab501a7 --- /dev/null +++ b/host_profile @@ -0,0 +1,14 @@ +SAPSYSTEMNAME = SAP +SAPSYSTEM = 99 +DIR_LIBRARY = /usr/sap/hostctrl/exe +DIR_EXECUTABLE = /usr/sap/hostctrl/exe +DIR_PROFILE = /usr/sap/hostctrl/exe +DIR_GLOBAL = /usr/sap/hostctrl/exe +DIR_INSTANCE = /usr/sap/hostctrl/exe +DIR_HOME = /usr/sap/hostctrl/work +service/porttypes = SAPHostControl SAPOscol SAPCCMS +DIR_NEW = /export/SAP/software/saphostagent/AIX/powerpc +#DIR_NEW = /export/SAP/software/saphostagent/Linux/x86_64 +#DIR_NEW = /export/SAP/software/saphostagent/Linux/ppc64le +#DIR_NEW = /export/SAP/software/saphostagent/Windows/x86_64 +hostexec/autoupgrade_delay=5 From 2db017d06ffb9eac8f3988f85c42a6b804e23c4e Mon Sep 17 00:00:00 2001 From: bartik Date: Mon, 29 Aug 2022 14:14:59 +0200 Subject: [PATCH 04/19] Rename extract.sh to saphostagent_extract.sh --- extract.sh => saphostagent_extract.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename extract.sh => saphostagent_extract.sh (100%) diff --git a/extract.sh b/saphostagent_extract.sh similarity index 100% rename from extract.sh rename to saphostagent_extract.sh From c4ff2fe0ca06cf73bda35ae9b29ec051ba0fcd0d Mon Sep 17 00:00:00 2001 From: bartik Date: Mon, 29 Aug 2022 14:15:19 +0200 Subject: [PATCH 05/19] Rename host_profile to saphostagent_host_profile --- host_profile => saphostagent_host_profile | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename host_profile => saphostagent_host_profile (100%) diff --git a/host_profile b/saphostagent_host_profile similarity index 100% rename from host_profile rename to saphostagent_host_profile From 41195954e942e21897f67c5ffab590872b1049a3 Mon Sep 17 00:00:00 2001 From: bartik Date: Mon, 29 Aug 2022 14:20:50 +0200 Subject: [PATCH 06/19] Create saphostagent_autoupdate.sh --- saphostagent_autoupdate.sh | 195 +++++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 saphostagent_autoupdate.sh diff --git a/saphostagent_autoupdate.sh b/saphostagent_autoupdate.sh new file mode 100644 index 0000000..1134884 --- /dev/null +++ b/saphostagent_autoupdate.sh @@ -0,0 +1,195 @@ +#!/bin/bash +# ARG_OPTIONAL_SINGLE([host],[h],[Hostname. (Default: hostname command result.)]) +# ARG_OPTIONAL_SINGLE([dir],[d],[Directory with hostagent executables.],['/usr/sap/hostctrl/exe/']) +# ARG_OPTIONAL_SINGLE([share],[s],[SAP shared directory.],['/export/SAP/software/saphostagent/']) +# ARG_OPTIONAL_SINGLE([delay],[e],[Autoupgrade delay in minutes.],[5]) +# ARG_OPTIONAL_SINGLE([tmp],[t],[Temporary directory.],['/tmp/']) +# ARG_HELP([Configure autoupdate parameters for hostagent.],[Configure autoupdate parameters for hostagent.],[?],[]) +# ARG_VERSION_AUTO([1.0]) + +export PS4='+(\D{%D %T} ${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' +set -euxo pipefail + +### START OF CODE GENERATED BY Argbash v2.9.0 one line above ### +# Argbash is a bash code generator used to get arguments parsing right. +# Argbash is FREE SOFTWARE, see https://argbash.io for more info +# Generated online by https://argbash.io/generate + +die() { + local _ret="${2:-1}" + test "${_PRINT_HELP:-no}" = yes && print_help >&2 + echo "$1" >&2 + exit "${_ret}" +} + +begins_with_short_option() { + local first_option all_short_options='hdset?v' + first_option="${1:0:1}" + test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0 +} + +# THE DEFAULTS INITIALIZATION - OPTIONALS +_arg_host=$(hostname) +_arg_dir='/usr/sap/hostctrl/exe/' +_arg_share='/export/SAP/software/saphostagent/' +_arg_delay="5" +_arg_tmp='/tmp/' + +print_help() { + printf '%s\n' "Configure autoupdate parameters for hostagent." + printf 'Usage: %s [-h|--host ] [-d|--dir ] [-s|--share ] [-e|--delay ] [-t|--tmp ] [-?|--help] [-v|--version]\n' "$0" + printf '\t%s\n' "-h, --host: Hostname. (Default: hostname command result.)" + printf '\t%s\n' "-d, --dir: Directory with hostagent executables. (default: /usr/sap/hostctrl/exe/)" + printf '\t%s\n' "-s, --share: SAP shared directory. (default: /export/SAP/software/saphostagent/)" + printf '\t%s\n' "-e, --delay: Autoupgrade delay in minutes. (default: 5)" + printf '\t%s\n' "-t, --tmp: Temporary directory. (default: /tmp/)" + printf '\t%s\n' "-?, --help: Prints help" + printf '\t%s\n' "-v, --version: Prints version" + printf '\n%s\n' "Configure autoupdate parameters for hostagent." +} + +parse_commandline() { + while test $# -gt 0; do + _key="$1" + case "$_key" in + -h | --host) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_host="$2" + shift + ;; + --host=*) + _arg_host="${_key##--host=}" + ;; + -h*) + _arg_host="${_key##-h}" + ;; + -d | --dir) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_dir="$2" + shift + ;; + --dir=*) + _arg_dir="${_key##--dir=}" + ;; + -d*) + _arg_dir="${_key##-d}" + ;; + -s | --share) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_share="$2" + shift + ;; + --share=*) + _arg_share="${_key##--share=}" + ;; + -s*) + _arg_share="${_key##-s}" + ;; + -e | --delay) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_delay="$2" + shift + ;; + --delay=*) + _arg_delay="${_key##--delay=}" + ;; + -e*) + _arg_delay="${_key##-e}" + ;; + -t | --tmp) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_tmp="$2" + shift + ;; + --tmp=*) + _arg_tmp="${_key##--tmp=}" + ;; + -t*) + _arg_tmp="${_key##-t}" + ;; + -\? | --help) + print_help + exit 0 + ;; + -\?*) + print_help + exit 0 + ;; + -v | --version) + printf '%s %s\n\n%s\n' "" "1.0" 'Configure autoupdate parameters for hostagent.' + exit 0 + ;; + -v*) + printf '%s %s\n\n%s\n' "" "1.0" 'Configure autoupdate parameters for hostagent.' + exit 0 + ;; + *) + _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1 + ;; + esac + shift + done +} + +parse_commandline "$@" + +# OTHER STUFF GENERATED BY Argbash + +### END OF CODE GENERATED BY Argbash (sortof) ### ]) +# [ <-- needed because of Argbash + +m_hostexec="${_arg_dir}saphostexec" +m_profile="${_arg_dir}host_profile" +m_autodir="${_arg_share}$(uname)/$(uname -p)" +m_link="${_arg_share}${_arg_host}" +m_entry_delay="hostexec/autoupgrade_delay = ${_arg_delay}" +m_entry_dirnew="DIR_NEW = ${m_link}" +m_flag_dirnew=0 +m_flag_delay=0 +m_uid_root="root" +m_uid_sapadm=20004 +m_uid_sapsys=20000 + +# set unique string +m_epoch=$(date +"%s") +m_sfx=$(printf "%X\n" "${m_epoch}") +m_tmp="${_arg_tmp}host_profile.${m_sfx}" + +# set-up autoupdate parameters in host_profile +while IFS= read -r M_LINE; do + case "${M_LINE}" in + DIR_NEW*) + echo "${m_entry_dirnew}" + m_flag_dirnew=1 + ;; + hostexec/autoupgrade_delay*) + echo "${m_entry_delay}" + m_flag_delay=1 + ;; + *) + echo "${M_LINE}" + ;; + esac +done <"${m_profile}" >"${m_tmp}" + +{ + if [[ ${m_flag_dirnew} == 0 ]]; then + echo "${m_entry_dirnew}" + fi + if [[ ${m_flag_delay} == 0 ]]; then + echo "${m_entry_delay}" + fi +} >>"${m_tmp}" + +ln -s -f "${m_autodir}" "${m_link}" +# The agreed upon user IDs for SAP users +# are not honored by all installs +# this causes also problems on shared +# filesystems therefore use numerical IDs +chown -h ${m_uid_sapadm}:${m_uid_sapsys} "${m_link}" + +# switch to the new configuration +mv "${m_profile}" "${_arg_tmp}" +mv "${m_tmp}" "${m_profile}" +chown ${m_uid_root}:${m_uid_sapsys} "${m_profile}" +"${m_hostexec}" -restart pf="${m_profile}" From a50530bcbf1091ef57e8f5bb02c78376d510b72f Mon Sep 17 00:00:00 2001 From: bartik Date: Mon, 29 Aug 2022 14:38:38 +0200 Subject: [PATCH 07/19] Create saphostagent_sso.sh --- saphostagent_sso.sh | 511 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 511 insertions(+) create mode 100644 saphostagent_sso.sh diff --git a/saphostagent_sso.sh b/saphostagent_sso.sh new file mode 100644 index 0000000..1b3977d --- /dev/null +++ b/saphostagent_sso.sh @@ -0,0 +1,511 @@ +#!/bin/bash +# ARG_OPTIONAL_SINGLE([host],[h],[Hostname. (Default: hostname command result.)]) +# ARG_OPTIONAL_SINGLE([dir],[r],[Directory with hostagent executables.],[/usr/sap/hostctrl/exe/]) +# ARG_OPTIONAL_SINGLE([share],[s],[SAP shared directory.],[/export/SAP/software/saphostagent/]) +# ARG_OPTIONAL_SINGLE([delay],[y],[Autoupgrade delay in minutes.],[5]) +# ARG_OPTIONAL_BOOLEAN([overwrite],[o],[Overwrite existing.],[off]) +# ARG_OPTIONAL_SINGLE([pse],[e],[PSE full path.]) +# ARG_OPTIONAL_SINGLE([tmp],[t],[Temporary directory.],[/tmp/]) +# ARG_OPTIONAL_SINGLE([subject],[j],[Certificate subject],[/C=DE/ST=Baden-Wuerttemberg/L=Beimerstetten/O=GCMA/OU=SCUBA/CN=SAP services]) +# ARG_OPTIONAL_SINGLE([user],[u],[Username.]) +# ARG_OPTIONAL_SINGLE([pass],[p],[Password.]) +# ARG_OPTIONAL_SINGLE([ip],[i],[Listen IP adress of saphostagent.]) +# ARG_OPTIONAL_SINGLE([rfile],[m],[Root certificate filename withoud path and extension.],[rootCA]) +# ARG_OPTIONAL_SINGLE([cfile],[n],[Client certificate filename withoud path and extension.],[monitoringCA]) +# ARG_OPTIONAL_SINGLE([uid],[d],[User ID of user sapadm if different from the one on shared storage], [11114]) +# ARG_OPTIONAL_SINGLE([gid],[g],[Group ID of group sapsys if different from the one on shared storage], [11110]) +# ARG_OPTIONAL_SINGLE([validity],[a],[Validity of the generated certificate in days.], [365]) +# ARG_HELP([Configure autoupdate parameters for hostagent.],[Configure autoupdate parameters for hostagent.],[?],[]) +# ARG_POSITIONAL_INF([function],[Function to execute with regard to sso.(root/server/client)],[1]) +# ARG_VERSION_AUTO([1.0]) + +export PS4='+(\D{%D %T} ${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' +set -euxo pipefail + +### START OF CODE GENERATED BY Argbash v2.9.0 one line above ### +# Argbash is a bash code generator used to get arguments parsing right. +# Argbash is FREE SOFTWARE, see https://argbash.io for more info +# Generated online by https://argbash.io/generate + +die() { + local _ret="${2:-1}" + test "${_PRINT_HELP:-no}" = yes && print_help >&2 + echo "$1" >&2 + exit "${_ret}" +} + +begins_with_short_option() { + local first_option all_short_options='hrsyetjupifdga?v' + first_option="${1:0:1}" + test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0 +} + +# THE DEFAULTS INITIALIZATION - POSITIONALS +_positionals=() +_arg_function=('') +# THE DEFAULTS INITIALIZATION - OPTIONALS +_arg_host="$(hostname)" +_arg_dir="/usr/sap/hostctrl/exe/" +_arg_share="/export/SAP/software/saphostagent/skript/" +_arg_delay=5 +_arg_pse= +_arg_tmp="/tmp/" +_arg_subject= +_arg_user="sapadm" +_arg_pass="OSsolman72" +_arg_ip=$(awk -v h="${_arg_host}" '$0 ~ h && /svc|service/ { print $1 }' /etc/hosts) +_arg_rfile="rootCA" +_arg_cfile="monitoringCA" +_arg_uid=11114 +_arg_gid=11110 +_arg_validity=365 +_arg_overwrite="off" +m_flag_ssl=0 +m_flag_ip=0 +m_flag_admin=0 +m_uid_root="root" +m_entry_ssl="saphostagent/ssl_setup = true" +m_entry_ip="service/http/hostname = " +m_entry_admin="service/sso_admin_user_0 = " + +print_help() { + printf '%s\n' "Configure SSO parameters for hostagent." + printf 'Usage: %s [-h|--host ] [-r|--dir ] [-s|--share ] [-y|--delay ] [-e|--pse ] [-t|--tmp ] [-j|--subject ] [-u|--user ] [-p|--pass ] [-i|--ip ] [-m|--rfile ] [-n|--cfile ] [-d|--uid ] [-g|--gid ] [-a|--validity ] [-?|--help] [-v|--version] [] ... [] ...\n' "$0" + printf '\t%s\n' ": Function to execute with regard to sso. (root/server/client)" + printf '\t%s\n' "-h, --host: Hostname. (Default: hostname command result.) (no default)" + printf '\t%s\n' "-r, --dir: Directory with hostagent executables. (default: '/usr/sap/hostctrl/exe/')" + printf '\t%s\n' "-s, --share: SAP shared directory. (default: '/export/SAP/software/saphostagent/')" + printf '\t%s\n' "-y, --delay: Autoupgrade delay in minutes. (default: '5')" + printf '\t%s\n' "-e, --pse: PSE full path. (no default)" + printf '\t%s\n' "-t, --tmp: Temporary directory. (default: '/tmp/')" + printf '\t%s\n' "-j, --subject: Certificate subject (default: '/C=DE/ST=Baden-Wuerttemberg/L=Beimerstetten/O=GCMA/OU=SCUBA/CN=SAP services')" + printf '\t%s\n' "-o, --overwrite, --no-overwrite: Overwrite existing. (off by default)" + printf '\t%s\n' "-u, --user: Username. (no default)" + printf '\t%s\n' "-p, --pass: Password. (no default)" + printf '\t%s\n' "-i, --ip: Listen IP adress of saphostagent. (no default)" + printf '\t%s\n' "-m, --rfile: Root certificate filename withoud path and extension. (default: 'rootCA')" + printf '\t%s\n' "-n, --cfile: Client certificate filename withoud path and extension. (default: 'monitoringCA')" + printf '\t%s\n' "-d, --uid: User ID of user sapadm if different from the one on shared storage (default: '11114')" + printf '\t%s\n' "-g, --gid: Group ID of group sapsys if different from the one on shared storage (default: '11110')" + printf '\t%s\n' "-a, --validity: Validity of the generated certificate in days. (default: '365')" + printf '\t%s\n' "-?, --help: Prints help" + printf '\t%s\n' "-v, --version: Prints version" + printf '\n%s\n' "Configure SSO parameters for hostagent." +} + +parse_commandline() { + _positionals_count=0 + while test $# -gt 0; do + _key="$1" + case "$_key" in + -h | --host) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_host="$2" + shift + ;; + --host=*) + _arg_host="${_key##--host=}" + ;; + -h*) + _arg_host="${_key##-h}" + ;; + -r | --dir) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_dir="$2" + shift + ;; + --dir=*) + _arg_dir="${_key##--dir=}" + ;; + -r*) + _arg_dir="${_key##-r}" + ;; + -s | --share) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_share="$2" + shift + ;; + --share=*) + _arg_share="${_key##--share=}" + ;; + -s*) + _arg_share="${_key##-s}" + ;; + -y | --delay) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_delay="$2" + shift + ;; + --delay=*) + _arg_delay="${_key##--delay=}" + ;; + -y*) + _arg_delay="${_key##-y}" + ;; + -e | --pse) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_pse="$2" + shift + ;; + --pse=*) + _arg_pse="${_key##--pse=}" + ;; + -e*) + _arg_pse="${_key##-e}" + ;; + -t | --tmp) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_tmp="$2" + shift + ;; + --tmp=*) + _arg_tmp="${_key##--tmp=}" + ;; + -t*) + _arg_tmp="${_key##-t}" + ;; + -j | --subject) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_subject="$2" + shift + ;; + --subject=*) + _arg_subject="${_key##--subject=}" + ;; + -j*) + _arg_subject="${_key##-j}" + ;; + -o | --no-overwrite | --overwrite) + _arg_overwrite="on" + test "${1:0:5}" = "--no-" && _arg_overwrite="off" + ;; + -o*) + _arg_overwrite="on" + _next="${_key##-o}" + if test -n "$_next" -a "$_next" != "$_key"; then + { begins_with_short_option "$_next" && shift && set -- "-o" "-${_next}" "$@"; } || die "The short option '$_key' can't be decomposed to ${_key:0:2} and -${_key:2}, because ${_key:0:2} doesn't accept value and '-${_key:2:1}' doesn't correspond to a short option." + fi + ;; + -u | --user) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_user="$2" + shift + ;; + --user=*) + _arg_user="${_key##--user=}" + ;; + -u*) + _arg_user="${_key##-u}" + ;; + -p | --pass) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_pass="$2" + shift + ;; + --pass=*) + _arg_pass="${_key##--pass=}" + ;; + -p*) + _arg_pass="${_key##-p}" + ;; + -i | --ip) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_ip="$2" + shift + ;; + --ip=*) + _arg_ip="${_key##--ip=}" + ;; + -i*) + _arg_ip="${_key##-i}" + ;; + -m | --rfile) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_rfile="$2" + shift + ;; + --rfile=*) + _arg_rfile="${_key##--rfile=}" + ;; + -m*) + _arg_rfile="${_key##-m}" + ;; + -n | --cfile) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_cfile="$2" + shift + ;; + --cfile=*) + _arg_cfile="${_key##--cfile=}" + ;; + -n*) + _arg_cfile="${_key##-n}" + ;; + -d | --uid) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_uid="$2" + shift + ;; + --uid=*) + _arg_uid="${_key##--uid=}" + ;; + -d*) + _arg_uid="${_key##-d}" + ;; + -g | --gid) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_gid="$2" + shift + ;; + --gid=*) + _arg_gid="${_key##--gid=}" + ;; + -g*) + _arg_gid="${_key##-g}" + ;; + -a | --validity) + test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1 + _arg_validity="$2" + shift + ;; + --validity=*) + _arg_validity="${_key##--validity=}" + ;; + -a*) + _arg_validity="${_key##-a}" + ;; + -\? | --help) + print_help + exit 0 + ;; + -\?*) + print_help + exit 0 + ;; + -v | --version) + printf '%s %s\n\n%s\n' "" "1.0" 'Configure autoupdate parameters for hostagent.' + exit 0 + ;; + -v*) + printf '%s %s\n\n%s\n' "" "1.0" 'Configure autoupdate parameters for hostagent.' + exit 0 + ;; + *) + _last_positional="$1" + _positionals+=("$_last_positional") + _positionals_count=$((_positionals_count + 1)) + ;; + esac + shift + done +} + +handle_passed_args_count() { + local _required_args_string="'function'" + test "${_positionals_count}" -ge 1 || _PRINT_HELP=yes die "FATAL ERROR: Not enough positional arguments - we require at least 1 (namely: $_required_args_string), but got only ${_positionals_count}." 1 +} + +assign_positional_args() { + local _positional_name _shift_for=$1 + _positional_names="_arg_function " + _our_args=$((${#_positionals[@]} - 1)) + for ((ii = 0; ii < _our_args; ii++)); do + _positional_names="$_positional_names _arg_function[$((ii + 1))]" + done + + shift "$_shift_for" + for _positional_name in ${_positional_names}; do + test $# -gt 0 || break + eval "$_positional_name=\${1}" || die "Error during argument parsing, possibly an Argbash bug." 1 + shift + done +} + +parse_commandline "$@" +handle_passed_args_count +assign_positional_args 1 "${_positionals[@]}" + +# OTHER STUFF GENERATED BY Argbash + +### END OF CODE GENERATED BY Argbash (sortof) ### ]) + +export LD_LIBRARY_PATH="${_arg_dir}" +export SECUDIR="${_arg_dir}sec" +m_profile="${_arg_dir}host_profile" +m_pse_server="${SECUDIR}/SAPSSLS.pse" +m_pse_client="${SECUDIR}/SAPSSLC.pse" +m_exe_openssl="openssl" +m_exe_sapgenpse="${_arg_dir}sapgenpse" +#m_p10=$(find ${SECUDIR} -type f -regex ".*${_arg_host}.*\.p10"|head -1) + +createPSE() +{ + # Parameter + m_pse=$1 + m_csrt=$2 + m_cn=$3 + + if [[ -f ${m_pse} && ${_arg_overwrite} != "on" ]]; then + # PSE exists generate csr only + "${m_exe_sapgenpse}" gen_pse -p "${m_pse}" \ + -onlyreq \ + -j \ + -r "${_arg_share}${m_csrt}.csr" \ + -k "GN-dNSName:${_arg_host}" \ + -k "GN-dNSName:localhost" \ + -k "GN-iPAddress:${_arg_ip}" \ + -k "GN-iPAddress:127.0.0.1" \ + -x "${_arg_pass}" + else + # Backup old PSE and make new + mv "${SECUDIR}" "${SECUDIR}.${m_sfx}" + mkdir -p "${SECUDIR}" + chown root:sapsys "${SECUDIR}" + cd "${SECUDIR}" || exit + + # Create PSE + "${m_exe_sapgenpse}" gen_pse -p "${m_pse}" \ + -k "GN-dNSName:${_arg_host}" \ + -k "GN-dNSName:localhost" \ + -k "GN-iPAddress:${_arg_ip}" \ + -k "GN-iPAddress:127.0.0.1" \ + -r "${_arg_share}${m_csrt}.csr" \ + -x "${_arg_pass}" "${m_cn}" + + # Grant Host Agent access to the PSE + "${m_exe_sapgenpse}" seclogin -p "${m_pse}" \ + -x "${_arg_pass}" \ + -O "${_arg_user}" + + # Allow file access + chmod 644 "${m_pse}" + fi + + # Set ownership on share + chown -h "${_arg_uid}":"${_arg_gid}" "${_arg_share}${m_csrt}.csr" + + # Verify CSR + "${m_exe_openssl}" req -in "${_arg_share}${m_csrt}.csr" -noout -text + + # Generate saphostagent cert + "${m_exe_openssl}" x509 -req \ + -extfile <(printf "subjectAltName=IP:%s,IP:127.0.0.1,DNS:%s,DNS:localhost" "${_arg_ip}" "${_arg_host}") \ + -in "${_arg_share}${m_csrt}.csr" \ + -passin pass:"${_arg_pass}" \ + -CA "${_arg_share}${_arg_rfile}.crt" \ + -CAkey "${_arg_share}${_arg_rfile}.key" \ + -CAcreateserial \ + -out "${_arg_share}${m_csrt}.crt" \ + -days "${_arg_validity}" \ + -sha256 + + # verify cert + "${m_exe_openssl}" x509 -in "${_arg_share}${m_csrt}.crt" -noout -text + + # import to Server PSE + "${m_exe_sapgenpse}" import_own_cert -p "${m_pse}" \ + -x "${_arg_pass}" \ + -c "${_arg_share}${m_csrt}.crt" \ + -r "${_arg_share}${_arg_rfile}.crt" + + # Verify the chain + "${m_exe_sapgenpse}" get_my_name -p "${m_pse}" \ + -x "${_arg_pass}" \ + -v +} + +if [[ ${_arg_function[0]} == "root" ]]; then + + # default subject for root certificate + if [[ ${#_arg_subject} -lt 1 ]]; then + _arg_subject="/C=DE/ST=Baden-Wuerttemberg/L=Beimerstetten/O=GCME/OU=SCUBA/CN=SAP services" + fi + "${m_exe_openssl}" genrsa -des3 \ + -passout pass:"${_arg_pass}" \ + -out "${_arg_share}${_arg_rfile}.key" \ + 4096 + "${m_exe_openssl}" req -x509 -new -nodes \ + -passin pass:"${_arg_pass}" \ + -subj "${_arg_subject}" \ + -key "${_arg_share}${_arg_rfile}.key" \ + -sha256 -days "${_arg_validity}" \ + -out "${_arg_share}${_arg_rfile}.crt" +elif [[ ${_arg_function[0]} == "server" ]]; then + + # default subject for server certificate + if [[ ${#_arg_subject} -lt 1 ]]; then + _arg_subject="CN=${_arg_host}.service.dc" + fi + + # set unique string + m_epoch=$(date +"%s") + m_sfx=$(printf "%X\n" "${m_epoch}") + + # stop the agent + "${_arg_dir}saphostexec" -stop + + createPSE "${m_pse_server}" "${_arg_host}" "${_arg_subject}" + + # Import monitoring client cert into PSE + "${m_exe_sapgenpse}" maintain_pk -p "${m_pse}" \ + -x "${_arg_pass}" \ + -a "${_arg_share}${_arg_cfile}.crt" + + # Extract subject from monitoring certificate + m_cn_client=$("${m_exe_openssl}" x509 -in "${_arg_share}${_arg_cfile}.crt" -noout -subject) + m_cn_client=${m_cn_client#*/} + m_cn_client=${m_cn_client//\//,} + + # Configure settings + while IFS= read -r m_line; do + case "${m_line}" in + saphostagent/ssl_setup*) + echo "${m_entry_ssl}" + m_flag_ssl=1 + ;; + service/http/hostname*) + echo "${m_entry_ip}${_arg_ip}" + m_flag_ip=1 + ;; + service/sso_admin_user_0*) + echo "${m_entry_admin}${m_cn_client}" + m_flag_admin=1 + ;; + *) + echo "${m_line}" + ;; + esac + done <"${m_profile}" >"${_arg_tmp}host_profile.${m_sfx}" + + { + if [[ ${m_flag_ssl} == 0 ]]; then + echo "${m_entry_ssl}" + fi + if [[ ${m_flag_ip} == 0 ]]; then + echo "${m_entry_ip}${_arg_ip}" + fi + if [[ ${m_flag_admin} == 0 ]]; then + echo "${m_entry_admin}${m_cn_client}" + fi + } >>"${_arg_tmp}host_profile.${m_sfx}" + + # switch configuration + mv "${m_profile}" "${_arg_tmp}" + mv "${_arg_tmp}host_profile.${m_sfx}" "${m_profile}" + chown -h "${m_uid_root}":"${_arg_gid}" "${m_profile}" + + # Restart Host Agent + "${_arg_dir}saphostexec" -restart pf="${m_profile}" +elif [[ ${_arg_function[0]} == "client" ]]; then + + # default subject for server certificate + if [[ ${#_arg_subject} -lt 1 ]]; then + _arg_subject="CN=monitoring" + fi + + # set unique string + m_epoch=$(date +"%s") + m_sfx=$(printf "%X\n" "${m_epoch}") + + createPSE "${m_pse_client}" "${_arg_cfile}" "${_arg_subject}" +fi From c0ff25a892856657136b53d8443d626b22ea135a Mon Sep 17 00:00:00 2001 From: bartik Date: Thu, 1 Sep 2022 14:35:02 +0200 Subject: [PATCH 08/19] Update saphostagent_sso.sh --- saphostagent_sso.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/saphostagent_sso.sh b/saphostagent_sso.sh index 1b3977d..515425a 100644 --- a/saphostagent_sso.sh +++ b/saphostagent_sso.sh @@ -52,7 +52,7 @@ _arg_pse= _arg_tmp="/tmp/" _arg_subject= _arg_user="sapadm" -_arg_pass="OSsolman72" +_arg_pass="THEpassword99" _arg_ip=$(awk -v h="${_arg_host}" '$0 ~ h && /svc|service/ { print $1 }' /etc/hosts) _arg_rfile="rootCA" _arg_cfile="monitoringCA" From deca57e030c60d1b4e0a8310181acdffb2be6dde Mon Sep 17 00:00:00 2001 From: bartik Date: Fri, 14 Oct 2022 09:19:26 +0200 Subject: [PATCH 09/19] check_maxdb added --- check_maxdb.pl | 252 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 check_maxdb.pl diff --git a/check_maxdb.pl b/check_maxdb.pl new file mode 100644 index 0000000..0b13751 --- /dev/null +++ b/check_maxdb.pl @@ -0,0 +1,252 @@ +#!/usr/bin/perl -w +############################## check_maxdb ############## +# Version : 0.50 +# Author : Mark Rittinghaus (rittinghaus.mark@lumberg.com) +# Licence : GPL - http://www.fsf.org/licenses/gpl.txt +################################################################# +# +# Help : ./check_maxdb.pl -h +# + +use strict; +use Getopt::Long; +use Time::Local; + +#set the path for the dmcli command +#my $dbmcli = "/usr/sapdb/clients/MaxDB/bin/dbmcli"; +my $dbmcli = "/sapdb/programs/bin/dbmcli"; + +# Nagios specific +use lib "/usr/local/nagios/libexec"; +use utils qw(%ERRORS); + +my $Version= '0.5'; +my $o_help= undef; # wan't some help ? +my $o_type= undef; # Check type +my $o_host= undef; # Database Server +my $o_dbname= undef; # Database +my $o_user= undef; # Database user +my $o_version= undef; # print version +my $o_warn= undef; # warning level option +my $o_crit= undef; # Critical level option +my $o_hours= undef; # hours for backup check +my $o_perf= undef; # Performance data + +########## functions ####### +sub isnnum { # Return true if arg is not a number + my $num = shift; + if ( $num =~ /^(\d+\.?\d*)|(^\.\d+)$/ ) { return 0 ;} + return 1; +} + +sub p_version { print "check_maxdb_data version : $Version\n"; } + +# functions +sub print_usage { + print "Usage: $0 -t -H -d -u -w -c \n"; + } + + +sub help { + print "\nMaxDB checks for Nagios version ",$Version,"\n"; + print "(c)2011 to Lumberg Holding - Author: Mark Rittinghaus\n\n"; + print "You need the database manager command line interface\n"; + print "for the MaxDB database system.\n"; + print "Set the variable \$dbmcli to the path of your dbmcli program.\n\n"; + print_usage(); + print < \$o_help, 'help' => \$o_help, + 't:s' => \$o_type, 'type:s' => \$o_type, + 'H:s' => \$o_host, 'hostname:s' => \$o_host, + 'd:s' => \$o_dbname, 'dbname:s' => \$o_dbname, + 'u:s' => \$o_user, 'user:s' => \$o_user, + 'V' => \$o_version, 'version' => \$o_version, + 'c:s' => \$o_crit, 'critical:s' => \$o_crit, + 'w:s' => \$o_warn, 'warn:s' => \$o_warn, + 'b:s' => \$o_hours, 'backup-hours' => \$o_hours, + 'f' => \$o_perf, 'perfparse' => \$o_perf, + ); + if (defined ($o_help) ) { help(); exit $ERRORS{"UNKNOWN"}}; + if (defined($o_version)) { p_version(); exit $ERRORS{"UNKNOWN"}}; + if ( !defined($o_type) ) + { print "No check type defiend!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; + if ( ($o_type ne 'L') && ($o_type ne 'l') && + ($o_type ne 'D') && ($o_type ne 'd') && + ($o_type ne 'B') && ($o_type ne 'b') && + ($o_type ne 'S') && ($o_type ne 's') ) + { print "wrong check type!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; + if ((( $o_type eq 'B' ) || ( $o_type eq 'b' )) && !defined($o_hours)) + { print "No hours for backup history check defiend!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; + if ((( $o_type eq 'B' ) || ( $o_type eq 'b' )) && defined($o_hours)) + { if ( isnnum($o_hours) ) { print "Numeric value for backup hours!\n";print_usage(); exit $ERRORS{"UNKNOWN"} }; } + if ( !defined($o_host) ) # check host and filter + { print "No host defined!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; + if ( !defined ($o_dbname)) + { print "No database defined!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; + if ( !defined($o_user)) + { print "No user defiend!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}; + + #Check Warning and crit are present + if (( $o_type ne 'S' ) && ( $o_type ne 's' )) { + if ( ! defined($o_warn) || ! defined($o_crit)) + { print "Put warning and critical values!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}; + # Get rid of % sign + $o_warn =~ s/\%//g; + $o_crit =~ s/\%//g; + if ( isnnum($o_warn) || isnnum($o_crit)) + { print "Numeric value for warning or critical !\n";print_usage(); exit $ERRORS{"UNKNOWN"} }; + if ( ($o_crit != 0) && ($o_warn > $o_crit) ) + { print "warning <= critical ! \n";print_usage(); exit $ERRORS{"UNKNOWN"}}; + if ( ($o_crit > 100) || ($o_warn > 100) ) + { print "warning or critical <= 100! \n";print_usage(); exit $ERRORS{"UNKNOWN"}}; + } +} +####### Query the database ##### +sub query { + # execute dbcli + my $ausgabe = `$dbmcli -n $o_host -d $o_dbname -u $o_user $_[0]|grep -v OK|grep -v END|grep -v CONTINUE`; + if ( $ausgabe =~ /^Error!/ ) + { print $ausgabe; + exit $ERRORS{"CRITICAL"}; + } + return $ausgabe; + } +########## end of functions ######### + +########## MAIN ####### +check_options(); +my $ausgabe; +my $label; +my @data; # query values +my $used_perc; # percentage used +my $used_mb; # used data +my $size_mb; # maximum capacity +my $used_byte; +my $size_byte; +my $output = ""; # Output +my $output_perf = ""; # Output performance data + +# check Data Area +if (($o_type eq 'd') || ($o_type eq 'D')) { + $ausgabe = query("sql_execute SELECT SIZE, USED_PERM_PAGES FROM SYSDD.SERVERDB_STATS"); + my @data = split /;/, $ausgabe; + $size_byte = ($data[0]) * 8 * 1024; + $used_byte = ($data[1]) * 8 * 1024; + $data[0] = ($data[0] * 8) / 1024; + $data[1] = ($data[1] * 8) / 1024; + $used_perc = sprintf "%.2f", 100 - (($data[0] - $data[1]) / ($data[0] / 100)); + $size_mb = sprintf "%.0f", $data[0]; + $used_mb = sprintf "%.0f", $data[1]; + if ($used_perc >= $o_crit) { + $label = "CRITICAL"; + } elsif ($used_perc >= $o_warn) { + $label = "WARNING"; + } else { + $label = "OK"; + } + $output = "$label: Data Area used ". $used_perc. "% (". $used_mb. "MB/". $size_mb. "MB)"; + # perfdata + $output_perf = "total=". $size_byte. " used=". $used_byte. " percent=". $used_perc. "%;" . $o_warn . ";" . $o_crit; + +# check Log Area +} elsif (($o_type eq 'l') || ($o_type eq 'L')) { + $ausgabe = query("sql_execute SELECT LOG_PAGES, USED_LOG_PAGES, LOG_NOT_SAVED FROM SYSDD.SERVERDB_STATS"); + my @data = split /;/, $ausgabe; + $size_byte = ($data[0] * 8) * 1024; + $used_byte = ($data[1] * 8) * 1024; + $data[0] = ($data[0] * 8) / 1024; + $data[1] = ($data[1] * 8) / 1024; + $used_perc = sprintf "%.2f", 100 - (($data[0] - $data[1]) / ($data[0] / 100)); + $size_mb = sprintf "%.2f", $data[0]; + $used_mb = sprintf "%.2f", $data[1]; + if ($used_perc >= $o_crit) { + $label = "CRITICAL"; + } elsif ($used_perc >= $o_warn) { + $label = "WARNING"; + + } else { + $label = "OK"; + } + $output = "$label: Log Area used ". $used_perc. "% (". $used_mb. "MB/". $size_mb. "MB)"; + # perfdata + $output_perf = "total=". $size_byte. " used=". $used_byte. " percent=". $used_perc. "%;" . $o_warn . ";" . $o_crit; + +# check backup history on any failed backups +} elsif (($o_type eq 'b') || ($o_type eq 'B')) { + query("backup_history_open"); + $ausgabe = query("backup_history_list -c LABEL,ACTION,START,RC,ERROR -I"); + my @data = split /\012/, $ausgabe; + my $backups_failed = 0; + foreach (@data) { + my @backup_set = split /\|/, $_; + # calculation of date and comparison + my @date_time = split /\s+/, $backup_set[2]; + my ($year, $month, $day) = split /-/, $date_time[0]; + my ($hour, $minute, $second) = split /:/, $date_time[1]; + my $now = time - (3600 * $o_hours); + my $time = timelocal($second, $minute, $hour, $day, ($month - 1), $year); + if (($now <= $time) && ($backup_set[3] != 0)) { $backups_failed++; } + } + if ($backups_failed >= $o_crit) { + $label = "CRITICAL"; + } elsif ($backups_failed >= $o_warn) { + $label = "WARNING"; + } else { + $label = "OK"; + } + $output = "$label: ". $backups_failed. " backups in the last ". $o_hours. " hours failed"; + $output_perf = "\"backups failed=\"" . $backups_failed . ";$o_warn;$o_crit" + +# check database status +} elsif (($o_type eq 's') || ($o_type eq 'S')) { + $ausgabe = query("db_state"); + my @data = split /\012/, $ausgabe; + if ($data[1] eq "OFFLINE") { + $label = "CRITICAL"; + } elsif (($data[1] eq "COLD") || ($data[1] eq "ADMIN")) { + $label = "WARNING"; + } elsif ($data[1] eq "ONLINE") { + $label = "OK"; + } else { + exit $ERRORS{"UNKNOWN"}; + } + $output = "$label: Database status is: " . $data[1]; +} + if (defined($o_perf) and $output_perf ne "") { + print $output, " | " , $output_perf , "\n"; + } + else { print $output , "\n"; } + exit $ERRORS{"$label"}; +########## end of MAIN ######### From c5055a5e9ea65339fa6ddb5da6c1911509c82a60 Mon Sep 17 00:00:00 2001 From: bartik Date: Fri, 14 Oct 2022 09:32:02 +0200 Subject: [PATCH 10/19] check_maxdb perltidy --- check_maxdb.pl | 364 ++++++++++++++++++++++++++----------------------- 1 file changed, 190 insertions(+), 174 deletions(-) diff --git a/check_maxdb.pl b/check_maxdb.pl index 0b13751..03d02f9 100644 --- a/check_maxdb.pl +++ b/check_maxdb.pl @@ -20,22 +20,22 @@ use lib "/usr/local/nagios/libexec"; use utils qw(%ERRORS); -my $Version= '0.5'; -my $o_help= undef; # wan't some help ? -my $o_type= undef; # Check type -my $o_host= undef; # Database Server -my $o_dbname= undef; # Database -my $o_user= undef; # Database user -my $o_version= undef; # print version -my $o_warn= undef; # warning level option -my $o_crit= undef; # Critical level option -my $o_hours= undef; # hours for backup check -my $o_perf= undef; # Performance data +my $Version = '0.5'; +my $o_help = undef; # wan't some help ? +my $o_type = undef; # Check type +my $o_host = undef; # Database Server +my $o_dbname = undef; # Database +my $o_user = undef; # Database user +my $o_version = undef; # print version +my $o_warn = undef; # warning level option +my $o_crit = undef; # Critical level option +my $o_hours = undef; # hours for backup check +my $o_perf = undef; # Performance data ########## functions ####### -sub isnnum { # Return true if arg is not a number +sub isnnum { # Return true if arg is not a number my $num = shift; - if ( $num =~ /^(\d+\.?\d*)|(^\.\d+)$/ ) { return 0 ;} + if ( $num =~ /^(\d+\.?\d*)|(^\.\d+)$/ ) { return 0; } return 1; } @@ -43,18 +43,17 @@ sub isnnum { # Return true if arg is not a number # functions sub print_usage { - print "Usage: $0 -t -H -d -u -w -c \n"; - } - + print "Usage: $0 -t -H -d -u -w -c \n"; +} sub help { - print "\nMaxDB checks for Nagios version ",$Version,"\n"; - print "(c)2011 to Lumberg Holding - Author: Mark Rittinghaus\n\n"; - print "You need the database manager command line interface\n"; - print "for the MaxDB database system.\n"; - print "Set the variable \$dbmcli to the path of your dbmcli program.\n\n"; - print_usage(); - print < \$o_help, 'help' => \$o_help, - 't:s' => \$o_type, 'type:s' => \$o_type, - 'H:s' => \$o_host, 'hostname:s' => \$o_host, - 'd:s' => \$o_dbname, 'dbname:s' => \$o_dbname, - 'u:s' => \$o_user, 'user:s' => \$o_user, - 'V' => \$o_version, 'version' => \$o_version, - 'c:s' => \$o_crit, 'critical:s' => \$o_crit, - 'w:s' => \$o_warn, 'warn:s' => \$o_warn, - 'b:s' => \$o_hours, 'backup-hours' => \$o_hours, - 'f' => \$o_perf, 'perfparse' => \$o_perf, - ); - if (defined ($o_help) ) { help(); exit $ERRORS{"UNKNOWN"}}; - if (defined($o_version)) { p_version(); exit $ERRORS{"UNKNOWN"}}; - if ( !defined($o_type) ) - { print "No check type defiend!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; - if ( ($o_type ne 'L') && ($o_type ne 'l') && - ($o_type ne 'D') && ($o_type ne 'd') && - ($o_type ne 'B') && ($o_type ne 'b') && - ($o_type ne 'S') && ($o_type ne 's') ) - { print "wrong check type!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; - if ((( $o_type eq 'B' ) || ( $o_type eq 'b' )) && !defined($o_hours)) - { print "No hours for backup history check defiend!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; - if ((( $o_type eq 'B' ) || ( $o_type eq 'b' )) && defined($o_hours)) - { if ( isnnum($o_hours) ) { print "Numeric value for backup hours!\n";print_usage(); exit $ERRORS{"UNKNOWN"} }; } - if ( !defined($o_host) ) # check host and filter - { print "No host defined!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; - if ( !defined ($o_dbname)) - { print "No database defined!\n";print_usage(); exit $ERRORS{"UNKNOWN"}}; - if ( !defined($o_user)) - { print "No user defiend!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}; - - #Check Warning and crit are present - if (( $o_type ne 'S' ) && ( $o_type ne 's' )) { - if ( ! defined($o_warn) || ! defined($o_crit)) - { print "Put warning and critical values!\n"; print_usage(); exit $ERRORS{"UNKNOWN"}}; - # Get rid of % sign - $o_warn =~ s/\%//g; - $o_crit =~ s/\%//g; - if ( isnnum($o_warn) || isnnum($o_crit)) - { print "Numeric value for warning or critical !\n";print_usage(); exit $ERRORS{"UNKNOWN"} }; - if ( ($o_crit != 0) && ($o_warn > $o_crit) ) - { print "warning <= critical ! \n";print_usage(); exit $ERRORS{"UNKNOWN"}}; - if ( ($o_crit > 100) || ($o_warn > 100) ) - { print "warning or critical <= 100! \n";print_usage(); exit $ERRORS{"UNKNOWN"}}; - } + Getopt::Long::Configure("bundling"); + GetOptions( + 'h' => \$o_help, + 'help' => \$o_help, + 't:s' => \$o_type, + 'type:s' => \$o_type, + 'H:s' => \$o_host, + 'hostname:s' => \$o_host, + 'd:s' => \$o_dbname, + 'dbname:s' => \$o_dbname, + 'u:s' => \$o_user, + 'user:s' => \$o_user, + 'V' => \$o_version, + 'version' => \$o_version, + 'c:s' => \$o_crit, + 'critical:s' => \$o_crit, + 'w:s' => \$o_warn, + 'warn:s' => \$o_warn, + 'b:s' => \$o_hours, + 'backup-hours' => \$o_hours, + 'f' => \$o_perf, + 'perfparse' => \$o_perf, + ); + if ( defined($o_help) ) { help(); exit $ERRORS{"UNKNOWN"} } + if ( defined($o_version) ) { p_version(); exit $ERRORS{"UNKNOWN"} } + if ( !defined($o_type) ) { print "No check type defiend!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + if ( ( $o_type ne 'L' ) && ( $o_type ne 'l' ) && ( $o_type ne 'D' ) && ( $o_type ne 'd' ) && ( $o_type ne 'B' ) && ( $o_type ne 'b' ) && ( $o_type ne 'S' ) && ( $o_type ne 's' ) ) { print "wrong check type!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + if ( ( ( $o_type eq 'B' ) || ( $o_type eq 'b' ) ) && !defined($o_hours) ) { print "No hours for backup history check defiend!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + if ( ( ( $o_type eq 'B' ) || ( $o_type eq 'b' ) ) && defined($o_hours) ) { + if ( isnnum($o_hours) ) { print "Numeric value for backup hours!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + } + if ( !defined($o_host) ) # check host and filter + { print "No host defined!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + if ( !defined($o_dbname) ) { print "No database defined!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + if ( !defined($o_user) ) { print "No user defiend!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + + #Check Warning and crit are present + if ( ( $o_type ne 'S' ) && ( $o_type ne 's' ) ) { + if ( !defined($o_warn) || !defined($o_crit) ) { print "Put warning and critical values!\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + + # Get rid of % sign + $o_warn =~ s/\%//g; + $o_crit =~ s/\%//g; + if ( isnnum($o_warn) || isnnum($o_crit) ) { print "Numeric value for warning or critical !\n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + if ( ( $o_crit != 0 ) && ( $o_warn > $o_crit ) ) { print "warning <= critical ! \n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + if ( ( $o_crit > 100 ) || ( $o_warn > 100 ) ) { print "warning or critical <= 100! \n"; print_usage(); exit $ERRORS{"UNKNOWN"} } + } } ####### Query the database ##### sub query { - # execute dbcli - my $ausgabe = `$dbmcli -n $o_host -d $o_dbname -u $o_user $_[0]|grep -v OK|grep -v END|grep -v CONTINUE`; - if ( $ausgabe =~ /^Error!/ ) - { print $ausgabe; - exit $ERRORS{"CRITICAL"}; - } - return $ausgabe; - } + + # execute dbcli + my $ausgabe = `$dbmcli -n $o_host -d $o_dbname -u $o_user $_[0]|grep -v OK|grep -v END|grep -v CONTINUE`; + if ( $ausgabe =~ /^Error!/ ) { + print $ausgabe; + exit $ERRORS{"CRITICAL"}; + } + return $ausgabe; +} ########## end of functions ######### ########## MAIN ####### check_options(); my $ausgabe; my $label; -my @data; # query values -my $used_perc; # percentage used -my $used_mb; # used data -my $size_mb; # maximum capacity +my @data; # query values +my $used_perc; # percentage used +my $used_mb; # used data +my $size_mb; # maximum capacity my $used_byte; my $size_byte; -my $output = ""; # Output -my $output_perf = ""; # Output performance data +my $output = ""; # Output +my $output_perf = ""; # Output performance data # check Data Area -if (($o_type eq 'd') || ($o_type eq 'D')) { - $ausgabe = query("sql_execute SELECT SIZE, USED_PERM_PAGES FROM SYSDD.SERVERDB_STATS"); - my @data = split /;/, $ausgabe; - $size_byte = ($data[0]) * 8 * 1024; - $used_byte = ($data[1]) * 8 * 1024; - $data[0] = ($data[0] * 8) / 1024; - $data[1] = ($data[1] * 8) / 1024; - $used_perc = sprintf "%.2f", 100 - (($data[0] - $data[1]) / ($data[0] / 100)); - $size_mb = sprintf "%.0f", $data[0]; - $used_mb = sprintf "%.0f", $data[1]; - if ($used_perc >= $o_crit) { - $label = "CRITICAL"; - } elsif ($used_perc >= $o_warn) { - $label = "WARNING"; - } else { - $label = "OK"; - } - $output = "$label: Data Area used ". $used_perc. "% (". $used_mb. "MB/". $size_mb. "MB)"; - # perfdata - $output_perf = "total=". $size_byte. " used=". $used_byte. " percent=". $used_perc. "%;" . $o_warn . ";" . $o_crit; - -# check Log Area -} elsif (($o_type eq 'l') || ($o_type eq 'L')) { - $ausgabe = query("sql_execute SELECT LOG_PAGES, USED_LOG_PAGES, LOG_NOT_SAVED FROM SYSDD.SERVERDB_STATS"); - my @data = split /;/, $ausgabe; - $size_byte = ($data[0] * 8) * 1024; - $used_byte = ($data[1] * 8) * 1024; - $data[0] = ($data[0] * 8) / 1024; - $data[1] = ($data[1] * 8) / 1024; - $used_perc = sprintf "%.2f", 100 - (($data[0] - $data[1]) / ($data[0] / 100)); - $size_mb = sprintf "%.2f", $data[0]; - $used_mb = sprintf "%.2f", $data[1]; - if ($used_perc >= $o_crit) { - $label = "CRITICAL"; - } elsif ($used_perc >= $o_warn) { - $label = "WARNING"; - - } else { - $label = "OK"; - } - $output = "$label: Log Area used ". $used_perc. "% (". $used_mb. "MB/". $size_mb. "MB)"; - # perfdata - $output_perf = "total=". $size_byte. " used=". $used_byte. " percent=". $used_perc. "%;" . $o_warn . ";" . $o_crit; - -# check backup history on any failed backups -} elsif (($o_type eq 'b') || ($o_type eq 'B')) { - query("backup_history_open"); - $ausgabe = query("backup_history_list -c LABEL,ACTION,START,RC,ERROR -I"); - my @data = split /\012/, $ausgabe; - my $backups_failed = 0; - foreach (@data) { - my @backup_set = split /\|/, $_; - # calculation of date and comparison - my @date_time = split /\s+/, $backup_set[2]; - my ($year, $month, $day) = split /-/, $date_time[0]; - my ($hour, $minute, $second) = split /:/, $date_time[1]; - my $now = time - (3600 * $o_hours); - my $time = timelocal($second, $minute, $hour, $day, ($month - 1), $year); - if (($now <= $time) && ($backup_set[3] != 0)) { $backups_failed++; } - } - if ($backups_failed >= $o_crit) { - $label = "CRITICAL"; - } elsif ($backups_failed >= $o_warn) { - $label = "WARNING"; - } else { - $label = "OK"; - } - $output = "$label: ". $backups_failed. " backups in the last ". $o_hours. " hours failed"; - $output_perf = "\"backups failed=\"" . $backups_failed . ";$o_warn;$o_crit" - -# check database status -} elsif (($o_type eq 's') || ($o_type eq 'S')) { - $ausgabe = query("db_state"); - my @data = split /\012/, $ausgabe; - if ($data[1] eq "OFFLINE") { - $label = "CRITICAL"; - } elsif (($data[1] eq "COLD") || ($data[1] eq "ADMIN")) { - $label = "WARNING"; - } elsif ($data[1] eq "ONLINE") { - $label = "OK"; - } else { - exit $ERRORS{"UNKNOWN"}; - } - $output = "$label: Database status is: " . $data[1]; +if ( ( $o_type eq 'd' ) || ( $o_type eq 'D' ) ) { + $ausgabe = query("sql_execute SELECT SIZE, USED_PERM_PAGES FROM SYSDD.SERVERDB_STATS"); + my @data = split /;/, $ausgabe; + $size_byte = ( $data[0] ) * 8 * 1024; + $used_byte = ( $data[1] ) * 8 * 1024; + $data[0] = ( $data[0] * 8 ) / 1024; + $data[1] = ( $data[1] * 8 ) / 1024; + $used_perc = sprintf "%.2f", 100 - ( ( $data[0] - $data[1] ) / ( $data[0] / 100 ) ); + $size_mb = sprintf "%.0f", $data[0]; + $used_mb = sprintf "%.0f", $data[1]; + + if ( $used_perc >= $o_crit ) { + $label = "CRITICAL"; + } + elsif ( $used_perc >= $o_warn ) { + $label = "WARNING"; + } + else { + $label = "OK"; + } + $output = "$label: Data Area used " . $used_perc . "% (" . $used_mb . "MB/" . $size_mb . "MB)"; + + # perfdata + $output_perf = "total=" . $size_byte . " used=" . $used_byte . " percent=" . $used_perc . "%;" . $o_warn . ";" . $o_crit; + + # check Log Area +} +elsif ( ( $o_type eq 'l' ) || ( $o_type eq 'L' ) ) { + $ausgabe = query("sql_execute SELECT LOG_PAGES, USED_LOG_PAGES, LOG_NOT_SAVED FROM SYSDD.SERVERDB_STATS"); + my @data = split /;/, $ausgabe; + $size_byte = ( $data[0] * 8 ) * 1024; + $used_byte = ( $data[1] * 8 ) * 1024; + $data[0] = ( $data[0] * 8 ) / 1024; + $data[1] = ( $data[1] * 8 ) / 1024; + $used_perc = sprintf "%.2f", 100 - ( ( $data[0] - $data[1] ) / ( $data[0] / 100 ) ); + $size_mb = sprintf "%.2f", $data[0]; + $used_mb = sprintf "%.2f", $data[1]; + + if ( $used_perc >= $o_crit ) { + $label = "CRITICAL"; + } + elsif ( $used_perc >= $o_warn ) { + $label = "WARNING"; + + } + else { + $label = "OK"; + } + $output = "$label: Log Area used " . $used_perc . "% (" . $used_mb . "MB/" . $size_mb . "MB)"; + + # perfdata + $output_perf = "total=" . $size_byte . " used=" . $used_byte . " percent=" . $used_perc . "%;" . $o_warn . ";" . $o_crit; + + # check backup history on any failed backups +} +elsif ( ( $o_type eq 'b' ) || ( $o_type eq 'B' ) ) { + query("backup_history_open"); + $ausgabe = query("backup_history_list -c LABEL,ACTION,START,RC,ERROR -I"); + my @data = split /\012/, $ausgabe; + my $backups_failed = 0; + foreach (@data) { + my @backup_set = split /\|/, $_; + + # calculation of date and comparison + my @date_time = split /\s+/, $backup_set[2]; + my ( $year, $month, $day ) = split /-/, $date_time[0]; + my ( $hour, $minute, $second ) = split /:/, $date_time[1]; + my $now = time - ( 3600 * $o_hours ); + my $time = timelocal( $second, $minute, $hour, $day, ( $month - 1 ), $year ); + if ( ( $now <= $time ) && ( $backup_set[3] != 0 ) ) { $backups_failed++; } + } + if ( $backups_failed >= $o_crit ) { + $label = "CRITICAL"; + } + elsif ( $backups_failed >= $o_warn ) { + $label = "WARNING"; + } + else { + $label = "OK"; + } + $output = "$label: " . $backups_failed . " backups in the last " . $o_hours . " hours failed"; + $output_perf = "\"backups failed=\"" . $backups_failed . ";$o_warn;$o_crit" + + # check database status +} +elsif ( ( $o_type eq 's' ) || ( $o_type eq 'S' ) ) { + $ausgabe = query("db_state"); + my @data = split /\012/, $ausgabe; + if ( $data[1] eq "OFFLINE" ) { + $label = "CRITICAL"; + } + elsif ( ( $data[1] eq "COLD" ) || ( $data[1] eq "ADMIN" ) ) { + $label = "WARNING"; + } + elsif ( $data[1] eq "ONLINE" ) { + $label = "OK"; + } + else { + exit $ERRORS{"UNKNOWN"}; + } + $output = "$label: Database status is: " . $data[1]; +} +if ( defined($o_perf) and $output_perf ne "" ) { + print $output, " | ", $output_perf, "\n"; } - if (defined($o_perf) and $output_perf ne "") { - print $output, " | " , $output_perf , "\n"; - } - else { print $output , "\n"; } - exit $ERRORS{"$label"}; +else { print $output , "\n"; } +exit $ERRORS{"$label"}; ########## end of MAIN ######### From 32ee2294942eba19803e37b4ac0307b05d753b3b Mon Sep 17 00:00:00 2001 From: bartik Date: Sun, 13 Nov 2022 10:04:57 +0100 Subject: [PATCH 11/19] Create check_oracle.sh - pgrep replaced with ps+egrep --- check_oracle/check_oracle.sh | 306 +++++++++++++++++++++++++++++++++++ 1 file changed, 306 insertions(+) create mode 100644 check_oracle/check_oracle.sh diff --git a/check_oracle/check_oracle.sh b/check_oracle/check_oracle.sh new file mode 100644 index 0000000..798ee0b --- /dev/null +++ b/check_oracle/check_oracle.sh @@ -0,0 +1,306 @@ +#!/bin/sh +# +# latigid010@yahoo.com +# 01/06/2000 +# +# This Nagios plugin was created to check Oracle status +# + +PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin" +export PATH +PROGNAME=$(basename "$0") +PROGPATH=$(echo "$0" | sed -e 's,[\\/][^\\/][^\\/]*$,,') +REVISION="2.3.3" +PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin" + +. "$PROGPATH"/utils.sh + + +print_usage() { + echo "Usage:" + echo " $PROGNAME --tns " + echo " $PROGNAME --db " + echo " $PROGNAME --login " + echo " $PROGNAME --connect " + echo " $PROGNAME --cache " + echo " $PROGNAME --tablespace " + echo " $PROGNAME --oranames " + echo " $PROGNAME --help" + echo " $PROGNAME --version" +} + +print_help() { + print_revision "$PROGNAME" $REVISION + echo "" + print_usage + echo "" + echo "Check Oracle status" + echo "" + echo "--tns SID/IP Address" + echo " Check remote TNS server" + echo "--db SID" + echo " Check local database (search /bin/ps for PMON process) and check" + echo " filesystem for sgadefORACLE_SID.dbf" + echo "--login SID" + echo " Attempt a dummy login and alert if not ORA-01017: invalid username/password" + echo "--connect SID" + echo " Attempt a login and alert if an ORA- error is returned" + echo "--cache" + echo " Check local database for library and buffer cache hit ratios" + echo " ---> Requires Oracle user/password and SID specified." + echo " ---> Requires select on v_$sysstat and v_$librarycache" + echo "--tablespace" + echo " Check local database for tablespace capacity in ORACLE_SID" + echo " ---> Requires Oracle user/password specified." + echo " ---> Requires select on dba_data_files and dba_free_space" + echo "--oranames Hostname" + echo " Check remote Oracle Names server" + echo "--help" + echo " Print this help screen" + echo "--version" + echo " Print version and license information" + echo "" + echo "If the plugin doesn't work, check that the ORACLE_HOME environment" + echo "variable is set, that ORACLE_HOME/bin is in your PATH, and the" + echo "tnsnames.ora file is locatable and is properly configured." + echo "" + echo "When checking local database status your ORACLE_SID is case sensitive." + echo "" + echo "If you want to use a default Oracle home, add in your oratab file:" + echo "*:/opt/app/oracle/product/7.3.4:N" + echo "" + support +} + +case "$1" in +1) + cmd='--tns' + ;; +2) + cmd='--db' + ;; +*) + cmd="$1" + ;; +esac + +# Information options +case "$cmd" in +--help) + print_help + exit "$STATE_OK" + ;; +-h) + print_help + exit "$STATE_OK" + ;; +--version) + print_revision "$PROGNAME" $REVISION + exit "$STATE_OK" + ;; +-V) + print_revision "$PROGNAME" $REVISION + exit "$STATE_OK" + ;; +esac + +# Hunt down a reasonable ORACLE_HOME +if [ -z "$ORACLE_HOME" ] ; then + # Adjust to taste + for oratab in /var/opt/oracle/oratab /etc/oratab + do + [ ! -f $oratab ] && continue + ORACLE_HOME=`IFS=: + while read SID ORACLE_HOME junk; + do + if [ "$SID" = "$2" -o "$SID" = "*" ] ; then + echo "$ORACLE_HOME"; + exit; + fi; + done < $oratab` + [ -n "$ORACLE_HOME" ] && break + done +fi +# Last resort +[ -z "$ORACLE_HOME" -a -d "$PROGPATH"/oracle ] && ORACLE_HOME=$PROGPATH/oracle + +if [ "$cmd" != "--db" ]; then + if [ -z "$ORACLE_HOME" -o ! -d "$ORACLE_HOME" ] ; then + echo "Cannot determine ORACLE_HOME for sid $2" + exit "$STATE_UNKNOWN" + fi +fi +PATH=$PATH:$ORACLE_HOME/bin +LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib +export ORACLE_HOME PATH LD_LIBRARY_PATH + +case "$cmd" in +--tns) + tnschk=$(tnsping "$2") + tnschk2=$(echo "$tnschk" | grep -c OK) + if [ "${tnschk2}" -eq 1 ] ; then + tnschk3=${tnschk##*(}; tnschk3=${tnschk3%)*} + echo "OK - reply time ${tnschk3} from $2" + exit "$STATE_OK" + else + echo "No TNS Listener on $2" + exit "$STATE_CRITICAL" + fi + ;; +--oranames) + namesctl status "$2" | awk ' + /Server has been running for:/ { + msg = "OK: Up" + for (i = 6; i <= NF; i++) { + msg = msg " " $i + } + status = '"$STATE_OK"' + } + /error/ { + msg = "CRITICAL: " $0 + status = '"$STATE_CRITICAL"' + } + END { + print msg + exit status + }' + ;; +--db) + #pmonchk=$(pgrep -f "(asm|ora|xe)_pmon_${2}$" | wc -l) + pmonchk=$(ps -ef | egrep "(asm|ora|xe)_pmon_${2}$" | wc -l) + if [ "${pmonchk}" -ge 1 ] ; then + echo "${2} OK - ${pmonchk} PMON process(es) running" + exit "$STATE_OK" + #if [ -f $ORACLE_HOME/dbs/sga*${2}* ] ; then + #if [ ${pmonchk} -eq 1 ] ; then + #utime=`ls -la $ORACLE_HOME/dbs/sga*$2* | cut -c 43-55` + #echo "${2} OK - running since ${utime}" + #exit $STATE_OK + #fi + else + echo "${2} Database is DOWN" + exit "$STATE_CRITICAL" + fi + ;; +--login) + loginchk=$(sqlplus dummy/user@"$2" < /dev/null) + loginchk2=$(echo "$loginchk" | grep -c ORA-01017) + if [ "${loginchk2}" -eq 1 ] ; then + echo "OK - dummy login connected" + exit "$STATE_OK" + else + loginchk3=$(echo "$loginchk" | grep "ORA-" | head -1) + echo "CRITICAL - $loginchk3" + exit "$STATE_CRITICAL" + fi + ;; +--connect) + connectchk=$(sqlplus "$2" < /dev/null) + connectchk2=$(echo "$connectchk" | grep -c ORA-) + if [ "${connectchk2}" -eq 0 ] ; then + echo "OK - login successful" + exit "$STATE_OK" + else + connectchk3=$(echo "$connectchk" | grep "ORA-" | head -1) + echo "CRITICAL - $connectchk3" + exit "$STATE_CRITICAL" + fi + ;; +--cache) + if [ "${5}" -gt "${6}" ] ; then + echo "UNKNOWN - Warning level is less then Crit" + exit "$STATE_UNKNOWN" + fi + result=`sqlplus -s "${3}"/"${4}"@"${2}" << EOF +set pagesize 0 +set numf '9999999.99' +select (1-(pr.value/(dbg.value+cg.value)))*100 +from v\\$sysstat pr, v\\$sysstat dbg, v\\$sysstat cg +where pr.name='physical reads' +and dbg.name='db block gets' +and cg.name='consistent gets'; +EOF` + + if echo "$result" | grep -q 'ORA-' ; then + error=$(echo "$result" | grep "ORA-" | head -1) + echo "CRITICAL - $error" + exit "$STATE_CRITICAL" + fi + + buf_hr=$(echo "$result" | awk '/^[0-9\. \t]+$/ {print int($1)}') + buf_hrx=$(echo "$result" | awk '/^[0-9\. \t]+$/ {print $1}') + result=`sqlplus -s "${3}"/"${4}"@"${2}" << EOF +set pagesize 0 +set numf '9999999.99' +select sum(lc.pins)/(sum(lc.pins)+sum(lc.reloads))*100 +from v\\$librarycache lc; +EOF` + + if echo "$result" | grep -q 'ORA-' ; then + error=$(echo "$result" | grep "ORA-" | head -1) + echo "CRITICAL - $error" + exit "$STATE_CRITICAL" + fi + + lib_hr=$(echo "$result" | awk '/^[0-9\. \t]+$/ {print int($1)}') + lib_hrx=$(echo "$result" | awk '/^[0-9\. \t]+$/ {print $1}') + + if [ "$buf_hr" -le "${5}" -o "$lib_hr" -le "${5}" ] ; then + echo "${2} CRITICAL - Cache Hit Rates: $lib_hrx% Lib -- $buf_hrx% Buff|lib=$lib_hrx%;${6};${5};0;100 buffer=$buf_hrx%;${6};${5};0;100" + exit "$STATE_CRITICAL" + fi + if [ "$buf_hr" -le "${6}" -o "$lib_hr" -le "${6}" ] ; then + echo "${2} WARNING - Cache Hit Rates: $lib_hrx% Lib -- $buf_hrx% Buff|lib=$lib_hrx%;${6};${5};0;100 buffer=$buf_hrx%;${6};${5};0;100" + exit "$STATE_WARNING" + fi + echo "${2} OK - Cache Hit Rates: $lib_hrx% Lib -- $buf_hrx% Buff|lib=$lib_hrx%;${6};${5};0;100 buffer=$buf_hrx%;${6};${5};0;100" + + exit "$STATE_OK" + ;; +--tablespace) + if [ "${6}" -lt "${7}" ] ; then + echo "UNKNOWN - Warning level is more then Crit" + exit "$STATE_UNKNOWN" + fi + result=`sqlplus -s "${3}"/"${4}"@"${2}" << EOF +set pagesize 0 +set numf '9999999.99' +select NVL(b.free,0.0),a.total,100 - trunc(NVL(b.free,0.0)/a.total * 1000) / 10 prc +from ( +select tablespace_name,sum(bytes)/1024/1024 total +from dba_data_files group by tablespace_name) A +LEFT OUTER JOIN +( select tablespace_name,sum(bytes)/1024/1024 free +from dba_free_space group by tablespace_name) B +ON a.tablespace_name=b.tablespace_name WHERE a.tablespace_name='${5}'; +EOF` + + if echo "$result" | grep -q 'ORA-'; then + error=$(echo "$result" | grep 'ORA-' | head -1) + echo "CRITICAL - $error" + exit "$STATE_CRITICAL" + fi + + ts_free=$(echo "$result" | awk '/^[ 0-9\.\t ]+$/ {print int($1)}') + ts_total=$(echo "$result" | awk '/^[ 0-9\.\t ]+$/ {print int($2)}') + ts_pct=$(echo "$result" | awk '/^[ 0-9\.\t ]+$/ {print int($3)}') + ts_pctx=$(echo "$result" | awk '/^[ 0-9\.\t ]+$/ {print $3}') + if [ "$ts_free" -eq 0 -a "$ts_total" -eq 0 -a "$ts_pct" -eq 0 ] ; then + echo "No data returned by Oracle - tablespace $5 not found?" + exit "$STATE_UNKNOWN" + fi + if [ "$ts_pct" -ge "${6}" ] ; then + echo "${2} : ${5} CRITICAL - $ts_pctx% used [ $ts_free / $ts_total MB available ]|${5}=$ts_pctx%;${7};${6};0;100" + exit "$STATE_CRITICAL" + fi + if [ "$ts_pct" -ge "${7}" ] ; then + echo "${2} : ${5} WARNING - $ts_pctx% used [ $ts_free / $ts_total MB available ]|${5}=$ts_pctx%;${7};${6};0;100" + exit "$STATE_WARNING" + fi + echo "${2} : ${5} OK - $ts_pctx% used [ $ts_free / $ts_total MB available ]|${5}=$ts_pctx%;${7};${6};0;100" + exit "$STATE_OK" + ;; +*) + print_usage + exit "$STATE_UNKNOWN" +esac From 285180241c68e2dc8597350aaa3085f625253c84 Mon Sep 17 00:00:00 2001 From: bartik Date: Sun, 13 Nov 2022 10:05:20 +0100 Subject: [PATCH 12/19] Create utils.sh --- check_oracle/utils.sh | 111 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 check_oracle/utils.sh diff --git a/check_oracle/utils.sh b/check_oracle/utils.sh new file mode 100644 index 0000000..142168d --- /dev/null +++ b/check_oracle/utils.sh @@ -0,0 +1,111 @@ +#! /bin/sh + +STATE_OK=0 +STATE_WARNING=1 +STATE_CRITICAL=2 +STATE_UNKNOWN=3 +STATE_DEPENDENT=4 + +print_revision() { + echo "$1 v$2 (nagios-plugins 2.3.3)" + printf '%b' "The nagios plugins come with ABSOLUTELY NO WARRANTY. You may redistribute\ncopies of the plugins under the terms of the GNU General Public License.\nFor more information about these matters, see the file named COPYING.\n" +} + +support() { + printf '%b' "Send email to help@nagios-plugins.org if you have questions regarding use\nof this software. To submit patches or suggest improvements, send email to\ndevel@nagios-plugins.org. Please include version information with all\ncorrespondence (when possible, use output from the --version option of the\nplugin itself).\n" +} + +# +# check_range takes a value and a range string, returning successfully if an +# alert should be raised based on the range. Range values are inclusive. +# Values may be integers or floats. +# +# Example usage: +# +# Generating an exit code of 1: +# check_range 5 2:8 +# +# Generating an exit code of 0: +# check_range 1 2:8 +# +check_range() { + local v range yes no err decimal start end cmp match + v="$1" + range="$2" + + # whether to raise an alert or not + yes=0 + no=1 + err=2 + + # regex to match a decimal number + decimal="-?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)" + + # compare numbers (including decimals), returning true/false + cmp() { awk "BEGIN{ if ($1) exit(0); exit(1)}"; } + + # returns successfully if the string in the first argument matches the + # regex in the second + match() { echo "$1" | grep -E -q -- "$2"; } + + # make sure value is valid + if ! match "$v" "^$decimal$"; then + echo "${0##*/}: check_range: invalid value" >&2 + unset -f cmp match + return "$err" + fi + + # make sure range is valid + if ! match "$range" "^@?(~|$decimal)(:($decimal)?)?$"; then + echo "${0##*/}: check_range: invalid range" >&2 + unset -f cmp match + return "$err" + fi + + # check for leading @ char, which negates the range + if match $range '^@'; then + range=${range#@} + yes=1 + no=0 + fi + + # parse the range string + if ! match "$range" ':'; then + start=0 + end="$range" + else + start="${range%%:*}" + end="${range#*:}" + fi + + # do the comparison, taking positive ("") and negative infinity ("~") + # into account + if [ "$start" != "~" ] && [ "$end" != "" ]; then + if cmp "$start <= $v" && cmp "$v <= $end"; then + unset -f cmp match + return "$no" + else + unset -f cmp match + return "$yes" + fi + elif [ "$start" != "~" ] && [ "$end" = "" ]; then + if cmp "$start <= $v"; then + unset -f cmp match + return "$no" + else + unset -f cmp match + return "$yes" + fi + elif [ "$start" = "~" ] && [ "$end" != "" ]; then + if cmp "$v <= $end"; then + unset -f cmp match + return "$no" + else + unset -f cmp match + return "$yes" + fi + else + unset -f cmp match + return "$no" + fi +} From 37120e711446527e85a358e7d9159d4c3114dbeb Mon Sep 17 00:00:00 2001 From: bartik Date: Sun, 13 Nov 2022 10:11:11 +0100 Subject: [PATCH 13/19] Update README.md --- README.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 23d0f3f..b332d87 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,12 @@ -# nagios-scripts -Scripts for monitoring using Nagios +# sap-nagios-scripts +Scripts for monitoring using Nagios modified to fit for reasons like: + +- not every nix* has a pgrep installed +- Perl can be a ... to install on some platforms +- You won't be allowed to install random ... in serious places to get the fancies running. * check_sybase_ase.sh -Full description of script: https://www.bersler.com/blog/nagios-script-for-checking-sap-adaptive-server-enterprise-sybase-ase/ + +* check_oracle +https://www.monitoring-plugins.org/doc/man/check_oracle.html From 7cff5e2eb6ffc723a9db230340774b35a250bf4f Mon Sep 17 00:00:00 2001 From: bartik Date: Sun, 13 Nov 2022 10:11:59 +0100 Subject: [PATCH 14/19] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b332d87..c8e7245 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Scripts for monitoring using Nagios modified to fit for reasons like: - not every nix* has a pgrep installed - Perl can be a ... to install on some platforms -- You won't be allowed to install random ... in serious places to get the fancies running. +- You won't be allowed to install random ... in serious places just to get the fancies running. * check_sybase_ase.sh https://www.bersler.com/blog/nagios-script-for-checking-sap-adaptive-server-enterprise-sybase-ase/ From 1e0b82496a3397911d815a99fe209f1d12c124a6 Mon Sep 17 00:00:00 2001 From: bartik Date: Tue, 15 Nov 2022 15:34:38 +0100 Subject: [PATCH 15/19] Create sap_maxdb_syscopy.sh --- sap_maxdb_syscopy.sh | 1923 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1923 insertions(+) create mode 100644 sap_maxdb_syscopy.sh diff --git a/sap_maxdb_syscopy.sh b/sap_maxdb_syscopy.sh new file mode 100644 index 0000000..7c20df1 --- /dev/null +++ b/sap_maxdb_syscopy.sh @@ -0,0 +1,1923 @@ +#!/usr/bin/bash + +# SYSCOPY MaxDB AIX/LINUX ############################################################################### +################################################################################ (c) 2022 Florian Lamml # + +# Prerequisites ######################################################################################### +# - copy this script to the source host and set the execution right # +# - ssh communication between source and target without password (authorized_keys) for both sidadm # +# via "ssh-keygen -t rsa -b 2048" and ".ssh/authorized_keys" (only source --> target) # +# --> ssh sourceadm@sourcehost must work without PW # +# --> ssh targetadm@targethost must work without PW # +# - the target database is large enough (automatic check) # +# - xuser DEFAULT for ABAP/JAVA DB User (SAP or SAPDB) must be available # +# - if passwords from source and target are different, xuser for copy can not be used # +# - the source database must be online, the target database must be able to start in state admin # +# - adjust the configuration of source and target system in this script # +# - best use with screen tool for unix/linux # +# - under Linux it can happen that you have to change the first line # +# from "#!/usr/bin/bash" to "#!/bin/bash" (check bash with "which bash") # +######################################################################################################### + +# Features ############################################################################################## +# - automatic function and prerequisites check # +# - backup to 2 parallel PIPE # +# - can use compressed and uncompressed backup (default uncompress) # +# - root is not needed # +# - copy status bar with size, transfered, left and speed (5 second update) # +# - automatic size check # +# - dd over ssh from source to target # +# - ssh encryption default cipher is aes192-ctr # +# - automatic rename database to target # +# - automatic export of custom tables (incl. templates of the most common) # +# - you can use a custom db user or xuser for backup and restore # +######################################################################################################### + +# Exit Codes ############################################################################################ +# exit 0 = normal or user exit # +# exit 99 = script run as root # +# exit 98 = another script is running # +# exit 97 = source database is not available # +# exit 96 = source database size bigger than target database max size # +# exit 95 = error in backup start # +# exit 94 = error in restore start # +# exit 93 = error in backup # +# exit 92 = error in restore # +# exit 91 = error with SSH on source # +# exit 90 = error with SSH on target # +# exit 89 = error with temporary status files on source # +# exit 88 = error with temporary status files on target # +# exit 87 = error with pipes on source # +# exit 86 = error with pipes on target # +# exit 85 = error in config check # +# exit 84 = error in target db start # +# exit 83 = error in target backup template create # +# exit 82 = error in source backup template create # +# exit 81 = error in rename target db # +######################################################################################################### + +# Configuration start ################################################################################### +# configuration need to be adjusted +# +# source host (example: server1 or the IP) +export sourcehost=server1 +# +# target host (example: server2 or the IP) +export targethost=server2 +# +# source SID (example: AAA) +export sourcesid=AAA +# +# target SID (example: BBB) +export targetsid=BBB +# +# logfile name (example/default: DB_Copy_AAAtoBBB_01011900.log) +export dbcopylog=DB_Copy_"$sourcesid"to"$targetsid"_$(date "+%d%m%Y").log +# +# send mail after syscopy (default no) +export sendfinishmail=no +export mailadress=user@domain.tld +# +# +#### Export / Import Options #### +# save sec directory with the sap certificates (default yes, saved in cdD/cdJ as syscopy_sec) +export savesecdir=yes +# define if abap or java (default abap) +export abaporjava=abap +#custom table export and imports (default is only e070l and sap license, yes or no) +# Export location on target (default /tmp, without ending / -> /tmp = OK, /tmp/ = NOT OK) +export exportlocation=/tmp +# import after syscopy (default yes) +export autoimport=yes +# export/import client (default 000, only all or 000, DO NOT USE ANY OTHER CLIENT) +export expimpclient=000 +# export E070L (default yes, should be done if target is an existing system) +export e07lexport=yes +# SAP License (default yes) +export licexport=yes +# RZ10 Profiles +export rz10export=no +# RZ04 Operation Modes +export rz04export=no +# STRUST +export strustexport=no +# STRUSTSSO2 +export strustsso2export=no +# STMS_QA (manual refresh in SAP needed before you can start) +export stmsqaexport=no +# STMS configuration +export stmsexport=no +# AL11 +export al11export=no +# BD54 +export bd54export=no +# FILE +export fileexport=no +# RZ70/SLD configuration +export rz70sldexport=no +# SCOT +export scotexport=no +# SICF services +export sicfexport=no +# RFC connections +export rfcconnectionsexport=no +# SM69 external commands +export sm69export=no +# WE20 WE21 BD97 +export we202197export=no +# SMLG/RZ12 +export smlgrz12export=no +# ABAP Dev (only if target is a development system) +export abapdevexport=no +# GTS/SLL Export +export gtssllexport=no +# OAC0 +export oac0export=no +# SCC4 +export scc4export=no +# Report Variants +export reportvariants=no +# DBACOCKPIT +export dbacockpit=no +# HTTPURLLOC +export httpurlloc=no +# LDAP +export ldap=no +# VSCAN +export vscan=no +# SPAD +export spad=no +# EWZ5 +export ewz5=no +# SBGRFCCONF +export sbgrfcconf=no +# SBWP +export sbwp=no +# SECPOL +export secpol=no +# SECSTORE +export secstore=no +# SM19 +export sm19=no +# Custom Tables (adjust array tables_customtables like this ('table1' 'table2' 'table3') if / in Table name -> ''\''/TABPART/TABPART'\') +export customtables=no +declare -a tables_customtables=('table1' 'table2' 'table3') +# +#### Expert Options #### +# change only if you know exactly what you are doing # +# +# use xuser instead of normal db user (default yes) +# Info: If you use xuser, no passwords will shown at the console +# Info: use 'xuser list' to show the available xusers +# WARNING: CAN NOT BE USED IF TARGET AND SOURCE DB USERS HAVE DIFFERENT PASSWORDS! +# WARNING: If the passwords of the target and source db users are different you have to set no! +export usexuser=yes +# +# xuserkey source (default w, xusersource need at least Backup, DBInfoRead, AccessUtility and SystemCmd) +export xusersource=w +# +# xuserkey target (default w, xusertarget need at least DBStart, DBStop, DBInfoRead, AccessUtility, SystemCmd, AccessSQL, LoadSysTab and Recovery) +export xusertarget=w +# +# source db user for backup (default SUPERDBA, need at least Backup, DBInfoRead, AccessUtility and SystemCmd) +# Warning: If you use db users, passwords will shown at the console +# only used if usexuser=no +export dbsourceuser=SUPERDBA +# +# target db user for restore (default SUPERDBA, need at least DBStart, DBStop, DBInfoRead, AccessUtility, SystemCmd, AccessSQL, LoadSysTab and Recovery) +# Warning: If you use db users, passwords will shown at the console +# only used if usexuser=no +export dbtargetuser=SUPERDBA +# +# second clear log run (default is no, yes or no) +export secondclearlog=no +# +# compressed backup (default is no, yes or no) +# Warning: can adversely affect the performance of the source system! +export backupcompressed=no +# +# ssh cipher (default aes192-ctr, example: arcfour, arcfour128, arcfour256, aes192-ctr, aes256-ctr, aes192-cbc, aes256-cbc etc.) +# on IBM Power7 "arcfour" is the fastest, on IBM Power8 "aes192-ctr" is best of security and speed +export sshcipher=aes192-ctr +# +# MaxDB pipe size (default 128 (1MB), value in pages and 1 page = 8 KB) +# dd blocksize and MaxDB pipe size are interdependent! +# pipesize should half blocksize (blocksize in k / 8 / 2) +# Warning: can adversely affect the performance of the source system! +# low performance impact but lower speed --> 8-32 +# high performance impact but faster --> >= 64 +export pipesize=128 +# +# dd blocksize (default is automatic calculated, example: 8k, 512k, 1M, 16M) +# dd blocksize and MaxDB pipe size are interdependent! +# blocksize should be double pipesize (pipesize * 8 * 2 k) +# Warning: can adversely affect the performance of the source system! +export blocksize=$(echo "($pipesize*8*2)" | bc -l)k +# export blocksize=2048k +# +# disable CTRL+C on some points to prevent damage and endless processes (default yes) +export disablectrlc=yes +# +# remove export file after successfull import (default no) +export remexpafterimp=no +# +# enable batch mode (no security question, default no) +# INFO: to run in batchmode you have to use nohup (example "nohup db_copy_xx.sh &") +# INFO: batchmode is only possible if you use xuser! +export enablebatch=no +# +# +#### Transport and SQL configuration #### +# change only if you know exactly what you are doing # +# +# sql tables to delete +declare -a sql_deltables=('ALCONSEG' 'ALSYSTEMS' 'DBSNP' 'MONI' 'OSMON' 'PAHI' 'SDBAD' 'SDBAH' 'SDBAP' 'SDBAR' 'DDLOG' 'TPFET' 'TPFHT' 'TLOCK' 'CNHIST' 'CNREPRT' 'CNMEDIA' 'DBSTATHADA' 'DBSTATIHADA' 'DBSTATIADA' 'DBSTATTADA' 'SDBAADAUPD') +# e07lexport +declare -a tables_e07lexport=('E070L') +# licexport +declare -a tables_licexport=('SAPLIKEY') +# rz10export +declare -a tables_rz10export=('TPFET' 'TPFHT') +# rz04export +declare -a tables_rz04export=('BTCOMSET' 'TPFBA' 'TPFID') +# strustexport +declare -a tables_strustexport=('SMIME_CAPA_CRYPT' 'SMIME_CAPA_SIGN' 'SMIME_CAPABILITY' 'SSF_PSE_D' 'SSF_PSE_H' 'SSF_PSE_HIST' 'SSF_PSE_L' 'SSF_PSE_T' 'SSFAPPLIC' 'SSFAPPLICT' 'SSFARGS' 'SSFVARGS' 'SSFVARGST' 'SSFVKEYDEF' 'STRUSTCAB' 'STRUSTCABEMAIL' 'STRUSTCERT' 'STRUSTCRL' 'STRUSTCRP' 'STRUSTCRPT' 'STRUSTCRR' 'STRUSTCRRT' 'STRUSTCRS' 'STRUSTCRT' 'STRUSTSMIM' 'STRUSTSMIMT' 'STRUSTSSL' 'STRUSTSSLS' 'STRUSTSSLST' 'STRUSTSSLT' 'STRUSTWSSE' 'STRUSTWSSET' 'TWPSSO2ACL' 'USERINFO_STORAGE' 'USRCERTMAP' 'USRCERTRULE') +# strustsso2export +declare -a tables_strustsso2export=('SNCSYSACL' 'TSP0U' 'TXCOMSECU' 'USRACL' 'USRACLEXT') +# stmsqaexport +declare -a tables_stmsqaexport=('TMSQNOTES' 'TMSQNOTESH' 'TMSQWLF' 'TMSQWLFH' 'TMSQWLH' 'TMSQWLN' 'TMSQWL' 'TMSQLASTWL') +# stmsexport +declare -a tables_stmsexport=('ALMBCDATA' 'DLV_SYSTC' 'E070L' 'E070USE' 'TCECLILY' 'TCECPSTAT' 'TCEDELI' 'TCERELE' 'TCESYST' 'TCESYSTT' 'TCETARG' 'TCETARGHDR' 'TCETARGT' 'TCETRAL' 'TCETRALT' 'TCEVERS' 'TCEVERST' 'TMSACTDAT' 'TMSALOG' 'TMSALOGAR' 'TMSALRTSYS' 'TMSBCIBOX' 'TMSBCIIBOX' 'TMSBCIJOY' 'TMSBCINEX' 'TMSBCINTAB' 'TMSBCIOBJ' 'TMSBCIXBOX' 'TMSBUFCNT' 'TMSBUFPRO' 'TMSBUFREQ' 'TMSBUFTXT' 'TMSCDES' 'TMSCDOM' 'TMSCDOMT' 'TMSCNFS' 'TMSCNFST' 'TMSCROUTE' 'TMSCSYS' 'TMSCSYST' 'TMSCTOK' 'TMSFSYSH' 'TMSFSYSL' 'TMSMCONF' 'TMSPCONF' 'TMSPVERS' 'TMSQASTEPS' 'TMSQASTEPT' 'TMSQASTEPZ' 'TMSQCONFRM' 'TMSSRV' 'TMSSRVT' 'TMSTLOCKNP' 'TMSTLOCKNR' 'TMSTLOCKP' 'TMSTLOCKR' 'TRBAT' 'TRJOB' 'TRNSPACE' 'TRNSPACEL' 'TRNSPACETT') +# al11export +declare -a tables_al11export=('USER_DIR') +# bd54export +declare -a tables_bd54export=('TBDLS' 'TBDLST') +# fileexport +declare -a tables_fileexport=('FILENAME' 'FILENAMECI' 'FILEPATH' 'FILESYS' 'FILETEXT' 'FILETEXTCI' 'FSYSTXT' 'OPSYSTEM' 'OPTEXT' 'PARAMVALUE' 'PATH' 'PATHTEXT' 'USER_DIR') +# rz70sldexport +declare -a tables_rz70sldexport=('LCRT_INDX' 'SLDAGADM') +# scotexport +declare -a tables_scotexport=('BCSD_BLMODULE' 'BCSD_BREAKLOOP' 'BCSD_RQST' 'BCSD_STML' 'SXADMINTAB' 'SXCONVERT' 'SXCONVERT2' 'SXCOS' 'SXCOS_T' 'SXCPDEF' 'SXCPRECV' 'SXCPSEND' 'SXDEVTYPE' 'SXDEVTYPL' 'SXDOMAINS' 'SXJOBS' 'SXNODES' 'SXPARAMS' 'SXRETRY' 'SXROUTE' 'SXSERV' 'SXTELMOIN' 'SXTELMOOUT' 'T005J' 'T005K' 'TSAPD') +# sicfexport +declare -a tables_sicfexport=('ICF_SESSION_CNTL' 'ICFALIAS' 'ICFAPPLCUST' 'ICFAPPLICATION' 'ICFDOCU' 'ICFHANDLER' 'ICFINSTACT' 'ICFSECPASSWD' 'ICFSERVICE' 'ICFSERVLOC' 'ICFVIRHOST' 'TWPURLSVR') +# rfcconnectionsexport +declare -a tables_rfcconnectionsexport=('APC_CROSS_ORIGIN' 'RFC_TT_ACL' 'RFC_TT_ACL_HIST' 'RFC_TT_SAMEU' 'RFCADPTATTR' 'RFCATTRIB' 'RFCCAT' 'RFCCBWHITELIST' 'RFCCBWHITELIST_A' 'RFCCHECK' 'RFCCMC' 'RFCDES' 'RFCDESSECU' 'RFCDOC' 'RFCGO' 'RFC2SOAPS' 'RFCSOAPS' 'RFCSYSACL' 'RFCSYSACL_CLNT' 'RFCTRUST' 'RFCTXTAB' 'RFCSTXTAB' 'RFCTYPE' 'RSECACHK' 'RSECACTB' 'RSECKEYMETA' 'RSECTAB' 'SNCSYSACL') +# we202197export +declare -a tables_we202197export=('EDIPO' 'EDIPO2' 'EDIPOA' 'EDIPOACODPAG' 'EDIPOD' 'EDIPOF' 'EDIPOI' 'EDIPORT' 'EDIPOX' 'EDIPOXH' 'EDIPOXU' 'EDP12' 'EDP13' 'EDP21' 'EDPP1' 'TBLSYSDEST' 'TBSPECDEST') +# sm69export +declare -a tables_sm69export=('SXPGCOSTAB') +# smlgrz12export +declare -a tables_smlgrz12export=('RZLLICLASS' 'RZLLITAB') +# abapdevexport +declare -a tables_abapdevexport=('ADIRACCESS' 'DEVACCESS' 'ENHCONTRACTCONT' 'ENHLOG' 'ENHOBJCONTRACT' 'RSEUMOD' 'VRSD' 'VRSMODISRC' 'VRSX' 'VRSX2' 'VRSX3' 'VRSX4' 'VRSX5') +# gtssllexport +declare -a tables_gtssllexport=(''\''/SAPSLL/TCOGVA'\' ''\''/SAPSLL/TCOGVS'\' ''\''/SAPSLL/TCOGVST'\') +# oac0export +declare -a tables_oac0export=('TOAAR') +# scc4export +declare -a tables_scc4export=('T000' 'CLMS_TENANT') +# reportvariants +declare -a tables_reportvariants=('TVARVC' 'VARI' 'VARID' 'VARIDESC' 'VARINUM' 'VARIS' 'VARIT') +# dbacockpit +declare -a tables_dbacockpit=('DB6NAVSYST' 'DB6PMPROT' 'DBA_CONFIG' 'DBCON' 'DBCONUSR' 'SDBAD' 'SDBAH' 'SDBAP' 'SDBAR') +# httpurlloc +declare -a tables_httpurlloc=('HTTPURLLOC' 'IACORDES' 'IACORDEST' 'IACORSITE') +# ldap +declare -a tables_ldap=('LDAPGATEW' 'LDAPMAP1' 'LDAPMAP2' 'LDAPMAP3' 'LDAPMAP4' 'LDAPMAP5' 'LDAPMAP6' 'LDAPSERVER' 'LDAPSYNC' 'LDAPUSER') +# vscan +declare -a tables_vscan=('VSCAN_GROUP' 'VSCAN_GROUP_P' 'VSCAN_GROUPT' 'VSCAN_PROF' 'VSCAN_PROF_GRP' 'VSCAN_PROF_PAR' 'VSCAN_PROFT' 'VSCAN_SERVER') +# SPAD +declare -a tables_spad=('TSP03' 'TSP03A' 'TSP03C' 'TSP03D' 'TSP03L' 'TSP03POCCNF' 'TSP03POCPRE' 'TSP03T' 'TSP0B' 'TSP0K' 'TSPCMDS' 'TSPLOMS' 'TSPROMS' 'TSPSV') +# EWZ5 +declare -a tables_ewz5=('EWUUSERTYP') +# SBGRFCCONF +declare -a tables_sbgrfcconf=('BGRFC_CUST_I_DST' 'BGRFC_CUST_I_SRV' 'BGRFC_CUST_I_SYS' 'BGRFC_CUST_O_DST' 'BGRFC_CUST_O_SRV' 'BGRFC_CUST_O_SYS' 'BGRFC_CUST_SUPER' 'BGRFC_MAIN_I_DST' 'QRFC_CUST_I_DEST') +# SBWP +declare -a tables_sbwp=('SODM' 'SOFD' 'SOFM' 'SOID' 'SOOD' 'SOUB' 'SOUC' 'SOUD') +# SECPOL +declare -a tables_secpol=('SEC_POLICY_CUST' 'SEC_POLICY_CUSTT' 'SEC_POLICY_RT') +# SECSTORE +declare -a tables_secstore=('RSECACTB' 'RSECTAB' 'RSECTAB') +# SM19 +declare -a tables_sm19=('RSAU_BUF_DATA' 'RSAU_TEMP_CDATA' 'RSAU_TEMP_DATA' 'RSAUFILES' 'RSAUFILES_STAT' 'RSAUPROF' 'RSAUPROFEX') +# Configuration end ##################################################################################### + +# INFOS AND CHECKS ###################################################################################### + +# variables - do NOT modify +export targetsidadm=$(echo $targetsid | tr '[:upper:]' '[:lower:]')adm +export sourcesidadm=$(echo $sourcesid | tr '[:upper:]' '[:lower:]')adm +export pipedate=$(date "+%d%m%Y") +export workdirectory=$(pwd) +export dbcopy_script_version='GitHub Version 1.3.1 (c) Florian Lamml - 2022' + +# clear screen +clear + +### define functions ### +# mail batch check +function sendmailcheckbatch { +if [ $sendfinishmail == yes ] && [ $enablebatch == yes ]; +then + echo $RCCODE | mail -s "System Copy $sourcesid to $targetsid ERROR in checks" "$mailadress" +fi +} + +# function batchmode ssh source +function batchmodesshsource { +ssh -oBatchMode=yes -oForwardX11=no -c $sshcipher $sourcesidadm@$sourcehost "$1" +} + +# function batchmode ssh target +function batchmodesshtarget { +ssh -oBatchMode=yes -oForwardX11=no -c $sshcipher $targetsidadm@$targethost "$1" +} + +# function ssh source +function sshsource { +ssh -oForwardX11=no -c $sshcipher $sourcesidadm@$sourcehost "$1" +} + +# function ssh target +function sshtarget { +ssh -oForwardX11=no -c $sshcipher $targetsidadm@$targethost "$1" +} + +# sleep and space +function sleepandspace { + sleep 1 + echo "=====" | tee -a $dbcopylog + sleep 1 +} + +# send mail normal +function sendmailnormal { +if [ $sendfinishmail == yes ]; +then + cat $dbcopylog | mail -s "System Copy $sourcesid to $targetsid finish" "$mailadress" +fi +} + +# send mail batch +function sendmailbatch { +if [ $sendfinishmail == yes ] && [ $enablebatch == yes ]; +then + cat $dbcopylog | mail -s "System Copy $sourcesid to $targetsid ERROR" "$mailadress" +fi +} +### define functions ### + +# do some checks +echo "====================================" +echo "DB Copy Script "$(date "+%d.%m.%Y %H:%M:%S") +echo $dbcopy_script_version +echo "====================================" +echo "Check environment, please wait..." + +# root check +echo -ne "* Check root... \c" +if [ "$(whoami)" == "root" ]; +then + echo "This script must not be run as root user! ... EXIT! (RC=99)" + export RCCODE="This script must not be run as root user! ... EXIT! (RC=99)" + sendmailcheckbatch + exit 99 +fi +sleep 1 +echo "OK!" + +# test source login an cipher +echo -ne "* Check SSH on source... \c" +batchmodesshsource 'exit' +if [ $? -ne 0 ]; + then + echo "Problem with SSH on source! .ssh/authorized_keys OK? SSH Cipher OK? known hosts OK? ... EXIT! (RC=91)" + export RCCODE="Problem with SSH on source! .ssh/authorized_keys OK? SSH Cipher OK? known hosts OK? ... EXIT! (RC=91)" + sendmailcheckbatch + exit 91 +fi +sleep 1 +echo "OK!" + +# test target login an cipher +echo -ne "* Check SSH on target... \c" +batchmodesshtarget 'exit' +if [ $? -ne 0 ]; + then + echo "Problem with SSH on target! .ssh/authorized_keys OK? SSH Cipher OK? known hosts OK? ... EXIT! (RC=90)" + export RCCODE="Problem with SSH on target! .ssh/authorized_keys OK? SSH Cipher OK? known hosts OK? ... EXIT! (RC=90)" + sendmailcheckbatch + exit 90 +fi +sleep 1 +echo "OK!" + +# lock file +echo -ne "* Check lockfile... \c" +export copylockfile=/tmp/dbcopy.lock +if [ -f $copylockfile ]; +then + kill -0 $(cat $copylockfile) &>/dev/null + if [ $? -eq 0 ]; + then + echo "Another copy script is still running. ... EXIT! (RC=98)" + export RCCODE="Another copy script is still running. ... EXIT! (RC=98)" + sendmailcheckbatch + exit 98 + else + echo -ne "Deprecated lock file found. Remove lock file. \c" + rm -f $copylockfile + fi +fi +sleep 1 +echo "OK!" + +# write lockfile +echo $$ > $copylockfile + +# logfile check +echo -ne "* Check logfile... \c" +if [ -f $dbcopylog ]; +then + echo -ne "Logfile with same name exists - rename to "$dbcopylog"."$(date "+%d%m%Y%H%M%S")"... \c" + mv $dbcopylog $dbcopylog.$(date "+%d%m%Y%H%M%S") +fi +sleep 1 +echo "OK!" + +# check config +echo -ne "* Check config... \c" +if [ $enablebatch == yes ] && [ $usexuser == no ]; +then + echo "Cannot run batchmode without xusers, check your config... EXIT! (RC=85)" + export RCCODE="Cannot run batchmode without xusers, check your config... EXIT! (RC=85)" + sendmailcheckbatch + exit 85 +elif [ -z "$sourcehost" ] || [ -z "$targethost" ] || [ -z "$sourcesid" ] || [ -z "$targetsid" ] || [ -z "$dbcopylog" ] || [ -z "$pipesize" ] || [ -z "$blocksize" ] || [ -z "$exportlocation" ]; +then + echo "Some parameter missing... EXIT! (RC=85)" + export RCCODE="Some parameter missing... EXIT! (RC=85)" + sendmailcheckbatch + exit 85 +fi +sleep 1 +echo "OK!" + +# check temporary status files source +echo -ne "* Check tempfile write on source... \c" +export check_tmprcheck=0 +declare -a check_tempstatusfiles=('/tmp/dbcopy_tmpbacklist' '/tmp/dbcopy_backuplog' '/tmp/dbcopy_backupend' '/tmp/dbcopy_tmp_recover_state' '/tmp/dbcopy_pipecopyend_1' '/tmp/dbcopy_pipecopyend_2' '/tmp/dbcopy_deltables.sql' '/tmp/dbcopy_tmp_exporttables.tpl' '/tmp/dbcopy_tmp_exporttables_unsort.tpl' '/tmp/dbcopy_tmp_exporttables_sort.tpl' '/tmp/dbcopy_dbsizetarget_'$sourcesid'' '/tmp/dbcopy_dbversion_'$sourcesid'') +for check_tempstatusfile in "${check_tempstatusfiles[@]}" +do + touch $check_tempstatusfile &>/dev/null + export check_tmprcheck=$(($check_tmprcheck + $?)) +done +if [ $check_tmprcheck -ne 0 ]; + then + echo "Problem to create temporary status files on source. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=89)" + rm -f $copylockfile + export RCCODE="Problem to create temporary status files on source. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=89)" + sendmailcheckbatch + exit 89 +fi +for check_tempstatusfile in "${check_tempstatusfiles[@]}" +do + rm $check_tempstatusfile +done +sleep 1 +echo "OK!" + +# check temporary status files target +echo -ne "* Check tempfile write on target... \c" +export check_tmprcheck=0 +declare -a check_tempstatusfiles=('/tmp/dbcopy_tmprestlist' '/tmp/dbcopy_restorelog' '/tmp/dbcopy_restoreend' '/tmp/dbcopy_deltables.sql' '/tmp/dbcopy_dbsizetarget_'$targetsid'' '/tmp/dbcopy_dbversion_'$targetsid'' ''$exportlocation'/'$targetsid'_dbcopy_exporttables.tpl' ''$exportlocation'/'$targetsid'_dbcopy_exporttables.log' '/tmp/dbcopy_renamedbsid' '/tmp/dbcopy_dbonline' '/tmp/dbcopy_changesqlpass') +for check_tempstatusfile in "${check_tempstatusfiles[@]}" +do + batchmodesshtarget 'touch '$check_tempstatusfile'' &>/dev/null + export check_tmprcheck=$(($check_tmprcheck + $?)) +done +if [ $check_tmprcheck -ne 0 ]; + then + echo "Problem to create temporary status files on target. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=88)" + rm -f $copylockfile + export RCCODE="Problem to create temporary status files on target. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=88)" + sendmailcheckbatch + exit 88 +fi +for check_tempstatusfile in "${check_tempstatusfiles[@]}" +do + batchmodesshtarget 'rm '$check_tempstatusfile'' +done +sleep 1 +echo "OK!" + +# check pipes on source +echo -ne "* Check pipes on source... \c" +export check_tmprcheck=0 +touch /tmp/"$sourcesid"to"$targetsid"_pipe_t_"$pipedate"_1 &>/dev/null +export tmprcheck=$(($tmprcheck + $?)) +touch /tmp/"$sourcesid"to"$targetsid"_pipe_t_"$pipedate"_2 &>/dev/null +export tmprcheck=$(($tmprcheck + $?)) +if [ $check_tmprcheck -ne 0 ]; + then + echo "Problem to create pipes on source. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=87)" + rm -f $copylockfile + export RCCODE="Problem to create pipes on source. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=87)" + sendmailcheckbatch + exit 87 +fi +rm /tmp/"$sourcesid"to"$targetsid"_pipe_t_"$pipedate"_1 +rm /tmp/"$sourcesid"to"$targetsid"_pipe_t_"$pipedate"_2 +sleep 1 +echo "OK!" + +# check pipes on target +echo -ne "* Check pipes on target... \c" +export check_tmprcheck=0 +batchmodesshtarget 'touch /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1' &>/dev/null +export tmprcheck=$(($tmprcheck + $?)) +batchmodesshtarget 'touch /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2' &>/dev/null +export tmprcheck=$(($tmprcheck + $?)) +if [ $check_tmprcheck -ne 0 ]; + then + echo "Problem to create pipes on target. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=86)" + rm -f $copylockfile + export RCCODE="Problem to create pipes on target. Check if there are in /tmp old data from a previous run! ... EXIT! (RC=86)" + sendmailcheckbatch + exit 86 +fi +batchmodesshtarget 'rm /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1' +batchmodesshtarget 'rm /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2' +sleep 1 +echo "OK!" + +#info +echo "====================================" +sleep 2 + +# clear screen +clear + +# message +echo "====================================" | tee -a $dbcopylog +echo "DB Copy Script "$(date "+%d.%m.%Y %H:%M:%S") | tee -a $dbcopylog +echo $dbcopy_script_version | tee -a $dbcopylog +echo "====================================" | tee -a $dbcopylog +echo "Source DB.........:" $sourcesid | tee -a $dbcopylog +echo "Source HOST.......:" $sourcehost | tee -a $dbcopylog +echo "Source SAPADM.....:" $sourcesidadm | tee -a $dbcopylog +if [ $usexuser == yes ]; +then + echo "Source XUSER Key..:" $xusersource | tee -a $dbcopylog +else + echo "Source DB User....:" $dbsourceuser | tee -a $dbcopylog +fi +echo "Target DB.........:" $targetsid | tee -a $dbcopylog +echo "Target HOST.......:" $targethost | tee -a $dbcopylog +echo "Target SAPADM.....:" $targetsidadm | tee -a $dbcopylog +if [ $usexuser == yes ]; +then + echo "Target XUSER Key..:" $xusertarget | tee -a $dbcopylog +else + echo "Target DB User....:" $dbtargetuser | tee -a $dbcopylog +fi +if [ $sourcehost == $targethost ]; +then + echo "Local System Copy.: yes" | tee -a $dbcopylog +fi +echo "DB Copy Logfile...:" $dbcopylog | tee -a $dbcopylog +echo "Compressed Backup.:" $backupcompressed | tee -a $dbcopylog +echo "SSH Cipher.......:" $sshcipher | tee -a $dbcopylog +echo "DD Blocksize......:" $blocksize | tee -a $dbcopylog +echo "MaxDB PIPE Size...:" $pipesize | tee -a $dbcopylog +echo "Save secdir.......:" $savesecdir | tee -a $dbcopylog +echo "Table Export......: yes/no" | tee -a $dbcopylog +echo "Table E/I Client..:" $expimpclient | tee -a $dbcopylog +echo "* SAP License.....:" $licexport | tee -a $dbcopylog +echo "* E070L...........:" $e07lexport | tee -a $dbcopylog +echo "* RZ10 Profiles...:" $rz10export | tee -a $dbcopylog +echo "* RZ04 Modes......:" $rz04export | tee -a $dbcopylog +echo "* STRUST..........:" $strustexport | tee -a $dbcopylog +echo "* STRUSTSSO2......:" $strustsso2export | tee -a $dbcopylog +echo "* STMS_QA.........:" $stmsqaexport | tee -a $dbcopylog +echo "* STMS............:" $stmsexport | tee -a $dbcopylog +echo "* AL11............:" $al11export | tee -a $dbcopylog +echo "* BD54............:" $bd54export | tee -a $dbcopylog +echo "* FILE............:" $fileexport | tee -a $dbcopylog +echo "* RZ70/SLD........:" $rz70sldexport | tee -a $dbcopylog +echo "* SCOT............:" $scotexport | tee -a $dbcopylog +echo "* SICF............:" $sicfexport | tee -a $dbcopylog +echo "* RFC Connections.:" $rfcconnectionsexport | tee -a $dbcopylog +echo "* WE20/WE21/DB97..:" $we202197export | tee -a $dbcopylog +echo "* SM69............:" $sm69export | tee -a $dbcopylog +echo "* SMLG/RZ12.......:" $smlgrz12export | tee -a $dbcopylog +echo "* ABAP DEV........:" $abapdevexport | tee -a $dbcopylog +echo "* GTS/SLL.........:" $gtssllexport | tee -a $dbcopylog +echo "* OAC0............:" $oac0export | tee -a $dbcopylog +echo "* SCC4............:" $scc4export | tee -a $dbcopylog +echo "* Report Variants.:" $reportvariants | tee -a $dbcopylog +echo "* DBACOCKPIT......:" $dbacockpit | tee -a $dbcopylog +echo "* HTTPURLLOC......:" $httpurlloc | tee -a $dbcopylog +echo "* LDAP............:" $ldap | tee -a $dbcopylog +echo "* VSCAN...........:" $vscan | tee -a $dbcopylog +echo "* SPAD............:" $spad | tee -a $dbcopylog +echo "* EWZ5............:" $ewz5 | tee -a $dbcopylog +echo "* SBGRFCCONF......:" $sbgrfcconf | tee -a $dbcopylog +echo "* SBWP............:" $sbwp | tee -a $dbcopylog +echo "* SECPOL..........:" $secpol | tee -a $dbcopylog +echo "* SM19............:" $sm19 | tee -a $dbcopylog +echo "* Custom Tables...:" $customtables | tee -a $dbcopylog +if [ $sendfinishmail == yes ]; +then + echo "Send mail to......:" $mailadress | tee -a $dbcopylog +fi +echo "====================================" | tee -a $dbcopylog +if [ $stmsqaexport == yes ]; + then +echo "************************************" | tee -a $dbcopylog +echo "ATTENTION: PLEASE UPDATE STMS_QA IN SOURCE BEFORE PROCEEDING" | tee -a $dbcopylog +echo "************************************" | tee -a $dbcopylog +echo "====================================" | tee -a $dbcopylog +fi + +# check if xuser is used or read passwords for db user +if [ $usexuser == yes ]; +then + # set connectioninformation + export dbmcliconnetsource="-U $xusersource" + export dbmcliconnettarget="-U $xusertarget" + export dbmcliconnetsourcesql="-USQL $xusersource" + export dbmcliconnettargetsql="-USQL $xusertarget" +else + # read passwords + echo $dbsourceuser "password of" $sourcesid ":" + # switch off echo + stty -echo + read sysdbapwdsource + # switch on echo + stty echo + echo $dbtargetuser "password of" $targetsid" :" + # switch off echo + stty -echo + read sysdbapwdtarget + # switch on echo + stty echo + echo "====================================" + # set connectioninformation + export dbmcliconnetsource="-u '$dbsourceuser','$sysdbapwdsource'" + export dbmcliconnettarget="-u '$dbtargetuser','$sysdbapwdtarget'" + export dbmcliconnetsourcesql="-uSQL '$dbsourceuser','$sysdbapwdsource'" + export dbmcliconnettargetsql="-uSQL '$dbtargetuser','$sysdbapwdtarget'" +fi + +# db size informations and checks +sshsource 'dbmcli -d '$sourcesid' '"$dbmcliconnetsource"' -o /tmp/dbcopy_dbsizesource_'$sourcesid' info state' +sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' -o /tmp/dbcopy_dbsizetarget_'$targetsid' info state' +export sourcesizekberror=$(sshsource 'grep "ERR" /tmp/dbcopy_dbsizesource_'$sourcesid'' | wc -l) +export sourcesizekb=$(sshsource 'grep "Data" /tmp/dbcopy_dbsizesource_'$sourcesid' | grep KB | grep -v Perm | grep -v Temp | grep -v Max' | awk '{ print $4 }') +export sourcesizemb=$(echo "scale=0;0$sourcesizekb/1024" | bc -l) +export targetmaxsizekberror=$(sshtarget 'grep "ERR" /tmp/dbcopy_dbsizetarget_'$targetsid'' | wc -l) +export targetmaxsizekb=$(sshtarget 'grep "Data Max" /tmp/dbcopy_dbsizetarget_'$targetsid' | grep KB' | awk '{ print $5 }') +export targetmaxsizemb=$(echo "scale=0;0$targetmaxsizekb/1024" | bc -l) + +# check source db +if [ $sourcesizekberror -ge 1 ]; +then + # message + echo "source database not available --> EXIT (RC=97)" + # logfile + echo "source database not available --> EXIT (RC=97) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # cleanup + sshtarget 'rm /tmp/dbcopy_dbsizetarget_'$targetsid'' + sshsource 'rm /tmp/dbcopy_dbsizesource_'$sourcesid'' + # send mail bath + sendmailbatch + exit 97; +else +# size check +if [ 1$sourcesizemb -gt 1$targetmaxsizemb ]; +then + # check target db + if [ $targetmaxsizekberror == 0 ]; + then + # message + echo "Size of source data in MB..........: " $sourcesizemb + echo "Maxsize of target database in MB...: " $targetmaxsizemb + echo "Error source database size bigger than target max database size --> EXIT (RC=96)" + # logfile + echo "Size of source data in MB..........: " $sourcesizemb " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "Maxsize of target database in MB...: " $targetmaxsizemb " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "Error source database size bigger than target max database size --> EXIT (RC=96) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # cleanup + sshtarget 'rm /tmp/dbcopy_dbsizetarget_'$targetsid'' + sshsource 'rm /tmp/dbcopy_dbsizesource_'$sourcesid'' + exit 96; + else + # message + sleep 1 + echo "Error - target database not available in state online" + echo "" + echo "Anyway, you can continue copy the system at your own risk!" + echo "" + echo "====================================" + # logfile + echo "Error target database not available, cannot check size "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "Anyway, you can continue copy the system at your own risk! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "==================================== "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # set noexport + export donotexport=1 + fi +else + # message + sleep 1 + echo "Size of source data in MB..........: " $sourcesizemb + echo "Maxsize of target database in MB...: " $targetmaxsizemb + echo "====================================" + # logfile + echo "Size of source data in MB..........: " $sourcesizemb " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "Maxsize of target database in MB...: " $targetmaxsizemb " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "====================================" >> $dbcopylog + # write E070L from source into log + echo "E070L from "$targetsid $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + sshtarget 'sqlcli -U DEFAULT -f "SELECT * FROM E070L"' &>> $dbcopylog + echo "====================================" >> $dbcopylog + # set noexport + export donotexport=0 +fi +fi + +# version check +sshsource 'dbmcli -d '$sourcesid' '"$dbmcliconnetsource"' -o /tmp/dbcopy_dbversion_'$sourcesid' dbm_version' +sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' -o /tmp/dbcopy_dbversion_'$targetsid' dbm_version' +export sourceversion=$(sshsource 'grep BUILD /tmp/dbcopy_dbversion_'$sourcesid'' | awk -F"= " '{ print $2 }') +export targetversion=$(sshtarget 'grep BUILD /tmp/dbcopy_dbversion_'$targetsid'' | awk -F"= " '{ print $2 }') +# message +sleep 1 +echo "Version of Source DB...............: " $sourceversion +echo "Version of Target DB...............: " $targetversion +if [ "$sourceversion" != "$targetversion" ]; + then + echo "************************************" + echo "ATTENTION: PLEASE CHECK THE DB VERSIONS!" + echo "SOURCE <= TARGET = OK" + echo "SOURCE > TARGET = NOT OK" + echo "************************************" +fi +echo "====================================" +# logfile +echo "Version of Source DB...............: " $sourceversion " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +echo "Version of Target DB...............: " $targetversion " "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +if [ "$sourceversion" != "$targetversion" ]; + then + echo "************************************" $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "ATTENTION: PLEASE CHECK THE DB VERSIONS!" $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "SOURCE <= TARGET = OK" $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "SOURCE > TARGET = NOT OK" $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "************************************" $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +fi +echo "====================================" >> $dbcopylog +# + +# security question +if [ $enablebatch == no ]; +then + echo "Start the Database-Copy from "$sourcesid" to "$targetsid" ?" + echo "WARNING: "$targetsid"-DB will be overwritten!" + echo "====================================" + read -r -p "Are you sure? [y/N] " response + case $response in + [yY][eE][sS]|[yY]) + # message + echo "Start the Database-Copy!" + echo "====================================" + # log + echo "Start the Database-Copy! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "====================================" >> $dbcopylog + ;; + *) + # message + echo "Stopping now & Cleanup! (RC=0)" + # log + echo "Stopping now & Cleanup! (RC=0) " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # cleanup + sshtarget 'rm /tmp/dbcopy_dbsizetarget_'$targetsid'' + sshsource 'rm /tmp/dbcopy_dbsizesource_'$sourcesid'' + exit 0 + ;; + esac +elif [ $enablebatch == yes ]; +then + # message + echo "Batchmode is active" + echo "====================================" + # log + echo "Batchmode is active " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "====================================" >> $dbcopylog +fi + +# START ################################################################################################# + +# time and date +echo "START DB COPY: " $(date "+%d.%m.%Y %H:%M:%S") & export starttime=$(date +%s) +echo "START DB COPY: " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +echo "====================================" +echo "====================================" >> $dbcopylog + +# cleanup files no longer used +sshtarget 'rm /tmp/dbcopy_dbsizetarget_'$targetsid'' +sshsource 'rm /tmp/dbcopy_dbsizesource_'$sourcesid'' + +if [ $savesecdir == yes ]; +then + # message + echo "Save SEC dir" + # logfile + echo "Save SEC dir "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # save secdir + if [ $abaporjava == abap ]; + then + sshtarget 'cd /usr/sap/$SAPSYSTEMNAME/D[0-9][0-9]; cp -rp sec syscopy_sec' >> $dbcopylog + export savesecdirpath=$(sshtarget 'cd /usr/sap/$SAPSYSTEMNAME/D[0-9][0-9]; cd syscopy_sec; pwd') + echo "SEC dir of "$targetsid" was saved to "$savesecdirpath" on "$targethost $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + elif [ $abaporjava == java ]; + then + sshtarget 'cd /usr/sap/$SAPSYSTEMNAME/J[0-9][0-9]; cp -rp sec syscopy_sec' >> $dbcopylog + export savesecdirpath=$(sshtarget 'cd /usr/sap/$SAPSYSTEMNAME/J[0-9][0-9]; cd syscopy_sec; pwd') + echo "SEC dir of "$targetsid" was saved to "$savesecdirpath" on "$targethost $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + else + export savesecdirpath='Cannot save secdir' + echo $savesecdirpath $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # message + echo "Please define if ABAP or JAVA, cannot save secdir" + # log + echo "Please define if ABAP or JAVA, cannot save secdir "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + fi + # message + echo "SEC dir saved" + # logfile + echo "SEC dir saved "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # function sleepandspace + sleepandspace +fi + +if ( [ $e07lexport == yes ] || [ $licexport == yes ] || [ $rz10export == yes ] || [ $rz04export == yes ] || [ $strustexport == yes ] || [ $strustsso2export == yes ] || [ $stmsqaexport == yes ] || [ $stmsexport == yes ] || [ $al11export == yes ] || [ $bd54export == yes ] || [ $fileexport == yes ] || [ $rz70sldexport == yes ] || [ $scotexport == yes ] || [ $sicfexport == yes ] || [ $rfcconnectionsexport == yes ] || [ $we202197export == yes ] || [ $sm69export == yes ] || [ $smlgrz12export == yes ] || [ $abapdevexport == yes ] || [ $gtssllexport == yes ] || [ $oac0export == yes ] || [ $scc4export == yes ] || [ $reportvariants == yes ] || [ $dbacockpit == yes ] || [ $httpurlloc == yes ] || [ $ldap == yes ] || [ $vscan == yes ] || [ $spad == yes ] || [ $ewz5 == yes ] || [ $sbgrfcconf == yes ] || [ $sbwp == yes ] || [ $secpol == yes ] || [ $secstore == yes ] || [ $sm19 == yes ] || [ $customtables == yes ] ) && ( [ $donotexport -eq 0 ] ); +then + # message + echo "Create Export Template File" + # logfile + echo "Create Export Template File " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # create export file header + echo "export" > /tmp/dbcopy_tmp_exporttables.tpl + echo "client = "$expimpclient >> /tmp/dbcopy_tmp_exporttables.tpl + echo "file = '"$exportlocation"/"$targetsid"_dbcopy_exporttables.dat'" >> /tmp/dbcopy_tmp_exporttables.tpl + # create a unsort list of tables to export + if [ $e07lexport == yes ]; + then + for table in "${tables_e07lexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $licexport == yes ]; + then + for table in "${tables_licexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $rz10export == yes ]; + then + for table in "${tables_rz10export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $rz04export == yes ]; + then + for table in "${tables_rz04export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $strustexport == yes ]; + then + for table in "${tables_strustexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $strustsso2export == yes ]; + then + for table in "${tables_strustsso2export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $stmsqaexport == yes ]; + then + for table in "${tables_stmsqaexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $stmsexport == yes ]; + then + for table in "${tables_stmsexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $al11export == yes ]; + then + for table in "${tables_al11export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $bd54export == yes ]; + then + for table in "${tables_bd54export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $fileexport == yes ]; + then + for table in "${tables_fileexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $rz70sldexport == yes ]; + then + for table in "${tables_rz70sldexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $scotexport == yes ]; + then + for table in "${tables_scotexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $sicfexport == yes ]; + then + for table in "${tables_sicfexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $rfcconnectionsexport == yes ]; + then + for table in "${tables_rfcconnectionsexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $we202197export == yes ]; + then + for table in "${tables_we202197export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $sm69export == yes ]; + then + for table in "${tables_sm69export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $smlgrz12export == yes ]; + then + for table in "${tables_smlgrz12export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $abapdevexport == yes ]; + then + for table in "${tables_abapdevexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $gtssllexport == yes ]; + then + for table in "${tables_gtssllexport[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $oac0export == yes ]; + then + for table in "${tables_oac0export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $scc4export == yes ]; + then + for table in "${tables_scc4export[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $reportvariants == yes ]; + then + for table in "${tables_reportvariants[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $dbacockpit == yes ]; + then + for table in "${tables_dbacockpit[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $httpurlloc == yes ]; + then + for table in "${tables_httpurlloc[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $ldap == yes ]; + then + for table in "${tables_ldap[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $vscan == yes ]; + then + for table in "${tables_vscan[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $spad == yes ]; + then + for table in "${tables_spad[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $ewz5 == yes ]; + then + for table in "${tables_ewz5[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $sbgrfcconf == yes ]; + then + for table in "${tables_sbgrfcconf[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $sbwp == yes ]; + then + for table in "${tables_sbwp[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $secpol == yes ]; + then + for table in "${tables_secpol[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $secstore == yes ]; + then + for table in "${tables_secstore[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $sm19 == yes ]; + then + for table in "${tables_sm19[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + + if [ $customtables == yes ]; + then + for table in "${tables_customtables[@]}" + do + echo $table >> /tmp/dbcopy_tmp_exporttables_unsort.tpl + done + fi + sleep 1 + + # sort list of tables to export and only use unique + sort -u /tmp/dbcopy_tmp_exporttables_unsort.tpl > /tmp/dbcopy_tmp_exporttables_sort.tpl + sleep 1 + # create final file for export + while read tmp_exporttables + do + echo "delete from "$tmp_exporttables >> /tmp/dbcopy_tmp_exporttables.tpl + echo "select * from "$tmp_exporttables >> /tmp/dbcopy_tmp_exporttables.tpl + done < /tmp/dbcopy_tmp_exporttables_sort.tpl + # cleanup files + rm /tmp/dbcopy_tmp_exporttables_unsort.tpl + rm /tmp/dbcopy_tmp_exporttables_sort.tpl + sleep 1 + # message + echo "Export Template File created" + # logfile + echo "Export Template File created" $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + export noexport=0 + + # function sleepandspace + sleepandspace +else + export noexport=1 +fi + +if [ $noexport -ne 1 ]; +then + # message + echo "Export Tables from "$targetsid + # logfile + echo "Export Tables from "$targetsid $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # export + scp /tmp/dbcopy_tmp_exporttables.tpl $targetsidadm@$targethost:$exportlocation/"$targetsid"_dbcopy_exporttables.tpl >> $dbcopylog + sshtarget 'R3trans -w '$exportlocation'/'$targetsid'_dbcopy_exporttables.log '$exportlocation'/'$targetsid'_dbcopy_exporttables.tpl' >> $dbcopylog + export expcode=$(sshtarget "cat '$exportlocation'/'$targetsid'_dbcopy_exporttables.log | tail -n 2 | head -n 1 | awk -F\( '{ print $2 }' | awk -F\) '{ print $1 }'" | awk -F\( '{ print $2 }' | awk -F\) '{ print $1 }') + # message + echo "Tables from "$targetsid" exported with RC="$expcode + if [ "$expcode" == '0000' ]; + then + rm /tmp/dbcopy_tmp_exporttables.tpl + fi + # logfile + echo "Tables from "$targetsid" exported " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "Returncode of Export: " $expcode $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + + # function sleepandspace + sleepandspace +fi + +# message +echo "Create PIPE "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_1 and "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_2 in /tmp" +# logfile +echo "Create PIPE "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_1 and "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_2 in /tmp "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# create pipes (MaxDB default - 2 pipes) +# target +sshtarget 'mkfifo /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1; chmod 777 /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1' &>> $dbcopylog +sshtarget 'mkfifo /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2; chmod 777 /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2' &>> $dbcopylog +# source +sshsource 'mkfifo /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_1; chmod 777 /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_1' &>> $dbcopylog +sshsource 'mkfifo /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_2; chmod 777 /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_2' &>> $dbcopylog +# message +echo "PIPE "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_1 and "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_2 are created in /tmp" +# logfile +echo "PIPE "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_1 and "$sourcesid"to"$targetsid"_pipe_(s/t)_"$pipedate"_2 are created in /tmp "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# backup template +if [ $backupcompressed == yes ]; + then + export backuptemplatesource=''$sourcesid'to'$targetsid' TO PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_1 COMPRESSED PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_2 COMPRESSED CONTENT COMPLETE DATA BLOCKSIZE '$pipesize'' + export backuptemplatetarget=''$sourcesid'to'$targetsid' TO PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1 COMPRESSED PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2 COMPRESSED CONTENT COMPLETE DATA BLOCKSIZE '$pipesize'' + else + export backuptemplatesource=''$sourcesid'to'$targetsid' TO PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_1 PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_2 CONTENT COMPLETE DATA BLOCKSIZE '$pipesize'' + export backuptemplatetarget=''$sourcesid'to'$targetsid' TO PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1 PIPE /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2 CONTENT COMPLETE DATA BLOCKSIZE '$pipesize'' +fi + +# message +echo "Create source backup media" +# logfile +echo "Create source backup media "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# create backup media in source +sshsource 'dbmcli -d '$sourcesid' '"$dbmcliconnetsource"' backup_template_create '"$backuptemplatesource"'' >> $dbcopylog +# exit status +if [ $? -ne 0 ]; + then + # message + echo "Error create source backup media --> EXIT (RC=82)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Error create source backup media --> EXIT (RC=82) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 82; +fi +# message +echo "Source backup media created" +# logfile +echo "Source backup media created "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# message +echo "Create target backup media" +# logfile +echo "Create target backup media "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# create restore media in target +sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' backup_template_create '"$backuptemplatetarget"'' >> $dbcopylog +# exit status +if [ $? -ne 0 ]; + then + # message + echo "Error create target backup media --> EXIT (RC=83)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Error create target backup media --> EXIT (RC=83) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 83; +fi +# message +echo "Target backup media created" +# logfile +echo "Target backup media created "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# message +echo "Stop target SAP system" +# logfile +echo "Stop target SAP system "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# stop target system +sshtarget 'stopsap r3' >> $dbcopylog +# check the stopsap command if batchmode is not enabled +if [ $? -ne 0 ]; + then + # message + if [ $enablebatch == no ]; + then + echo "Error with stopsap command." | tee -a $dbcopylog + read -rsp $'Check the error, stop the target system and press ENTER to continue (cancel with CTRL+C)...\n' + fi +fi + +# message +echo "Target SAP system stopped" +# logfile +echo "Target SAP system stopped "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# disable Signal 2 (CTRL+C) +if [ $disablectrlc == yes ]; + then + trap '' 2 + echo "### CTRL+C disabled ###" | tee -a $dbcopylog + echo "=====" | tee -a $dbcopylog +fi + +# message +echo "Start backup on source" +# logfile +echo "Start backup on source "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# start backup on source +sshsource 'echo "db_connect" > /tmp/dbcopy_tmpbacklist' +sshsource 'echo "backup_start "'$sourcesid'"to"'$targetsid' >> /tmp/dbcopy_tmpbacklist' +sshsource 'dbmcli -d '$sourcesid' '"$dbmcliconnetsource"' -i /tmp/dbcopy_tmpbacklist -o /tmp/dbcopy_backuplog && touch /tmp/dbcopy_backupend' >> $dbcopylog & +# exit status +if [ $? -ne 0 ]; + then + # message + echo "Error Backup start --> EXIT (RC=95)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Error Backup start --> EXIT (RC=95) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 95; +fi +# status of backup +backupstartstatus=0 +while [ $backupstartstatus -ne 1 ]; +do + export backupstartstatus=$(sshsource 'ls -l /tmp/ | grep dbcopy_backuplog | wc -l') + sleep 5 +done +# check +sleep 3 +export backupstart=$(sshsource "cat /tmp/dbcopy_backuplog | head -n 2 | tail -n 1") +if [ "$backupstart" == 'OK' ]; +then + # message + sleep 3 + echo "Backup started on source" + # logfile + echo "Backup started on source "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +else + # message + sleep 3 + echo "Error Backup start --> EXIT (RC=95)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Error Backup start --> EXIT (RC=95) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 95; +fi + +# function sleepandspace +sleepandspace + +# message +echo "Start restore on target" +# logfile +echo "Start restore on target "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# start restore on target +sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' db_admin' >> $dbcopylog +sshtarget 'echo "db_connect" > /tmp/dbcopy_tmprestlist' +sshtarget 'echo "db_activate RECOVER "'$sourcesid'"to"'$targetsid'" DATA AUTOIGNORE" >> /tmp/dbcopy_tmprestlist' +sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' -i /tmp/dbcopy_tmprestlist -o /tmp/dbcopy_restorelog && touch /tmp/dbcopy_restoreend' >> $dbcopylog & +# exit status +if [ $? -ne 0 ]; + then + # message + echo "Error Restore start --> EXIT (RC=94)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Error Restore start --> EXIT (RC=94) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 94; +fi +# status of recover +export recoverstartstatus=0 +while [ $recoverstartstatus -ne 1 ]; +do + export recoverstartstatus=$(sshtarget 'ls -l /tmp/ | grep dbcopy_restorelog | wc -l') + sleep 5 +done +# check +sleep 3 +export backupstart=$(sshtarget "cat /tmp/dbcopy_restorelog | head -n 2 | tail -n 1") +if [ "$backupstart" == 'OK' ]; +then + # message + sleep 3 + echo "Restore started on target" + # logfile + echo "Restore started on target "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +else + # message + sleep 3 + echo "Error Restore start --> EXIT (RC=94)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Error Restore start --> EXIT (RC=94) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 94; +fi + +# function sleepandspace +sleepandspace + +# message +echo "Data transfer started with 2 dd streams" +# logfile +echo "Data transfer started with 2 dd streams "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# check if local or remote copy and start data transfer +if [ $sourcehost == $targethost ]; + then + echo "Local System Copy" + echo "Local System Copy "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + sshsource 'dd if=/tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_1 of=/tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1 bs='$blocksize' && touch /tmp/dbcopy_pipecopyend_1' &>> $dbcopylog & + sshsource 'dd if=/tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_2 of=/tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2 bs='$blocksize' && touch /tmp/dbcopy_pipecopyend_2' &>> $dbcopylog & + else + echo "Remote System Copy" + echo "Remote System Copy "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + sshsource 'dd if=/tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_1 bs='$blocksize' | ssh -oForwardX11=no -c '$sshcipher' '$targetsidadm'@'$targethost' dd of=/tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1 bs='$blocksize' && touch /tmp/dbcopy_pipecopyend_1' &>> $dbcopylog & + sshsource 'dd if=/tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_2 bs='$blocksize' | ssh -oForwardX11=no -c '$sshcipher' '$targetsidadm'@'$targethost' dd of=/tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2 bs='$blocksize' && touch /tmp/dbcopy_pipecopyend_2' &>> $dbcopylog & +fi +# status of copy +export copystate=0 +export transferstarted=0 +export tempcounter=0 +while [ $copystate -ne 2 ]; +do + # create a tempchar for status bar + if [ $tempcounter -eq 0 ]; + then + export tempchar="(|)" + export tempcounter=$(($tempcounter + 1)) + elif [ $tempcounter -eq 1 ]; + then + export tempchar="(/)" + export tempcounter=$(($tempcounter + 1)) + elif [ $tempcounter -eq 2 ]; + then + export tempchar="(-)" + export tempcounter=$(($tempcounter + 1)) + elif [ $tempcounter -eq 3 ]; + then + export tempchar="(\\)" + export tempcounter=0 + fi + # check recover state + sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' recover_state' > /tmp/dbcopy_tmp_recover_state + # restore overall pages + export restoreprograssall=$(cat /tmp/dbcopy_tmp_recover_state | grep Count | grep -v Converter | awk '{ print $3 }') + if ( [ -z "$restoreprograssall" ] || [ "$restoreprograssall" == "0" ] ); + then restoreprograssall=1 + fi + # restore left pages + export restoreprogressleft=$(cat /tmp/dbcopy_tmp_recover_state | grep Left | awk '{ print $3 }') + # restore transfered pages + export restoreprogresstransfered=$(cat /tmp/dbcopy_tmp_recover_state | grep Transferred | awk '{ print $3 }') + # copystate + export copystate=$(sshsource 'ls -l /tmp/ | grep dbcopy_pipecopyend_ | wc -l') + if [ $copystate -ne 2 ]; + then + export restorepercent=$(echo "$restoreprogresstransfered/($restoreprograssall/100)" | bc -l | grep -v divide | awk -F. '{ print $1 }') + # check if transfer started or clear log still running + if [ 1$restoreprogressleft -gt 10 ]; + then + # take ddtime when transfer is really started + if [ $transferstarted -eq 0 ]; + then + echo "Data transfer startet (after clear log) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + export ddtimestart=$(echo "$(date +%s)+8" | bc -l) + export transferstarted=1 + fi + export allmb=$(echo "scale=2;(0$restoreprograssall*8)/1024" | bc -l) + export leftmb=$(echo "scale=2;(0$restoreprogressleft*8)/1024" | bc -l) + export transmb=$(echo "scale=2;(0$restoreprogresstransfered*8)/1024" | bc -l) + export ddduration=$(echo "$(date +%s)-$ddtimestart" | bc -l) + # check to prevent from divide by 0 + if [ $ddduration -le 0 ]; + then + export ddduration=8 + fi + export speed=$(echo "scale=2;$transmb/$ddduration" | bc -l) + echo -ne "\r\e[KPage Count:" $restoreprograssall "("$allmb"MB) Transferred:" $restoreprogresstransfered "("$transmb"MB) Left:" $restoreprogressleft "("$leftmb"MB) Progress:" $restorepercent"% Speed: "$speed"MB/s "$tempchar" \r\c" + # write info to logfile (only every two minutes) + if [ $(date "+%S") -ge 53 ] && [ $((10$(date "+%M")%2)) -eq 0 ]; + then + echo "Page Count:" $restoreprograssall "("$allmb"MB) Transferred:" $restoreprogresstransfered "("$transmb"MB) Left:" $restoreprogressleft "("$leftmb"MB) Progress:" $restorepercent"% Speed: "$speed"MB/s " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + fi + else + echo -ne "\r\e[KWork in progress (that may take some time)... "$tempchar" \r\c" + fi + else + echo -ne "\r\e[KData transfer end... \r\c" + fi +sleep 5 +done +sleep 2 +sshsource 'rm /tmp/dbcopy_pipecopyend_*' +sshsource 'rm /tmp/dbcopy_tmp_recover_state' +# message +echo "Data transfer complete" +# logfile +echo "Data transfer complete "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# status of backup +export backupstate=0 +while [ $backupstate -ne 1 ]; +do + export backupstate=$(sshsource 'ls -l /tmp/ | grep dbcopy_backupend | wc -l') + sleep 5 +done +sleep 2 +sshsource 'rm /tmp/dbcopy_backupend' +# backupcheck +export dbcopy_backupendstate=$(sshsource 'grep "Returncode" /tmp/dbcopy_backuplog' | awk '{ print $2 }') +if [ "$dbcopy_backupendstate" == '0' ]; +then + # message + echo "Backup complete" + # logfile + echo "Backup complete "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +else + # message + echo "Backup Error --> EXIT (RC=93)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Backup Error --> EXIT (RC=93) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 93; +fi + +# function sleepandspace +sleepandspace + +# status of restore +export restorestate=0 +while [ $restorestate -ne 1 ]; +do + export restorestate=$(sshtarget 'ls -l /tmp/ | grep dbcopy_restoreend | wc -l') + sleep 5 +done +sleep 2 +sshtarget 'rm /tmp/dbcopy_restoreend' +# restorecheck +export dbcopy_restoreendstate=$(sshtarget 'grep "Returncode" /tmp/dbcopy_restorelog' | awk '{ print $2 }') +if [ "$dbcopy_restoreendstate" == '0' ]; +then + # message + echo "Restore complete" + # logfile + echo "Restore complete "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +else + # message + echo "Restore Error --> EXIT (RC=92)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Restore Error --> EXIT (RC=92) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 92; +fi + +# function sleepandspace +sleepandspace + +# message +echo "Delete Backup and Restore logs" +# logfile +echo "Delete Backup and Restore logs "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# delete backup and restore logs +sshtarget 'rm /tmp/dbcopy_restorelog' +sshsource 'rm /tmp/dbcopy_backuplog' +# message +echo "Backup and Restore logs deleted" +# logfile +echo "Backup and Restore logs deleted "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +if [ $secondclearlog == yes ]; +then + # message + echo "Clear Log" + # logfile + echo "Clear Log "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # clear log + sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' db_offline' >> $dbcopylog + sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' db_admin' >> $dbcopylog + sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' util_execute clear log' >> $dbcopylog + # message + echo "Log cleared" + # logfile + echo "Log cleared "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # function sleepandspace + sleepandspace +fi + +# enable Signal 2 (CTRL+C) +if [ $disablectrlc == yes ]; + then + trap 2 + echo "### CTRL+C enabled ###" | tee -a $dbcopylog + echo "=====" | tee -a $dbcopylog +fi + +# message +echo "Start target DB" +# logfile +echo "Start target DB "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# start target db +if [ $usexuser == no ] && [ "$sysdbapwdsource" != "$sysdbapwdtarget" ]; + then + echo "Different passwords between source and target "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + sshtarget 'echo "user_sysdba "'$dbsourceuser'","'$sysdbapwdsource' > /tmp/dbcopy_dbonline; chmod 600 /tmp/dbcopy_dbonline' + sshtarget 'echo "db_online" >> /tmp/dbcopy_dbonline' + sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' -i /tmp/dbcopy_dbonline' >> $dbcopylog + export dbstartstatus=$? + sshtarget 'dbmcli -d '$targetsid' -u '$dbtargetuser','$sysdbapwdsource' user_put '$dbtargetuser' password='$sysdbapwdtarget'' >> $dbcopylog + sshtarget 'rm /tmp/dbcopy_dbonline' + # read passwords + echo "Need actual password of SAP"$sourcesid "User of the "$targetsid" Database:" + # switch off echo + stty -echo + read targetsqluserpassword + # switch on echo + stty echo + sshtarget 'echo "ALTER PASSWORD SAP"'$sourcesid' '$targetsqluserpassword' > /tmp/dbcopy_changesqlpass; chmod 600 /tmp/dbcopy_changesqlpass' + sshtarget 'sqlcli -d '$targetsid' -u '$dbtargetuser','"$sysdbapwdtarget"' -f -i /tmp/dbcopy_changesqlpass' &>> $dbcopylog + sshtarget 'rm /tmp/dbcopy_changesqlpass' +else + sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' db_online' >> $dbcopylog + export dbstartstatus=$? +fi +# exit status +if [ $dbstartstatus -ne 0 ]; + then + # message + echo "Error in Target DB start (RC=84)" + # logfile + echo "Error in Target DB start (RC=84) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # exit + sendmailbatch + exit 84; +fi +sleep 1 +# check for error +export dbstartfail=$(sshsource 'grep "Database state: OFFLINE" '$workdirectory'/'$dbcopylog' | wc -l') >> $dbcopylog +if [ $dbstartfail -ne 0 ]; + then + # message + echo "Error in Target DB start (RC=84)" + # logfile + echo "Error in Target DB start (RC=84) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # exit + sendmailbatch + exit 84; +fi +# message +echo "Target DB started" +# logfile +echo "Target DB started "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# message +echo "Rename target DB" +# logfile +echo "Rename target DB "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# rename target db +sshtarget 'echo "sql_execute rename user SAP"'$sourcesid'" to SAP"'$targetsid' > /tmp/dbcopy_renamedbsid; chmod 600 /tmp/dbcopy_renamedbsid' +sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' '"$dbmcliconnettargetsql"' -i /tmp/dbcopy_renamedbsid' >> $dbcopylog +export dbrenamestatus=$? +sshtarget 'rm /tmp/dbcopy_renamedbsid' +# exit status +if [ $dbrenamestatus -ne 0 ]; + then + # message + echo "Error rename target DB --> EXIT (RC=81)" + echo "You must fix the problem and clean up the /tmp directory before you start again!" + # logfile + echo "Error rename target DB --> EXIT (RC=81) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "You must fix the problem and clean up the /tmp directory before you start again! "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + # remove lockfile + rm -f $copylockfile + # send mail bath + sendmailbatch + exit 81; +fi +sleep 3 +# message +echo "Target DB renamed" +# logfile +echo "Target DB renamed "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# message +echo "Truncate tables in target DB" +# logfile +echo "Truncate tables in target DB (messages with \"Unknown table name\" can be ignored) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# truncate tables in target db +for sql_deltable in "${sql_deltables[@]}" +do + echo "truncate table "$sql_deltable >> /tmp/dbcopy_deltables.sql + echo "//" >> /tmp/dbcopy_deltables.sql +done +scp /tmp/dbcopy_deltables.sql $targetsidadm@$targethost:/tmp/dbcopy_deltables.sql >> $dbcopylog +sshtarget 'sqlcli -U DEFAULT -f -i /tmp/dbcopy_deltables.sql' &>> $dbcopylog +sleep 3 +sshsource 'rm /tmp/dbcopy_deltables.sql' +sshtarget 'rm /tmp/dbcopy_deltables.sql' +# message +echo "Tables in target DB truncated" +# logfile +echo "Tables in target DB truncated "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# message +echo "Delete source backup media" +# log +echo "Delete source backup media "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# delete backup media in source +sshsource 'dbmcli -d '$sourcesid' '"$dbmcliconnetsource"' backup_template_delete "'$sourcesid'"to"'$targetsid'" ' >> $dbcopylog +# exit status +if [ $? -ne 0 ]; + then + # message + echo "Error delete source backup media --> INFO" + # logfile + echo "Error delete source backup media --> INFO "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +fi +sleep 3 +sshsource 'rm /tmp/dbcopy_tmpbacklist' +# message +echo "Source backup media deleted" +# logfile +echo "Source backup media deleted "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# message +echo "Delete target backup media" +# log +echo "Delete target backup media "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# delete restore media in target +sshtarget 'dbmcli -d '$targetsid' '"$dbmcliconnettarget"' backup_template_delete "'$sourcesid'"to"'$targetsid'" ' >> $dbcopylog +# exit status +if [ $? -ne 0 ]; + then + # message + echo "Error delete source backup media --> INFO" + # logfile + echo "Error delete source backup media --> INFO "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +fi +sleep 3 +sshtarget 'rm /tmp/dbcopy_tmprestlist' +# message +echo "Target backup media deleted" +# logfile +echo "Target backup media deleted "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + +# message +echo "Delete PIPE" +# log +echo "Delete PIPE "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +# delete pipes +sshtarget 'rm /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_1' +sshtarget 'rm /tmp/'$sourcesid'to'$targetsid'_pipe_t_'$pipedate'_2' +sshsource 'rm /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_1' +sshsource 'rm /tmp/'$sourcesid'to'$targetsid'_pipe_s_'$pipedate'_2' +# message +echo "PIPE deleted" +# logfile +echo "PIPE deleted "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# function sleepandspace +sleepandspace + + +if [ $noexport -ne 1 ]; +then + if [ $autoimport == yes ]; + then + # Import Tables + # message + echo "Import Tables for "$targetsid + # logfile + echo "Import Tables for "$targetsid $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + if [ "$expcode" == '0000' ]; + then + # import tables + sshtarget 'cd '$exportlocation'; R3trans -w '$exportlocation'/'$targetsid'_dbcopy_exporttables_imp.log -i '$exportlocation'/'$targetsid'_dbcopy_exporttables.dat' >> $dbcopylog + sleep 3 + sshtarget 'rm '$exportlocation'/'$targetsid'_dbcopy_exporttables.tpl; rm '$exportlocation'/'$targetsid'_dbcopy_exporttables_imp.log; rm '$exportlocation'/'$targetsid'_dbcopy_exporttables.log' >> $dbcopylog + if [ $remexpafterimp == yes ]; + then + sshtarget 'rm '$exportlocation'/'$targetsid'_dbcopy_exporttables.dat' >> $dbcopylog + else + sshtarget 'mv '$exportlocation'/'$targetsid'_dbcopy_exporttables.dat '$exportlocation'/'$targetsid'_dbcopy_exporttables.dat.save' >> $dbcopylog + fi + # message + echo "Tables for "$targetsid" imported" + # logfile + echo "Tables for "$targetsid" imported " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + else + # message + echo "No clean Table export for "$targetsid" found" + echo "Check Files "$exportlocation"/"$targetsid"_dbcopy_exporttables.tpl, "$exportlocation"/"$targetsid"_dbcopy_exporttables.dat and "$exportlocation"/"$targetsid"_dbcopy_exporttables.log on" $targethost + # logfile + echo "No clean Table export for "$targetsid" found " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "Check Files "$exportlocation"/"$targetsid"_dbcopy_exporttables.tpl, "$exportlocation"/"$targetsid"_dbcopy_exporttables.dat and "$exportlocation"/"$targetsid"_dbcopy_exporttables.log on" $targethost >> $dbcopylog + fi + # function sleepandspace + sleepandspace + elif [ $autoimport == no ]; + then + # message + echo "Auto Import disabled for "$targetsid + echo "To import the export use this command: R3trans -w "$exportlocation"/"$targetsid"_dbcopy_exporttables_imp.log -i "$exportlocation"/"$targetsid"_dbcopy_exporttables.dat on "$targethost" !" + # logfile + echo "Auto Import disabled for "$targetsid $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + echo "To import the export use this command: R3trans -w "$exportlocation"/"$targetsid"_dbcopy_exporttables_imp.log -i "$exportlocation"/"$targetsid"_dbcopy_exporttables.dat on "$targethost" !" >> $dbcopylog + # function sleepandspace + sleepandspace + fi +fi + +# information for sapstart +echo "INFO: Please set rdisp/wp_no_btc = 0 and rdisp/wp_no_spo = 0 before start of the SAP system "$targetsid"!" +if [ $savesecdir == yes ]; +then + echo "INFO: SEC dir of "$targetsid" was saved to "$savesecdirpath" on "$targethost + echo "INFO: SEC dir of "$targetsid" was saved to "$savesecdirpath" on "$targethost $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +fi + +# function sleepandspace +sleepandspace + +# END ################################################################################################### +# message +echo "Database-Copy created (RC=0)" +# logfile +echo "Database-Copy created (RC=0) "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog + +# time and date +echo "====================================" | tee -a $dbcopylog +echo "END DB COPY: " $(date "+%d.%m.%Y %H:%M:%S") & export endtime=$(date +%s) +echo "END DB COPY: " $(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +echo "====================================" | tee -a $dbcopylog +export durationtime=$(($endtime - $starttime)) +echo "Duration: $(($durationtime /3600)) h $(($durationtime % 3600 /60)) min $(($durationtime % 60)) sec" +echo "Duration: $(($durationtime /3600)) h $(($durationtime % 3600 /60)) min $(($durationtime % 60)) sec "$(date "+%d.%m.%Y %H:%M:%S") >> $dbcopylog +echo "====================================" | tee -a $dbcopylog + +# send mail +sendmailnormal + +# remove lockfile +rm -f $copylockfile +sleep 2 +exit 0 From 89eed2737eacb1ffbbbdf34e7b010a7b75a63e1a Mon Sep 17 00:00:00 2001 From: bartik Date: Thu, 17 Nov 2022 15:48:12 +0100 Subject: [PATCH 16/19] Create J2EEGetComponentList2.conf --- J2EEGetComponentList2/J2EEGetComponentList2.conf | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 J2EEGetComponentList2/J2EEGetComponentList2.conf diff --git a/J2EEGetComponentList2/J2EEGetComponentList2.conf b/J2EEGetComponentList2/J2EEGetComponentList2.conf new file mode 100644 index 0000000..1d5b749 --- /dev/null +++ b/J2EEGetComponentList2/J2EEGetComponentList2.conf @@ -0,0 +1,9 @@ +Name:J2EEGetComponentList2 + +Command: /usr/sap/hostctrl/exe/operations.d/custom_operations/J2EEGetComponentList2.sh $[SAPSYSTEM:#required] +ResultConverter: flat +Platform: Unix + +Command: "C:\Program Files\SAP\hostctrl\exe\operations.d\custom_operations\J2EEGetComponentList2.bat" $[SAPSYSTEM:#required] +ResultConverter: flat +Platform: Windows From a1ad482ad7762649c4d68eb6e83f37441e678a62 Mon Sep 17 00:00:00 2001 From: bartik Date: Thu, 17 Nov 2022 15:49:27 +0100 Subject: [PATCH 17/19] Create J2EEGetComponentList2.bat --- J2EEGetComponentList2/J2EEGetComponentList2.bat | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 J2EEGetComponentList2/J2EEGetComponentList2.bat diff --git a/J2EEGetComponentList2/J2EEGetComponentList2.bat b/J2EEGetComponentList2/J2EEGetComponentList2.bat new file mode 100644 index 0000000..421c42a --- /dev/null +++ b/J2EEGetComponentList2/J2EEGetComponentList2.bat @@ -0,0 +1,16 @@ +@ECHO OFF +SET "_filename=%TEMP%\%~n0" +SET "_sapsystem=%~1" +REG QUERY HKLM\Software\SAP /s /v SAPEXE | FINDSTR /C:SAPEXE >"%_filename%.tmp" +FOR /F "tokens=3,6 delims=\\ " %%G IN (%_filename%.tmp) DO ( + CALL :func_checkBatchConfig %%G %%H +) +DEL /Q "%_filename%.tmp" +GOTO :eof + +:func_checkBatchConfig +SET "_batchconfig=%1\usr\sap\%2\J%_sapsystem%\j2ee\configtool\batchconfig.bat" +IF EXIST "%_batchconfig%" ( + CALL "%_batchconfig%" -task get.versions.of.deployed.units +) +EXIT /B From d5bfe077a0511eb0d082b428f4ebdde5cc038b88 Mon Sep 17 00:00:00 2001 From: bartik Date: Thu, 17 Nov 2022 15:50:22 +0100 Subject: [PATCH 18/19] Create J2EEGetComponentList2.sh --- J2EEGetComponentList2/J2EEGetComponentList2.sh | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 J2EEGetComponentList2/J2EEGetComponentList2.sh diff --git a/J2EEGetComponentList2/J2EEGetComponentList2.sh b/J2EEGetComponentList2/J2EEGetComponentList2.sh new file mode 100644 index 0000000..ff3e2e0 --- /dev/null +++ b/J2EEGetComponentList2/J2EEGetComponentList2.sh @@ -0,0 +1,2 @@ +#!/bin/bash +find /usr/sap/[A-Z][A-Z0-9][A-Z0-9]/J${1}/j2ee/configtool/ -regex ".*/batchconfig\.[c]*sh$" -type f -exec '{}' -task get.versions.of.deployed.units \; From b21ee297a2ea48861094a50f22626c41e47fc2c7 Mon Sep 17 00:00:00 2001 From: bartik Date: Thu, 17 Nov 2022 15:54:33 +0100 Subject: [PATCH 19/19] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index c8e7245..acfc46f 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,13 @@ Scripts for monitoring using Nagios modified to fit for reasons like: - You won't be allowed to install random ... in serious places just to get the fancies running. * check_sybase_ase.sh + https://www.bersler.com/blog/nagios-script-for-checking-sap-adaptive-server-enterprise-sybase-ase/ * check_oracle + https://www.monitoring-plugins.org/doc/man/check_oracle.html + +* j2eegetcomponentlist2 - this time with versions too + +/usr/sap/hostctrl/exe/saphostctrl -host saphostwithjavainstance -user sapadm password -function ExecuteOperation -name J2EEGetComponentList2 SAPSYSTEM=66