Friday, August 19, 2022

DBA_BUNDLE6/ 0000755 0152073 0152061 00000000000 14122405733 012447 5 ustar oracle oinstall DBA_BUNDLE6/analyze_tables.sh 0000740 0152073 0152061 00000024010 13703113413 015765 0 ustar oracle oinstall ################################################### # This script gathers object stats using ANALYZE.. # To be run by ORACLE user # # Author: ABD-ELGAWAD OTHMAN # Modified: Mahmmoud ADEL # 29-01-2014 # Script Environment Globalization. # ################################################### SCRIPT_NAME="analyze_tables" ############# # Description: ############# echo echo "=======================================================" echo "This script Gathers object stats using ANALYZE command." echo "=======================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. ############################# # Listing Available Instances: ############################# # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Run this script against:[Enter the number]" echo "-------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME #echo "ORACLE_HOME from PWDX is ${ORACLE_HOME}" # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi ########################################## # Exit if the user is not the Oracle Owner: ########################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi ########################## # Getting ORACLE_BASE: ########################## # Get ORACLE_BASE from user's profile if not set: if [ -z "${ORACLE_BASE}" ] then ORACLE_BASE=`grep 'ORACLE_BASE=\/' $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi ########################### # SQLPLUS Section: ########################### # PROMPT FOR VARIABLES: ###################### echo echo "Please Enter the location where you want keep staging script: [Default is: ${USR_ORA_HOME}]" echo "============================================================" read LOC1 if [ -z ${LOC1} ]; then LOC1=${USR_ORA_HOME} echo "Location has been set to: [${LOC1}]" fi if [ ! -d ${LOC1} ]; then echo "The location you entered is NOT EXIST." echo "Location has been set to: ${USR_ORA_HOME}" echo "" LOC1=${USR_ORA_HOME} fi cd ${LOC1} echo echo "Enter the SCHEMA NAME you want to ANALYZE its tables:" echo "====================================================" while read SCHEMA_NAME do if [ -z ${SCHEMA_NAME} ] then echo echo "Enter the SCHEMA NAME:" echo "=====================" else VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('$SCHEMA_NAME'); EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` if [ ${VAL22} -eq 0 ] then echo echo "ERROR: USER [${SCHEMA_NAME}] IS NOT EXIST ON DATABASE [$ORACLE_SID] !" echo; echo "Enter the SCHEMA NAME:" echo "=====================" else break fi fi done # Execution of SQL Statement: ############################ ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/audit_details.sh 0000740 0152073 0152061 00000020327 13775602155 015631 0 ustar oracle oinstall # ################################################# # This script shows AUDIT records for a user. # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 25-04-2013 # # # # # # # ################################################# # ########################### # Listing Available Instances: # ########################### echo echo "==================================================================" echo "This Script Retreives AUDIT data for a user if auditing is enabled." echo "==================================================================" echo sleep 1 # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Run this script Against:[Enter the number]" echo "-------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################### # SQLPLUS Section: # ######################### # PROMPT FOR VARIABLES: # #################### echo echo "Enter The USERNAME you want to retrieve it's Audit Data: [Blank Value means ALL Users]" echo "=======================================================" while read DB_USERNAME do case $DB_USERNAME in # NO VALUE PROVIDED: "") USERNAME_COND=$DB_USERNAME;break ;; *) USERNAME_COND="USERNAME=upper('$DB_USERNAME') and";break ;; esac done echo echo "How [MANY DAYS BACK] you want to retrieve AUDIT data? [Default 1]" echo "=====================================================" echo "OR: Enter A Specific DATE in this FORMAT [DD-MM-YYYY] e.g. 25-01-2011" echo "== =================================================================" while read NUM_DAYS do case $NUM_DAYS in # User PROVIDED a NON NUMERIC value: *[!0-9]*) echo;echo "Retreiving AUDIT data for User [${DB_USERNAME}] on [${NUM_DAYS}] ..." ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < SYSDATE-$NUM_DAYS order by EXTENDED_TIMESTAMP; PROMPT LOGON/LOGOFF Audit data have been ommited from this report. EOF # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/object_size.sh 0000740 0152073 0152061 00000030230 13775602071 015305 0 ustar oracle oinstall # ############################################################################### # This script shows OBJECT SIZE # Ver 2.0 # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-04-16 # # # # # # Modified: 09-05-19 Add the aggregation of total object size [indexes+lobs]. # ############################################################################### # ########### # Description: # ########### echo echo "================================" echo "This script gets OBJECT Size ..." echo "================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # SQLPLUS: Get Object Size: # ######################################## # Variables echo echo "Enter the OWNER of the Object:" echo "=============================" while read OWNER do case ${OWNER} in "")echo echo "Enter the OWNER of the Object:" echo "=============================";; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('$OWNER'); EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "ERROR: USER [${OWNER}] IS NOT EXIST ON DATABASE [$ORACLE_SID] !" echo echo "Enter the OWNER of the Table:" echo "============================";; *) break;; esac esac done echo echo "Enter the OBJECT NAME:" echo "=====================" while read OBJECT_NAME do case ${OBJECT_NAME} in "")echo echo "Enter the OBJECT NAME:" echo "=====================";; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_OBJECTS WHERE OWNER=upper('$OWNER') AND OBJECT_NAME=UPPER('$OBJECT_NAME'); EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "ERROR: OBJECT [${OBJECT_NAME}] IS NOT EXIST under [${OWNER}] SCHEMA !" echo; echo "Searching for tables that match provided string ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 190 set pagesize 1000 set feedback off set trim on set echo off col owner for a35 col OBJECT_TYPE for a30 col OBJECT_NAME for a35 select OWNER,OBJECT_TYPE,OBJECT_NAME FROM DBA_OBJECTS WHERE OBJECT_TYPE<>'SYNONYM' AND OBJECT_NAME like UPPER('%$OBJECT_NAME%'); EOF echo echo "Enter A VALID OBJECT NAME:" echo "=========================";; *) break;; esac esac done SINGLETABLESIZE_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off lines 1000; prompt select /*+RULE*/ ROUND(SUM(BYTES)/1024/1024) FROM DBA_SEGMENTS where owner=upper('${OWNER}') and SEGMENT_NAME=upper('${OBJECT_NAME}'); exit; EOF ) export SINGLETABLESIZE=`echo ${SINGLETABLESIZE_RAW} |perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 100 PROMPT PROMPT OBJECT SIZE: PROMPT ------------- set linesize 190 col SEGMENT_NAME format a30 SELECT /*+RULE*/ SEGMENT_NAME, TABLESPACE_NAME, SEGMENT_TYPE OBJECT_TYPE, ROUND(SUM(BYTES/1024/1024)) OBJECT_SIZE_MB FROM SYS.DBA_SEGMENTS WHERE OWNER = upper('$OWNER') AND SEGMENT_NAME = upper('$OBJECT_NAME') GROUP BY SEGMENT_NAME, TABLESPACE_NAME, SEGMENT_TYPE; PROMPT EOF LOB_COUNT_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_LOBS WHERE OWNER=upper('$OWNER') AND TABLE_NAME=UPPER('$OBJECT_NAME'); EOF ) LOB_COUNT=`echo ${LOB_COUNT_RAW}| awk '{print $NF}'` case ${LOB_COUNT} in 0) ;; *) LOBSIZE_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off lines 1000; prompt SELECT /*+RULE*/ ROUND(SUM(BYTES)/1024/1024) FROM DBA_SEGMENTS WHERE SEGMENT_NAME IN (SELECT SEGMENT_NAME FROM DBA_LOBS WHERE owner=upper('${OWNER}') AND table_name=UPPER('${OBJECT_NAME}')); exit; EOF ) export LOBSIZE=`echo ${LOBSIZE_RAW} |perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 200 pages 1000 feedback off echo off col LOB_NAME format a30 comp SUM of OBJECT_SIZE_MB on report bre on report PROMPT ITS LOBS SIZE: PROMPT -------------- SELECT /*+RULE*/ SEGMENT_NAME LOB_NAME, TABLESPACE_NAME, ROUND(SUM(BYTES/1024/1024)) OBJECT_SIZE_MB FROM SYS.DBA_SEGMENTS WHERE SEGMENT_NAME in (select /*+RULE*/ SEGMENT_NAME from dba_lobs where owner=upper('$OWNER') and table_name=UPPER('$OBJECT_NAME')) GROUP BY SEGMENT_NAME, TABLESPACE_NAME; EOF echo "" ;; esac IDX_COUNT_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_INDEXES WHERE OWNER=upper('$OWNER') AND TABLE_NAME=UPPER('$OBJECT_NAME'); EOF ) IDX_COUNT=`echo ${IDX_COUNT_RAW}| awk '{print $NF}'` case ${IDX_COUNT} in 0) ;; *) INDEXESSIZE_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off lines 1000; prompt SELECT /*+RULE*/ round(SUM(BYTES/1024/1024)) FROM SYS.DBA_SEGMENTS WHERE OWNER = upper('${OWNER}') AND SEGMENT_NAME in (select index_name from dba_indexes where owner=upper('${OWNER}') and table_name=UPPER('${OBJECT_NAME}')); exit; EOF ) export INDEXESSIZE=`echo ${INDEXESSIZE_RAW} |perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 200 pages 1000 feedback off echo off col INDEX_NAME format a30 comp SUM of OBJECT_SIZE_MB on report bre on report PROMPT ITS INDEXES SIZE: PROMPT ----------------- SELECT /*+RULE*/ SEGMENT_NAME INDEX_NAME, TABLESPACE_NAME, ROUND(SUM(BYTES/1024/1024)) OBJECT_SIZE_MB FROM SYS.DBA_SEGMENTS WHERE OWNER = upper('${OWNER}') AND SEGMENT_NAME in (select index_name from dba_indexes where owner=upper('${OWNER}') and table_name=UPPER('${OBJECT_NAME}')) GROUP BY SEGMENT_NAME, TABLESPACE_NAME; EOF ;; esac # Aggregate Full Object Size: [Object + Indexes + Lobs] # If no INDEXES found set INDEXESSIZE to 0 to avoid the aggregation failure: if [ -z ${INDEXESSIZE} ] then export INDEXESSIZE=0 fi # If no LOBS found set INDEXESSIZE to 0 to avoid the aggregation failure: if [ -z ${LOBSIZE} ] then export LOBSIZE=0 fi echo "" export OBJECTSIZE=$(echo "${SINGLETABLESIZE} + ${LOBSIZE} + ${INDEXESSIZE}" | bc) echo "[TOTAL OBJECT SIZE: ${OBJECTSIZE} MB]" echo "" # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/last_logon_report.sh 0000740 0152073 0152061 00000020103 13775063436 016545 0 ustar oracle oinstall ################################################### # This script check last logon time for EACH User. # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 03-06-2013 # # # # # # # # ################################################### ############# # Description: ############# echo echo "====================================================================" echo "This script check the last logon time for EACH User on the database." echo "====================================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. ############################# # Listing Available Instances: ############################# # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Run this script Against:[Enter the number]" echo "--------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi ########################################## # Exit if the user is not the Oracle Owner: ########################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi ########################### # Getting DB_NAME: ########################### VAL1=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/oradebug.sh 0000740 0152073 0152061 00000021507 13775064113 014603 0 ustar oracle oinstall # ########################################################################### VER="[1.2]" # Script to generate ORABEDUG report. # To be run against a hung instance. # Author: Mahmmoud ADEL # # # # # # # # ### # # # # # # # Created: 24-01-17 # Modified 31-05-20 Making SYSTEMSTATE the default # # # # # ########################################################################### # ############ # Description: # ############ echo echo "================================================================" echo "This script runs ORADEBUG to dump HANG analysis into trace file." echo "================================================================" echo echo -e "\033[33;5mORADEBUG utility should be run in SEVERE cases; where the instance is totally hung as it may crash your instance!\033[0m" sleep 3 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select ORACLE_SID: [Enter the number]" echo "-----------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID Number" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -f /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # ################################ # SQLPLUS: RUN ORADEBUG: # ################################ echo echo "Enter the HANG ANALYSIS level: [Enter one of these values [1,2,3,4,5,10]]" echo "------------------------------" echo "" while read ANALYZE_LEVEL do case ${ANALYZE_LEVEL} in "1"|"2"|"3"|"4"|"5"|"10") echo;echo "Hang Analysis Level is: ${ANALYZE_LEVEL}"; break ;; *) echo echo "Invalid Hang Analysis Level, please enter a number from this list [1,2,3,4,5,10]:" echo "---------------------------------------------------------------------------------";; esac done echo echo "Select the mode you want to run ORABEDUG with:" echo "==============================================" echo "[1] to run ORADEBUG with SYSTEMSTATE option. [Default]" echo "[2] to run ORADEBUG against the DATABASE." while read ANS do case $ANS in ""|"1"|"SYSTEM"|"system") echo;echo "ORADEBUG will analyze SYSTEM hang now ...";echo;sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/nolog' << EOF set _prelim on conn / as sysdba oradebug setmypid -- Set tracefile size unlimited: oradebug unlimit -- Run ORADEBUG: --oradebug dump crs ${ANALYZE_LEVEL} --oradebug -g all dump systemstate 266 oradebug dump systemstate 266 oradebug tracefile_name --Flush any pending writes to the trace file and close it: oradebug flush oradebug close_trace EOF break;; "2"|"DATABASE"|"database") echo; echo "ORADEBUG will analyze DATABASE hang now ..." echo "[If this session hung for more than a minute, kill it and run the script again with SYSTEMSTATE option.]";echo;sleep 1; # I know it's not wise to connect directly with SYSDBA as the DB is supposed to be hung, but starting from 11.2.0.2 onwards, hanganalyze will not produce output under a sqlplus "preliminary connection" unless you are connected to a fully logged SQLPLUS session! [Doc ID 452358.1]. ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF oradebug setmypid -- perform cluster DB wide HANGANALYZE: oradebug setinst all -- Set tracefile size unlimited: oradebug unlimit --oradebug tracefile_name --oradebug -g def hanganalyze ${ANALYZE_LEVEL} --oradebug -g all hanganalyze ${ANALYZE_LEVEL} oradebug hanganalyze ${ANALYZE_LEVEL} --oradebug tracefile_name --Flush any pending writes to the trace file and close it: oradebug flush oradebug close_trace EOF break ;; *) echo "Please enter a VALID answer [1|2]"; echo "*********************************" ;; esac done # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/report_long_runing_queries.sh 0000740 0152073 0152061 00000031532 13775064232 020465 0 ustar oracle oinstall # ################################################################################## # Checking long running queries run by specific user # [Ver 1.2] # # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 09-03-17 # # # # # # Modified: 21-01-19 Enhanced the fetch for ORACLE_HOME. # 19-02-19 Enabled the HTML report version. # 06-07-20 New calculation method for 12c+ updated. # # # # # # # # # # # ################################################################################## EMAIL="youremail@yourcompany.com" SCRIPT_NAME="report_long_runing_queries" SRV_NAME=`uname -n` case ${EMAIL} in "youremail@yourcompany.com") echo echo "****************************************************************************************************" echo "Buddy! You will not receive an E-mail with the result, because you didn't set EMAIL variable yet" echo "Just replace youremail@yourcompany.com with your right email." echo "****************************************************************************************************" echo esac export EMAIL # ######################### # THRESHOLDS: # ######################### # Modify the THRESHOLDS to the value you prefer: EXEC_TIME_IN_MINUTES=60 # Report Sessions running longer than N minutes [Default is 60 minutes]. LONG_RUN_SESS_COUNT=0 # CONTROL the number of long running sessions if reached, the report will tirgger. [Default 0 which means report all long running sessions]. HTMLENABLE=Y # Enable HTML Email Format export EXEC_TIME_IN_MINUTES export LONG_RUN_SESS_COUNT # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ######################### # SQLPLUS Output Format: # ######################### SQLLINESIZE=160 SQLPAGES=1000 SQLLONG=999999999 export SQLLINESIZE export SQLPAGES export SQLLONG # ########################## # Neutralize login.sql file: [Bug Fix] # ########################## # Existance of login.sql file under Oracle user Linux home directory eliminates many functions during the execution of this script from crontab: if [ -f ${USR_ORA_HOME}/login.sql ] then mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################### # Setting ORACLE_SID: # ######################### for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -f /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # ################### # Getting DB Version: # ################### echo "Checking DB Version" VAL311=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 60*${EXEC_TIME_IN_MINUTES} and TOTALWORK <> '0' and round(SOFAR/TOTALWORK*100,2) <> '100'; exit; EOF ) LONG_RUN_COUNT2=`echo ${LONG_RUN_COUNT_RAW2}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` if [ ${LONG_RUN_COUNT2} -gt ${LONG_RUN_SESS_COUNT} ] then # Long running query output: LONG_QUERY_DETAIL2=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF col OPERATION for a21 col "%DONE" for 999.999 col "STARTED|MIN_ELAPSED|MIN_REMAIN" for a26 col MESSAGE for a77 col "USERNAME| SID,SERIAL#" for a28 spool ${LOGFILE} select USERNAME||'| '||SID||','||SERIAL# "USERNAME| SID,SERIAL#",SQL_ID --,OPNAME OPERATION --,substr(SOFAR/TOTALWORK*100,1,5) "%DONE" ,round(SOFAR/TOTALWORK*100,2) "%DONE" ,to_char(START_TIME,'DD-MON HH24:MI')||'| '||trunc(ELAPSED_SECONDS/60)||'|'||trunc(TIME_REMAINING/60) "STARTED|MIN_ELAPSED|MIN_REMAIN" ,MESSAGE from v\$session_longops where ELAPSED_SECONDS > 60 and TOTALWORK <> '0' and round(SOFAR/TOTALWORK*100,2) <> '100' order by "STARTED|MIN_ELAPSED|MIN_REMAIN" desc, "USERNAME| SID,SERIAL#"; spool off exit; EOF ) cat ${LOGFILE} export MSGSUBJECT="Info: Long Running Queries on DB [${ORACLE_SID}] on Server [${SRV_NAME}]" ${MAILEXEC} "${MSGSUBJECT}" ${EMAIL} < ${LOGFILE} ( echo "To: ${EMAIL};" echo "MIME-Version: 1.0" echo "Content-Type: text/html;" echo "Subject: ${MSGSUBJECT}" cat ${LOGFILE} ) | ${SENDMAIL} fi else # If database version is 10g backwards: # Check the Long Running Session Count: LONG_RUN_COUNT_RAW2=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 60*${EXEC_TIME_IN_MINUTES} and username is not null and module is not null and module not like 'backup%' and module not like 'OGG-%' and status = 'ACTIVE'; exit; EOF ) LONG_RUN_COUNT2=`echo ${LONG_RUN_COUNT_RAW2}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` if [ ${LONG_RUN_COUNT2} -gt ${LONG_RUN_SESS_COUNT} ] then # Long running query output: LONG_QUERY_DETAIL2=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF set long ${SQLLONG} col module for a30 col DURATION_HOURS for 99999.9 col STARTED_AT for a13 col "USERNAME| SID,SERIAL#" for a30 col "SQL_ID | SQL_TEXT" for a${SQLLINESIZE} spool ${LOGFILE} select username||'| '||sid ||','|| serial# "USERNAME| SID,SERIAL#",substr(MODULE,1,30) "MODULE", to_char(sysdate-last_call_et/24/60/60,'DD-MON HH24:MI') STARTED_AT, last_call_et/60/60 "DURATION_HOURS" ,SQL_ID ||' | '|| (select SQL_FULLTEXT from v\$sql where address=sql_address and CHILD_NUMBER=SQL_CHILD_NUMBER) "SQL_ID | SQL_TEXT" --,SQL_ID ||' | '|| (select SQL_FULLTEXT from v\$sql where address=sql_address) "SQL_ID | SQL_TEXT" --,SQL_ID from v\$session where -- To capture active session for more than defined EXEC_TIME_IN_MINUTES variable in minutes: last_call_et > 60*${EXEC_TIME_IN_MINUTES} and username is not null and module is not null and module not like 'backup%' and status = 'ACTIVE' order by "DURATION_HOURS" desc; spool off exit; EOF ) cat ${LOGFILE} export MSGSUBJECT="Info: Long Running Queries on DB [${ORACLE_SID}] on Server [${SRV_NAME}]" ${MAILEXEC} "${MSGSUBJECT}" ${EMAIL} < ${LOGFILE} ( echo "To: ${EMAIL};" echo "MIME-Version: 1.0" echo "Content-Type: text/html;" echo "Subject: ${MSGSUBJECT}" cat ${LOGFILE} ) | ${SENDMAIL} fi fi done # ############################# # De-Neutralize login.sql file: # ############################# # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/role_ddl.sh 0000740 0152073 0152061 00000022061 13775063373 014602 0 ustar oracle oinstall # ################################################# # This script show the user details (Creation Stmt) # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-09-11 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # 16-09-14 Add Search Feature. # # # ################################################# # ########### # Description: # ########### echo echo "================================================" echo "This script shows the user's CREATION STATEMENT." echo "================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ############################################# # SQLPLUS: Get the Creation statment for a ROLE: # ############################################# # Variables echo echo Please enter the ROLE NAME: echo "==========================" while read ROLE do case ${ROLE} in "")echo echo "Enter the ROLE NAME:" echo "====================";; public|PUBLIC|Public) SPOOL_FILE="${USR_ORA_HOME}"/"${ROLE}"_creation_stmt.log ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 set echo off heading off feedback off spool '$SPOOL_FILE' select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE||';' from dba_role_privs where grantee= 'PUBLIC' UNION select 'GRANT '||PRIVILEGE||' TO '||GRANTEE||';' from dba_sys_privs where grantee= 'PUBLIC' UNION select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||';' from DBA_TAB_PRIVS where GRANTEE='PUBLIC' and OWNER not in ('SYS','SYSTEM','WMSYS','XDB','DBSNMP','OLAPSYS','ORDSYS'); spool off EOF if [ -f "${SPOOL_FILE}" ] then echo;echo "The Creation Statement has been spooled in: ${SPOOL_FILE}" echo fi exit;break ;; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_ROLES WHERE ROLE=upper('$ROLE'); EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "INFO: ROLE [${ROLE}] IS NOT EXIST ON DATABASE [$ORACLE_SID] !" echo; echo "Searching..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off select role "Available Roles" from dba_roles where role like upper ('%$ROLE%'); EOF echo; echo "Please Enter the FULL ROLE NAME:";echo "===============================" ;; *) break;; esac esac done SPOOL_FILE="${USR_ORA_HOME}"/"${ROLE}"_creation_stmt.log ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 set echo off heading off feedback off PROMPT spool '$SPOOL_FILE' PROMPT ROLE [${ROLE}] DDL: PROMPT ------------------ SELECT 'CREATE ROLE ' || ROLE ||';' FROM DBA_ROLES WHERE ROLE=UPPER('$ROLE') UNION select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted Roles" from dba_role_privs where grantee= upper('$ROLE') UNION select 'GRANT '||PRIVILEGE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted System Privileges" from dba_sys_privs where grantee= upper('$ROLE') UNION select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where GRANTEE=upper('$ROLE'); spool off EOF if [ -f "${SPOOL_FILE}" ] then echo;echo "The Creation Statement has been spooled in: ${SPOOL_FILE}" echo fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/SHUTDOWN_All.sh 0000740 0152073 0152061 00000020211 13775601331 015044 0 ustar oracle oinstall ################################################### # Shutting Down All Databases & Listeners # VER 1.2 # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 13-01-2014 # # # # # # ################################################### SCRIPT_NAME="SHUTDOWN_All.sh" SRV_NAME=`uname -n` ############# # Description: ############# echo echo "====================================================================" echo "This script SHUTDOWN All Running Databases & Listeners on the SERVER..." echo "====================================================================" echo sleep 2 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. ########################### # Getting ORACLE_SID ########################### # Exit with sending Alert mail if No DBs are running: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) if [ $INS_COUNT -eq 0 ] then echo "No Databases Are Currently Running !" exit fi # Setting ORACLE_SID: #################### for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib ########################### # Getting DB_NAME: ########################### VAL1=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <> >> >>" done exit else echo "ALL INSTANCES ARE DOWN." fi done ############### # END OF SCRIPT ############### # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/parameter_val.sh 0000740 0152073 0152061 00000020224 13775602526 015636 0 ustar oracle oinstall # ################################################################################################## # Script to Show the value of DB Parameters. # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 05-06-10 # # # # # # Modified: 02-01-14 Customized the script to run on various environments. # 13-05-14 Add "IS_DEFAULT" column. # 17-09-20 Add new options [List all parameters & Non-DEFAULT parameters] # # ################################################################################################## # ########### # Description: # ########### echo echo "============================================================" echo "This script Shows the value of a DB Initialization Parameter ..." echo "============================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ####################################### # SQLPLUS: View Norm/Hidd Parameter value: # ####################################### #Variables echo "" echo "Enter the Parameter Name or part of it: [Blank input will List All NON-DEFAULT Parameters | * will list All parameters [Visible & Hidden]]" echo "======================================" read PARM case ${PARM} in '') # Blank Value will list all NON-DEFAULT parameters: ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set lines 170 pages 10000 --col "INSTANCE_NAME.PARAMETER_NAME" for a110 select i.INSTANCE_NAME||'.'||p.NAME||'='''||p.VALUE||'''' "INSTANCE_NAME.PARAMETER_NAME" from gv\$parameter p, gv\$instance i where p.INST_ID=i.INST_ID and p.ISDEFAULT='FALSE' order by "INSTANCE_NAME.PARAMETER_NAME"; EOF ;; '*') # * will list all parameters: [Visible and Hidden]: ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 169 feedback off pages 100 col Parameter for a50 col "Session Value" for a45 col "Instance Value" for a80 col "IS_DEFAULT" for a10 --SELECT a.ksppinm "Parameter", b.ksppstvl "Session Value", c.ksppstvl "Instance Value",decode (b.ksppstdf,'TRUE','YES','FALSE','NO') "IS_DEFAULT" SELECT a.ksppinm "Parameter", c.ksppstvl "Instance Value",decode (b.ksppstdf,'TRUE','YES','FALSE','NO') "IS_DEFAULT" FROM x\$ksppi a, x\$ksppcv b, x\$ksppsv c WHERE a.indx = b.indx AND a.indx = c.indx order by b.ksppstdf,a.ksppinm; EOF ;; *) # Ay other value will list all the parameters that match: ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 169 feedback off pages 1000 col Parameter for a50 col "Session Value" for a45 col "Instance Value" for a80 col "IS_DEFAULT" for a10 --SELECT a.ksppinm "Parameter", b.ksppstvl "Session Value", c.ksppstvl "Instance Value",decode (b.ksppstdf,'TRUE','YES','FALSE','NO') "IS_DEFAULT" SELECT a.ksppinm "Parameter", c.ksppstvl "Instance Value",decode (b.ksppstdf,'TRUE','YES','FALSE','NO') "IS_DEFAULT" FROM x\$ksppi a, x\$ksppcv b, x\$ksppsv c WHERE a.indx = b.indx AND a.indx = c.indx AND a.ksppinm LIKE lower('%$PARM%') order by b.ksppstdf,a.ksppinm; EOF ;; esac # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/invalid_objects.sh 0000740 0152073 0152061 00000022352 13775601470 016154 0 ustar oracle oinstall ################################################### # Script to check invalid objects # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-08-11 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # # # ################################################### ############# # Description: ############# echo echo "=====================================================" echo "This script Checks ALL INVALID OBJECTS on a database." echo "=====================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib ########################################## # Exit if the user is not the Oracle Owner: ########################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi #################### # VARIABLES: #################### LOC1=${USR_ORA_HOME} cd ${LOC1} ################################# # SQLPLUS: Check Invalid Objects ################################# ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' < 'VALID' and object_type like '%PACKAGE%' union select 'alter type '||owner||'.'||object_name||' compile specification;' from dba_objects where status <> 'VALID' and object_type like '%TYPE%'union select 'alter '||object_type||' '||owner||'.'||object_name||' compile;' from dba_objects where status <> 'VALID' and object_type not in ('PACKAGE','PACKAGE BODY','SYNONYM','TYPE','TYPE BODY') union select 'alter public synonym '||object_name||' compile;' from dba_objects where status <> 'VALID' and object_type ='SYNONYM'; spool off select 'Invalid Objects#: '||count(distinct (owner||object_name)) a from dba_objects where status <> 'VALID'; EOF # Check if the fix script is exist: if [ -f ${LOC1}/FIX_INVALID_OBJ.sql ] then echo;echo "Do you want to FIX THOSE INVALID Objects? [Y|N] [Y]" echo "========================================" while read ANS do case $ANS in ""|y|Y|yes|YES|Yes) echo;echo "START COMPILING INVALID OBJECTS ...";sleep 1 ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 'VALID' and object_type like '%PACKAGE%' union select 'alter TYPE '||owner||'.'||object_name||' compile specification;' from dba_objects where status <> 'VALID' and object_type like '%TYPE%'union select 'alter '||object_type||' '||owner||'.'||object_name||' compile;' from dba_objects where status <> 'VALID' and object_type not in ('PACKAGE','PACKAGE BODY','SYNONYM','TYPE','TYPE BODY') union select 'alter public synonym '||object_name||' compile;' from dba_objects where status <> 'VALID' and object_type ='SYNONYM'; select 'Invalid Objects#: '||count(distinct (owner||object_name)) a from dba_objects where status <> 'VALID'; EOF break ;; n|N|no|NO|No) echo;echo "Later To FIX the invalid objects:" echo "run script: ${LOC1}/FIX_INVALID_OBJ.sql" echo "OR better execute: @?/rdbms/admin/utlrp.sql" echo;exit;break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/stop_tracing.sh 0000740 0152073 0152061 00000022246 13775601433 015512 0 ustar oracle oinstall # ################################################# # Script to STOP tracing an Oracle Traced Session. # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-12-11 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # 04-05-14 Enhanced search criteria # for generated trace file. # # ################################################# # ########### # Description: # ########### echo echo "=================================================" echo "This script STOP Tracing a TRACED Oracle Session." echo "=================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################### # Getting BDUMP Location: # ######################### VAL_DUMP=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < '$SESSIONID', serial_num => '$SESSIONSERIAL'); end; / EOF ) VAL2=`echo $VAL1| grep "successfully completed"` if [ -z "${VAL2}" ] then echo echo "The Session with Provided SID & SERIAL# Is NOT Being Traced!" echo "Script Terminated." echo exit fi echo sleep 1 echo "Tracing Has been STOPPED Successfully." TRACEFILE=`find ${BDUMP}/${VAL44}_ora_${VAL22}.trc -mmin -10|tail -1` echo echo "Trace File Location:" echo "-------------------" if [ -z ${TRACEFILE} ] then echo "You can find the TRACE file Under: ${BDUMP}" else sleep 1 echo "${TRACEFILE}" ${ORACLE_HOME}/bin/tkprof ${TRACEFILE} ${TRACEFILE}_tkprofed.log sys=no waits=yes sleep 3 echo "The TKPROFED version [Readable version] of the TRACE FILE is:" echo "--------------------" echo "${TRACEFILE}_tkprofed.log" fi echo # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/table_info.sh 0000740 0152073 0152061 00000040371 13775601554 015123 0 ustar oracle oinstall ################################################### # This script show the TABLE DETAILS # Ver 2.0 # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 10-04-11 # # # # # # Modified: 28-02-19 Added Statistics status. # 14-05-19 Added the DDL Generation. # ################################################### # ########### # Description: # ########### echo echo "==============================" echo "This script gets TABLE Details ..." echo "==============================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################################## # SQLPLUS: Get table details: # ######################################## # Variables echo echo "Enter the OWNER of Table:" echo "========================" while read OWNER do case ${OWNER} in "")echo echo "Enter the OWNER of the Table:" echo "============================";; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('${OWNER}'); EOF ) VAL22=`echo ${VAL11}| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "ERROR: USER [${OWNER}] IS NOT EXIST ON DATABASE [${ORACLE_SID}] !" echo echo "Enter the OWNER of the Table:" echo "============================";; *) break;; esac esac done echo echo "Enter the TABLE name:" echo "====================" while read OBJECT_NAME do case ${OBJECT_NAME} in "")echo echo "Enter the TABLE NAME:" echo "====================";; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_TABLES WHERE OWNER=upper('${OWNER}') AND TABLE_NAME=UPPER('${OBJECT_NAME}'); EOF ) VAL22=`echo ${VAL11}| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "ERROR: TABLE [${OBJECT_NAME}] IS NOT EXIST under [${OWNER}] SCHEMA !" echo; echo "Searching for tables that match provided string ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 190 set pagesize 1000 set feedback off set trim on set echo off col TABLE_NAME for a45 select TABLE_NAME FROM DBA_TABLES WHERE OWNER=upper('${OWNER}') AND TABLE_NAME like UPPER('%${OBJECT_NAME}%'); EOF echo echo "Enter A VALID TABLE NAME:" echo "========================";; *) break;; esac esac done # Getting Object Type: VAL7=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set heading off echo off feedback off SELECT object_type from dba_objects where owner=upper('${OWNER}') and object_name=upper('${OBJECT_NAME}'); EOF ) OBJECT_TYPE=`echo ${VAL7}| awk '{print $(NF)}'` case ${OBJECT_TYPE} in # Correct the value of BODY to PACKAGE BODY: "BODY") OBJECT_TYPE="PACKAGE" esac ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 linesize 200 heading off feedback off col DDL_STATEMENT for a160 word_wrapped PROMPT PROMPT -- RETRIEVING DDL STATEMENT FOR THE TABLE AND ITS CONSTRAINTS: [${OWNER}.${OBJECT_NAME}] ... PROMPT -- ----------------------------------------------------------- set long 10000000 col DDL_STATEMENT for a160 EXECUTE DBMS_METADATA.SET_TRANSFORM_PARAM (DBMS_METADATA.SESSION_TRANSFORM, 'CONSTRAINTS_AS_ALTER', true); EXECUTE DBMS_METADATA.SET_TRANSFORM_PARAM (DBMS_METADATA.SESSION_TRANSFORM, 'PRETTY' , true); EXECUTE DBMS_METADATA.SET_TRANSFORM_PARAM (DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR' , true); EXECUTE DBMS_METADATA.SET_TRANSFORM_PARAM (DBMS_METADATA.SESSION_TRANSFORM, 'STORAGE' , false); SELECT dbms_metadata.get_ddl(upper('${OBJECT_TYPE}'),upper('${OBJECT_NAME}'),upper('${OWNER}')) DDL_STATEMENT FROM dual; PROMPT -- DISABLE REFERENCING FK ON OTHER TABLES: [For reference only] PROMPT -- --------------------------------------- SELECT 'ALTER TABLE '||owner||'.'||table_name||' DISABLE CONSTRAINT '||constraint_name||';' FROM DBA_CONSTRAINTS WHERE constraint_type = 'R' AND r_constraint_name IN (SELECT constraint_name from DBA_CONSTRAINTS WHERE OWNER=upper('${OBJECT_OWNER}') AND table_name=upper('${OBJECT_NAME}') AND constraint_type='P'); PROMPT PROMPT -- INDEXES DDL: PROMPT -- ------------ SELECT dbms_metadata.get_dependent_ddl('INDEX', upper('${OBJECT_NAME}'), upper('${OWNER}')) DDL_STATEMENT FROM dual; PROMPT PROMPT -- Granted Privileges: PROMPT -- ------------------- select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||';' from DBA_TAB_PRIVS where owner=upper('${OWNER}') and table_name=upper('${OBJECT_NAME}'); set pages 100 heading on PROMPT PROMPT General Info: PROMPT ------------- set linesize 190 col "OWNER.TABLE" for a35 col tablespace_name for a25 col PCT_FREE for 99999999 col PCT_USED for 99999999 col "STATS_LOCKED|STALE|DATE" for a23 col "READONLY" for a8 select t.owner||'.'||t.table_name "OWNER.TABLE",t.TABLESPACE_NAME,t.PCT_FREE --,t.PCT_USED,d.extents,t.MAX_EXTENTS,t.COMPRESSION,t.READ_ONLY "READONLY",o.created,t.LAST_ANALYZED ,t.PCT_USED,d.extents,t.MAX_EXTENTS,t.COMPRESSION,t.STATUS,o.created,s.stattype_locked||'|'||s.stale_stats||'|'||s.LAST_ANALYZED "STATS_LOCKED|STALE|DATE" from dba_tables t, dba_objects o, dba_segments d, dba_tab_statistics s where t.owner= upper('${OWNER}') and t.table_name = upper('${OBJECT_NAME}') and o.owner=t.owner and o.object_name=t.table_name and o.owner=d.owner and t.table_name=d.SEGMENT_NAME and o.owner=s.owner and t.table_name=s.table_name; PROMPT PROMPT Column Details: PROMPT --------------- col Name for a30 col Type for a30 desc ${OWNER}.${OBJECT_NAME} PROMPT PROMPT PROMPT Getting Table Size [TABLE + ITS LOBS + ITS INDEXES]... PROMPT ------------------- /* --select SUM(BYTES/1024/1024)||'MB' FROM SYS.DBA_EXTENTS WHERE OWNER = upper('$OWNER') AND SEGMENT_NAME = upper('$OBJECT_NAME') GROUP BY SEGMENT_NAME; SELECT TRUNC(sum(bytes)/1024/1024)||' MB' FROM (SELECT segment_name table_name, owner, bytes FROM dba_segments WHERE segment_type = 'TABLE' UNION ALL SELECT l.table_name, l.owner, s.bytes FROM dba_lobs l, dba_segments s WHERE s.segment_name = l.segment_name AND s.owner = l.owner AND s.segment_type = 'LOBSEGMENT') WHERE owner in UPPER('${OWNER}') AND table_name in UPPER('${OBJECT_NAME}'); */ -- The following block quoted from: https://willsnotes.wordpress.com/2013/09/20/find-size-of-table-in-oracle-includes-indexes-and-lobs set heading on echo off COLUMN TABLE_NAME FORMAT A32 COLUMN OBJECT_NAME FORMAT A32 COLUMN OWNER FORMAT A30 SELECT owner, table_name, TRUNC(sum(bytes)/1024/1024) TOTAL_SIZE_MB FROM (SELECT segment_name table_name, owner, bytes FROM dba_segments WHERE segment_type = 'TABLE' UNION ALL SELECT i.table_name, i.owner, s.bytes FROM dba_indexes i, dba_segments s WHERE s.segment_name = i.index_name AND s.owner = i.owner AND s.segment_type = 'INDEX' UNION ALL SELECT l.table_name, l.owner, s.bytes FROM dba_lobs l, dba_segments s WHERE s.segment_name = l.segment_name AND s.owner = l.owner AND s.segment_type = 'LOBSEGMENT' UNION ALL SELECT l.table_name, l.owner, s.bytes FROM dba_lobs l, dba_segments s WHERE s.segment_name = l.index_name AND s.owner = l.owner AND s.segment_type = 'LOBINDEX') WHERE owner= UPPER('${OWNER}') and table_name = UPPER('${OBJECT_NAME}') GROUP BY table_name, owner --HAVING SUM(bytes)/1024/1024 > 10 /* Ignore really small tables */ ORDER BY SUM(bytes) desc; PROMPT PROMPT PROMPT INDEXES On the Table: PROMPT --------------------- set pages 100 feedback on set heading on COLUMN OWNER FORMAT A25 heading "Index Owner" COLUMN INDEX_NAME FORMAT A35 heading "Index Name" COLUMN COLUMN_NAME FORMAT A30 heading "On Column" COLUMN COLUMN_POSITION FORMAT 9999 heading "Pos" COLUMN "INDEX" FORMAT A40 COLUMN TABLESPACE_NAME FOR A25 COLUMN INDEX_TYPE FOR A15 SELECT IND.OWNER||'.'||IND.INDEX_NAME "INDEX", IND.INDEX_TYPE, COL.COLUMN_NAME, COL.COLUMN_POSITION, IND.TABLESPACE_NAME, IND.STATUS, IND.UNIQUENESS, S.stattype_locked||'|'||S.stale_stats||'|'||S.LAST_ANALYZED "STATS_LOCKED|STALE|DATE" FROM SYS.DBA_INDEXES IND, SYS.DBA_IND_COLUMNS COL, SYS.DBA_IND_STATISTICS S WHERE IND.TABLE_NAME = upper('${OBJECT_NAME}') AND IND.TABLE_OWNER = upper('${OWNER}') AND IND.TABLE_NAME = COL.TABLE_NAME AND IND.OWNER = COL.INDEX_OWNER AND IND.TABLE_OWNER = COL.TABLE_OWNER AND IND.INDEX_NAME = COL.INDEX_NAME AND IND.OWNER = S.OWNER AND IND.INDEX_NAME = S.INDEX_NAME; PROMPT PROMPT PROMPT CONSTRAINTS On the Table: PROMPT ------------------------- col type format a10 col constraint_name format a40 COL COLUMN_NAME FORMAT A25 heading "On Column" select decode(d.constraint_type, 'C', 'Check', 'O', 'R/O View', 'P', 'Primary', 'R', 'Foreign', 'U', 'Unique', 'V', 'Check view') type , d.constraint_name , c.COLUMN_NAME , d.status , d.last_change from dba_constraints d, dba_cons_columns c where d.owner = upper('${OWNER}') and d.table_name = upper('${OBJECT_NAME}') and d.OWNER=c.OWNER and d.CONSTRAINT_NAME=c.CONSTRAINT_NAME order by 1; PROMPT PROMPT PROMPT Foreign Keys WITHOUT INDEX: [Recommended to Index them to Avoid Bad Performance (On OLTP only)] PROMPT --------------------------- col constraint_name format a40 COL COLUMN_NAME FORMAT A25 heading "On Column" select acc.CONSTRAINT_NAME, acc.COLUMN_NAME, acc.POSITION, 'No Index' Problem from dba_cons_columns acc, dba_constraints ac where ac.CONSTRAINT_NAME = acc.CONSTRAINT_NAME and ac.CONSTRAINT_TYPE = 'R' and acc.OWNER =upper('${OWNER}') and acc.TABLE_NAME =upper('${OBJECT_NAME}') and not exists ( select 'TRUE' from dba_ind_columns b where b.TABLE_OWNER = acc.OWNER and b.TABLE_NAME = acc.TABLE_NAME and b.COLUMN_NAME = acc.COLUMN_NAME and b.COLUMN_POSITION = acc.POSITION) order by acc.OWNER, acc.CONSTRAINT_NAME, acc.COLUMN_NAME, acc.POSITION; PROMPT PROMPT PROMPT DMLs On the Table: PROMPT ------------------- set feedback off col TRUNCATED for a9 col LAST_DML_DATE for a13 select INSERTS,UPDATES,DELETES,TRUNCATED,TIMESTAMP LAST_DML_DATE from DBA_TAB_MODIFICATIONS where TABLE_OWNER= upper('${OWNER}') and TABLE_NAME= upper('${OBJECT_NAME}'); PROMPT PROMPT Getting Number of ROWS ... PROMPT ----------------------- set heading off select count(*) from ${OWNER}.${OBJECT_NAME}; PROMPT PROMPT PROMPT Last ROW In the Table: PROMPT ---------------------- set heading on select * from ${OWNER}.${OBJECT_NAME} where rowid=(select max(rowid) from ${OWNER}.${OBJECT_NAME}); PROMPT EOF # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/active_sessions.sh 0000740 0152073 0152061 00000040601 14122402566 016203 0 ustar oracle oinstall # ########################################################################################################## # Script to show all Active Sessions info. # [Ver 1.7] # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 07-02-17 # # # # # # Modified: 03-08-17 Added Running Jobs. # 08-01-18 Added Kill Command for long running queries. # 16-10-18 Added Checking Running Backups. # 16-10-18 Fixed a bug of TOTALWORK=0 in v$session_longops # 15-07-19 Display the command for PAUSE/RESUME/KILL a runnning RMAN backup. # 16-06-20 Added the modules to exclude from the output, defaulted it to exclude goldengate. # 03-02-21 Added more idle events to be excluded (OFS idle, REPL Capture: archive log, # Space Manager: slave idle wait, PX Deq: Execute Reply, PX Deq: Execution Msg). # # # # # # ########################################################################################################## SCRIPT_NAME="active_sessions" SQLLINESIZE=190 export SCRIPT_NAME export SQLLINESIZE # ####################################### # Excluded Modules: # ####################################### EXCLUDED_MODULES="'OGG-USE_OCI_THREAD','OGG-OCI_META_THREAD'" # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ######################### # Check if the OS is Linux: [Disaply the RMAN PAUSE/RESUME command if a backup is currently running] # ######################### case `uname` in Linux ) export SHOW_OS_COMMAND="";; *) export SHOW_OS_COMMAND="--";; esac # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## #CURR_USER=`whoami` # if [ ${ORA_USER} != ${CURR_USER} ]; then # echo "" # echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" # echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" # echo "Script Terminated!" # exit # fi # ################################### # SQLPLUS: Getting All Sessions Info: # ################################### ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF EXEC DBMS_SESSION.set_identifier('${SCRIPT_NAME}'); set feedback off prompt ================================ prompt ACTIVE Sessions in the Database: prompt ================================ set feedback off linesize ${SQLLINESIZE} pages 1000 col inst for 99 col module for a27 col event for a24 col MACHINE for a27 col "ST|WAITD|ACT_SINC|LOGIN" for a35 col "INST|USER|SID,SERIAL#" for a30 col "INS|USER|SID,SER|MACHIN|MODUL" for a64 col "PREV|CURR SQLID" for a27 col "I|BLK_BY" for a9 col "CURRENT SQL" for a14 select substr(s.INST_ID||'|'||s.USERNAME||'| '||s.sid||','||s.serial#||' |'||substr(s.MACHINE,1,20)||'|'||substr(s.MODULE,1,18),1,64)"INS|USER|SID,SER|MACHIN|MODUL" --select s.INST_ID||'|'||s.USERNAME||' | '||s.sid||','||s.serial# "INST|USER|SID,SERIAL#" --,substr(s.MODULE,1,27)"MODULE" --,substr(s.MACHINE,1,27)"MACHINE" ,substr(s.status||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||to_char(LOGON_TIME,'ddMon HH24:MI'),1,40) "ST|WAITD|ACT_SINC|LOGIN" ,substr(w.event,1,24) "EVENT" --,s.PREV_SQL_ID||'|'||s.SQL_ID "PREV|CURR SQLID" ,s.SQL_ID "CURRENT SQL" ,s.FINAL_BLOCKING_INSTANCE||'|'||s.FINAL_BLOCKING_SESSION "I|BLK_BY" from gv\$session s, gv\$session_wait w where s.USERNAME is not null and s.sid=w.sid and s.STATUS='ACTIVE' --and module not in (${EXCLUDED_MODULES}) and w.EVENT NOT IN ( 'SQL*Net message from client' ,'class slave wait' ,'Streams AQ: waiting for messages in the queue' ,'Streams capture: waiting for archive log' ,'Streams AQ: waiting for time management or cleanup tasks' ,'PL/SQL lock timer' ,'rdbms ipc message' ,'OFS idle' --,'REPL Capture: archive log' ,'Space Manager: slave idle wait' ,'PX Deq: Execute Reply' ,'PX Deq: Execution Msg' ) order by "I|BLK_BY" desc,"CURRENT SQL",w.event,"INS|USER|SID,SER|MACHIN|MODUL","ST|WAITD|ACT_SINC|LOGIN" desc; --order by "ST|WA_ST|WAITD|ACT_SINC|LOG_T" desc, "INST|USER|SID,SERIAL#"; set pages 0 PROMPT PROMPT SESSIONS STATUS: PROMPT ---------------- select 'ACTIVE: '||count(*) from gv\$session where USERNAME is not null and status='ACTIVE'; select 'INACTIVE: '||count(*) from gv\$session where USERNAME is not null and status='INACTIVE'; select 'BACKGROUND: '||count(*) from gv\$session where USERNAME is null; select 'TOTAL: '||count(*) from gv\$session; prompt prompt ======================= Prompt Running Jobs: prompt ======================= set pages 1000 col INS for 999 col "JOB_NAME|OWNER|SPID|SID" for a55 col ELAPSED_TIME for a17 col CPU_USED for a17 col "WAIT_SEC" for 9999999999 col WAIT_CLASS for a15 col "BLKD_BY" for 9999999 col "WAITED|WCLASS|EVENT" for a45 select j.RUNNING_INSTANCE INS,j.JOB_NAME ||' | '|| j.OWNER||' |'||SLAVE_OS_PROCESS_ID||'|'||j.SESSION_ID"JOB_NAME|OWNER|SPID|SID" ,s.FINAL_BLOCKING_SESSION "BLKD_BY",ELAPSED_TIME ,substr(s.SECONDS_IN_WAIT||'|'||s.WAIT_CLASS||'|'||s.EVENT,1,45) "WAITED|WCLASS|EVENT",S.SQL_ID from dba_scheduler_running_jobs j, gv\$session s where j.RUNNING_INSTANCE=S.INST_ID(+) and j.SESSION_ID=S.SID(+) order by "JOB_NAME|OWNER|SPID|SID",ELAPSED_TIME; prompt prompt ======================= Prompt Long Running Operations: prompt ======================= set linesize ${SQLLINESIZE} pages 1000 col OPERATION for a21 col "%DONE" for 999.999 col "STARTED|MIN_ELAPSED|REMAIN" for a26 col MESSAGE for a77 col "USERNAME| SID,SERIAL#" for a28 select USERNAME||'| '||SID||','||SERIAL# "USERNAME| SID,SERIAL#",SQL_ID --,OPNAME OPERATION --,substr(SOFAR/TOTALWORK*100,1,5) "%DONE" ,round(SOFAR/TOTALWORK*100,2) "%DONE" ,to_char(START_TIME,'DD-Mon HH24:MI')||'| '||trunc(ELAPSED_SECONDS/60)||'|'||trunc(TIME_REMAINING/60) "STARTED|MIN_ELAPSED|REMAIN" ,MESSAGE from v\$session_longops where SOFAR/TOTALWORK*100 <>'100' and TOTALWORK <> '0' order by "STARTED|MIN_ELAPSED|REMAIN" desc, "USERNAME| SID,SERIAL#"; EOF # ######################### # Checking Running Backups: # ######################### BACKUPJOBCOUNTRAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 60*60*1 and module not in (${EXCLUDED_MODULES}) and status = 'ACTIVE'; exit; EOF ) ACTIVE_SESS_COUNT=`echo ${ACTIVE_SESS_COUNT_RAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` # If ASM DISKS Are Exist, Check the size utilization: if [ ${ACTIVE_SESS_COUNT} -gt 0 ] then ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF PROMPT prompt ============================================================ PROMPT Active Sessions for More Than 1 Hour On Instance [${ORACLE_SID}]: PROMPT ============================================================ set lines ${SQLLINESIZE} pages 1000 col "MODULE | MACHINE" for a63 col DURATION_HOURS for 99999.9 col STARTED_AT for a13 col "USERNAME| SID,SERIAL#| OSPID" for a35 col "SQL_ID | SQL_TEXT" for a120 select s.username||'| '||s.sid ||','|| s.serial# ||' |'||p.spid "USERNAME| SID,SERIAL#| OSPID",substr(s.MODULE,1,30)||' | '||substr(s.MACHINE,1,30) "MODULE | MACHINE", to_char(sysdate-s.last_call_et/24/60/60,'DD-MON HH24:MI') STARTED_AT, s.last_call_et/60/60 "DURATION_HOURS", SQL_ID from v\$session s , v\$process p where s.username is not null and p.addr = s.paddr and s.module is not null and s.module not in (${EXCLUDED_MODULES}) -- 1 is the number of hours and s.last_call_et > 60*60*1 and s.status = 'ACTIVE' order by "DURATION_HOURS"; set pages 0 echo off feedback off linesize ${SQLLINESIZE} PROMPT PROMPT Providing Kill Command for Active Sessions since more than 1 Hour: [Don't kill unless you investigate these sessions first ;-)] PROMPT ------------------------------------------------------------------ select 'ALTER SYSTEM DISCONNECT SESSION '''||sid ||','|| serial#||''' IMMEDIATE;'from v\$session where username is not null and module is not null and module not in (${EXCLUDED_MODULES}) -- 1 is the number of hours and last_call_et > 60*60*1 and status = 'ACTIVE' order by last_call_et/60/60; PROMPT EOF fi # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/delete_applied_archives_on_standby.sh 0000740 0152073 0152061 00000033162 13775064372 022066 0 ustar oracle oinstall # ################################################################################################# # [VER 1.4] # This Script deletes Applied Archives older than Specified N hours on STANDBY DATABASE # This script will run by default against ALL running STANDBY DATABASES. # Please read the following instructions on how to use this script: # - You can set MAIL_LIST variable to your E-mail to receive an email alert if archives # are not applied. # e.g. MAIL_LIST="john.smith@abc.com" # - You can specify the candidate archives for deletion older than N hours by setting # LAST_N_HOURS variable to the number of hours. # e.g. Deleting applied archives in older than 24 hours # LAST_N_HOURS=24 # - You can EXCLUDE any instance from having the script to run against by passing INSTANCE_NAME # to EXL_DB variable. # e.g. excluding orcl from archive deletion: # EXL_DB="\-MGMTDB|ASM|orcl" # - You can use FORCE option when deleting the archives from RMAN console: [Y|N] # e.g. FORCE_DELETION=Y # - You can decide to CROSSCHECK the archivelogs after the archivelogs deletion: [Y|N] # e.g. VALIDATE_ARCHIVES=Y # # # # # # Author: Mahmmoud ADEL # # # # ### # # # # # # # Created: 14-Nov-2016 # Modified: 11-Jan-2017 Added more information to the output. # 17-Jan-2017 Added the capability of turning ON/OFF the options of # FORCE deletion of the archives and CROSSCHECK after the deletion. # 20-Jul-2017 Neutralized login.sql if found under Oracle User Home Directory. # # # # # # # # # # # # ################################################################################################# # ################################## # VARIABLES: [To be ALTERED By User] ....................................... # ################################## SCRIPT_NAME="delete_standby_archives.sh" SRV_NAME=`uname -n` MAIL_LIST="youremail@yourcompany.com" # ############################################################################# # Define the number of HOURS where ARCHIVES older than N Hours will be deleted: [Default 8 HOURS] # ############################################################################# LAST_N_HOURS=8 export LAST_N_HOURS # ############################################################################# # Do you want to CROSSCHECK the ARCHIVELOGS after the deletion?: [Y|N] [Default YES] # ############################################################################# VALIDATE_ARCHIVES=Y # ############################################################################# # Do you want to FORCEFULLY DELETE the ARCHIVELOGS?: [Y|N] [Default NO] # ############################################################################# FORCE_DELETION=N # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ######################### # Setting ORACLE_SID: # ######################### for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi if [ -f ${USR_ORA_HOME}/login.sql ] then mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################### # Variables: # ######################### export PATH=$PATH:${ORACLE_HOME}/bin # ######################### # LOG FILE: # ######################### export LOG_DIR=`pwd` if [ ! -d ${LOG_DIR} ] then export LOG_DIR=/tmp fi LOG_FILE=${LOG_DIR}/DELETE_ARCHIVES.log # ######################### # Getting DB_NAME: # ######################### VAL1=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <= sysdate-${LAST_N_HOURS}/24 order by completion_time asc; EOF echo "" echo "NO CANDIDATE ARCHIVES ARE ELIGIBLE FOR DELETION IN THE LAST ${LAST_N_HOURS} HOURS !" echo "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv" echo "" fi fi fi if [ ${DB_ROLE} -eq 0 ] then echo "" echo "Database [${DB_NAME}] is NOT a STANDBY DB." echo "This script is designed to run against STANDBY DBs ONLY!" echo "Database [${DB_NAME}] SKIPPED!" echo "" fi done # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/gather_stats.sh 0000740 0152073 0152061 00000052751 14055134415 015503 0 ustar oracle oinstall # ################################################################################################################# # V. 2.2 # Backup & Gather Statistics On SCHEMA|TABLE. # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 02-02-2014 # # # # # # Modified: 02-05-2018 Re-coded the script to run the gather stats commands in the background [nohup mode]. # 14-01-2021 Checking the statistics LOCK status before gathering statistics. # 31-05-2021 Added the option of gathering STALE statistics only instead of gathering all statistics. # ################################################################################################################# # ########### # Description: # ########### echo echo "=======================================================" echo "This script Gather & Backup Statistics on SCHEMA|TABLE." echo "=======================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################## # Getting ORACLE_BASE: # ######################## # Get ORACLE_BASE from user's profile if not set: if [ -z "${ORACLE_BASE}" ] then ORACLE_BASE=`grep 'ORACLE_BASE=\/' $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi # ######################### # SQLPLUS Section: # ######################### # PROMPT FOR VARIABLES: # #################### if [ ! -d ${USR_ORA_HOME} ] then export USR_ORA_HOME=/tmp fi GATHERSTATSSCRIPT=${USR_ORA_HOME}/gather_stats_script_DBA_BUNDLE.sql GATHERSTATSSCRIPTRUNNER=${USR_ORA_HOME}/gather_stats_script_DBA_BUNDLE.sh GATHERSTATSSPOOL=${USR_ORA_HOME}/gather_stats_script_DBA_BUNDLE.log STATS_TABLE=BACKUP_STATS STATS_OWNER=SYS STATS_TBS=SYSTEM VAL33=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT STATUS FROM V\$INSTANCE; EOF ) VAL44=`echo $VAL33| awk '{print $NF}'` case ${VAL44} in "OPEN") echo ;; *) echo;echo "ERROR: INSTANCE [${ORACLE_SID}] IS IN STATUS: ${VAL44} !" echo; echo "PLEASE OPEN THE INSTANCE [${ORACLE_SID}] AND RE-RUN THIS SCRIPT.";echo; exit ;; esac echo "Enter the SCHEMA NAME/TABLE OWNER:" echo "==================================" while read SCHEMA_NAME do if [ -z ${SCHEMA_NAME} ] then echo echo "Enter the SCHEMA NAME/TABLE OWNER:" echo "==================================" else VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('${SCHEMA_NAME}'); EOF ) VAL22=`echo ${VAL11}| awk '{print $NF}'` if [ ${VAL22} -eq 0 ] then echo echo "ERROR: USER [${SCHEMA_NAME}] IS NOT EXIST ON DATABASE [${ORACLE_SID}] !" echo echo "Enter the SCHEMA NAME:" echo "=====================" else break fi fi done echo echo "Enter the TABLE NAME: [BLANK VALUE MEANS GATHER THE WHOLE [${SCHEMA_NAME}] SCHEMA STATISTICS]" echo "====================" while read TABLE_NAME do if [ -z ${TABLE_NAME} ] then echo echo "Confirm GATHERING STATISTICS ON WHOLE [${SCHEMA_NAME}] SCHEMA? [Y|N] [Y]" echo "====================================================" while read ANS do case $ANS in ""|y|Y|yes|YES|Yes) echo "GATHERING STATISTICS ON SCHEMA [${SCHEMA_NAME}] ..." echo echo "GATHER HISTOGRAMS ALONG WITH STATISTICS? [Y|N] [N]" echo "=======================================" while read ANS1 do case $ANS1 in y|Y|yes|YES|Yes) HISTO="FOR ALL COLUMNS SIZE SKEWONLY";HISTOMSG="(+HISTOGRAMS)"; break ;; ""|n|N|no|NO|No) HISTO="FOR ALL COLUMNS SIZE 1"; break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done echo printf "`echo "GATHER STATISTICS FOR"` `echo -e "\033[33;5mSTALE\033[0m"` `echo "STATISTCS ONLY? [Y|N] [N]"`\n" echo "===========================================" while read ANS2 do case $ANS2 in y|Y|yes|YES|Yes) STALE_OPTION="OPTIONS => 'GATHER STALE',"; export STALE_OPTION; break ;; ""|n|N|no|NO|No) STALE_OPTION=""; export STALE_OPTION; break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done # Check The Existence of BACKUP STATS TABLE: VAL1=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_TABLES WHERE OWNER=upper('${STATS_OWNER}') AND TABLE_NAME=upper('${STATS_TABLE}'); EOF ) VAL2=`echo $VAL1| awk '{print $NF}'` if [ ${VAL2} -gt 0 ] then echo echo "STATISTICS BACKUP TABLE [${STATS_OWNER}.${STATS_TABLE}] IS ALREADY EXISTS." else echo ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < upper('${STATS_OWNER}'), tblspace => upper('${STATS_TBS}'), stattab => upper('${STATS_TABLE}')); END; / PROMPT EOF fi echo "spool ${GATHERSTATSSPOOL}" > ${GATHERSTATSSCRIPT} echo "PROMPT BACKING UP CURRENT STATISTICS OF SCHEMA [${SCHEMA_NAME}] ..." >>${GATHERSTATSSCRIPT} echo "BEGIN" >>${GATHERSTATSSCRIPT} echo "DBMS_STATS.EXPORT_SCHEMA_STATS (" >>${GATHERSTATSSCRIPT} echo "ownname => upper('${SCHEMA_NAME}')," >>${GATHERSTATSSCRIPT} echo "statown => upper('${STATS_OWNER}')," >>${GATHERSTATSSCRIPT} echo "stattab => upper('${STATS_TABLE}'));" >>${GATHERSTATSSCRIPT} echo "END;" >>${GATHERSTATSSCRIPT} echo "/" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT GATHERING STATISTICS ${HISTOMSG} ON SCHEMA [${SCHEMA_NAME}] ..." >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT Feel free to exist this session any time as this script is running in the background :-)" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT To check the progress:" >>${GATHERSTATSSCRIPT} echo "PROMPT tail -f ${GATHERSTATSSPOOL}" >>${GATHERSTATSSCRIPT} echo "BEGIN" >>${GATHERSTATSSCRIPT} echo "DBMS_STATS.GATHER_SCHEMA_STATS (" >>${GATHERSTATSSCRIPT} echo "ownname => upper('${SCHEMA_NAME}')," >>${GATHERSTATSSCRIPT} echo "METHOD_OPT => '${HISTO}'," >>${GATHERSTATSSCRIPT} echo "DEGREE => DBMS_STATS.AUTO_DEGREE," >>${GATHERSTATSSCRIPT} echo "${STALE_OPTION}" >>${GATHERSTATSSCRIPT} echo "estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE);" >>${GATHERSTATSSCRIPT} echo "END;" >>${GATHERSTATSSCRIPT} echo "/" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT (IN CASE THE NEW STATISTICS ARE PERFORMING BAD, RESTORE BACK THE ORIGINAL STATISTICS USING THE FOLLOWING SQL COMMAND):" >>${GATHERSTATSSCRIPT} echo "PROMPT >>>>" >>${GATHERSTATSSCRIPT} echo "PROMPT EXEC DBMS_STATS.IMPORT_SCHEMA_STATS (ownname => upper('${SCHEMA_NAME}'), statown => upper('${STATS_OWNER}'), stattab => upper('${STATS_TABLE}'));;">>${GATHERSTATSSCRIPT} echo "PROMPT >>>>" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT SCRIPT COMPLETED!" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "spool off" >>${GATHERSTATSSCRIPT} echo "exit" >>${GATHERSTATSSCRIPT} echo "#!/bin/bash" > ${GATHERSTATSSCRIPTRUNNER} echo "nohup ${ORACLE_HOME}/bin/sqlplus \"/ as sysdba\" @${GATHERSTATSSCRIPT} | tee ${GATHERSTATSSPOOL} 2>&1 &" >>${GATHERSTATSSCRIPTRUNNER} chmod 740 ${GATHERSTATSSCRIPTRUNNER} echo "" source ${GATHERSTATSSCRIPTRUNNER} exit 1 ;; n|N|no|NO|No) echo; echo "Enter the TABLE NAME:";echo "====================";break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done else # Check The Existence of ENTERED TABLE: VAL1=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_TABLES WHERE OWNER=upper('${SCHEMA_NAME}') AND TABLE_NAME=upper('${TABLE_NAME}'); EOF ) VAL2=`echo $VAL1| awk '{print $NF}'` if [ ${VAL2} -eq 0 ] then echo echo "ERROR: TABLE [${SCHEMA_NAME}.${TABLE_NAME}] IS NOT EXIST !" echo;echo "Enter the TABLE NAME: [BLANK VALUE MEANS GATHER THE WHOLE SCHEMA [${SCHEMA_NAME}] STATISTICS]" echo "====================" else ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < upper('${STATS_OWNER}'), tblspace => upper('${STATS_TBS}'), stattab => upper('${STATS_TABLE}')); END; / PROMPT EOF fi echo "SET LINESIZE 157" > ${GATHERSTATSSCRIPT} echo "SET PAGESIZE 5000" >>${GATHERSTATSSCRIPT} echo "SET HEADING OFF" >>${GATHERSTATSSCRIPT} echo "spool ${GATHERSTATSSPOOL}" >>${GATHERSTATSSCRIPT} echo "${UNLOCK_STATS_MSG}" >>${GATHERSTATSSCRIPT} echo "${UNLOCK_STATS_SQL}" >>${GATHERSTATSSCRIPT} echo "PROMPT BACKING UP CURRENT STATISTICS OF TABLE [${SCHEMA_NAME}.${TABLE_NAME}] ..." >>${GATHERSTATSSCRIPT} echo "BEGIN" >>${GATHERSTATSSCRIPT} echo "DBMS_STATS.EXPORT_TABLE_STATS (" >>${GATHERSTATSSCRIPT} echo "ownname => upper('${SCHEMA_NAME}')," >>${GATHERSTATSSCRIPT} echo "tabname => upper('${TABLE_NAME}')," >>${GATHERSTATSSCRIPT} echo "statown => upper('${STATS_OWNER}')," >>${GATHERSTATSSCRIPT} echo "stattab => upper('${STATS_TABLE}'));" >>${GATHERSTATSSCRIPT} echo "END;" >>${GATHERSTATSSCRIPT} echo "/" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT GATHERING STATISTICS ${HISTOMSG} FOR TABLE [${SCHEMA_NAME}.${TABLE_NAME}] ${CASCMSG} ..." >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT Feel free to exist this session any time as this script is running in the background :-)" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT To check the progress:" >>${GATHERSTATSSCRIPT} echo "PROMPT tail -f ${GATHERSTATSSPOOL}" >>${GATHERSTATSSCRIPT} echo "BEGIN" >>${GATHERSTATSSCRIPT} echo "DBMS_STATS.GATHER_TABLE_STATS (" >>${GATHERSTATSSCRIPT} echo "ownname => upper('${SCHEMA_NAME}')," >>${GATHERSTATSSCRIPT} echo "tabname => upper('${TABLE_NAME}')," >>${GATHERSTATSSCRIPT} echo "cascade => ${CASCD}," >>${GATHERSTATSSCRIPT} echo "METHOD_OPT => '${HISTO}'," >>${GATHERSTATSSCRIPT} echo "DEGREE => DBMS_STATS.AUTO_DEGREE," >>${GATHERSTATSSCRIPT} echo "estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE);" >>${GATHERSTATSSCRIPT} echo "END;" >>${GATHERSTATSSCRIPT} echo "/" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT => IN CASE THE NEW STATISTICS ARE PERFORMING BAD, RESTORE BACK THE ORIGINAL STATISTICS USING THE FOLLOWING SQL COMMAND:" >>${GATHERSTATSSCRIPT} echo "PROMPT >>>>" >>${GATHERSTATSSCRIPT} echo "PROMPT EXEC DBMS_STATS.IMPORT_TABLE_STATS (ownname => upper('${SCHEMA_NAME}'), tabname => upper('${TABLE_NAME}'), statown => upper('${STATS_OWNER}'), stattab => upper('${STATS_TABLE}'));;" >>${GATHERSTATSSCRIPT} echo "PROMPT >>>>" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "${LOCK_STATS_MSG}" >>${GATHERSTATSSCRIPT} echo "${LOCK_STATS_SQL}" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "PROMPT SCRIPT COMPLETED!" >>${GATHERSTATSSCRIPT} echo "PROMPT" >>${GATHERSTATSSCRIPT} echo "spool off" >>${GATHERSTATSSCRIPT} echo "exit" >>${GATHERSTATSSCRIPT} echo "#!/bin/bash" > ${GATHERSTATSSCRIPTRUNNER} echo "nohup ${ORACLE_HOME}/bin/sqlplus \"/ as sysdba\" @${GATHERSTATSSCRIPT} | tee ${GATHERSTATSSPOOL} 2>&1 &" >>${GATHERSTATSSCRIPTRUNNER} chmod 740 ${GATHERSTATSSCRIPTRUNNER} echo "" source ${GATHERSTATSSCRIPTRUNNER} # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/dbalarm.sh 0000740 0152073 0152061 00000356501 14115362711 014414 0 ustar oracle oinstall # ##################################################################################################################################################### # Database Server Monitoring Script [dbalarm]. VER="[6.7]" SCRIPT_NAME="dbalarm${VER}" # Features: # Report ERRORS in DB, ASM Instance, GRID INFRASTRUCTURE, GOLDENGATE and LISTENERS ALERTLOG plus dmesg DEVICE DRIVER OS log. # Report TABLESPACES, ASM DISKGROUPS and FRA when reach %USED THRESHOLD. # Report OFFLINE databases. # Report CPU, FILESYSTEM, TABLESPACES When hit the THRESHOLD. # Report LONG RUNNING operations/Active SESSIONS on DB when the CPU hits the THRESHOLD. # Report BLOCKING SESSIONS in the database. # Report Failed RMAN Backup Jobs. # Report User Defined DATABASE SERVICES when they go OFFLINE. # Notes: # Most of THRESHOLD and CONTROLS in this script located under THRESHOLDS section. Please adjust them to meet your needs. # ##################################################################################################################################################### # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 22-12-13 # # # # # # # Modified: 23-12-13 Handled non exist logs 1run # 14-05-14 Handled non existance of LOG_DIR directory. # 18-05-14 Add Filsystem monitoring. # 19-05-14 Add CPU monitoring. # 03-12-14 Add Tablespaces monitoring # 08-09-15 mpstat output change in Linux 6 # 02-04-16 Using dba_tablespace_usage_metrics To calculate MAXSIZE (11g onwards) Recommended by Satyajit Mohapatra. # 10-04-16 Add Flash Recovery Area monitoring. # 10-04-16 Add ASM Disk Groups monitoring. # 15-09-16 Add "DIG MORE" feature to report.long running operations, queries # and active sessions on DB side when CPU hits the pre-defined threshold. # 29-12-16 Enhanced ORACLE_HOME search criteria. # 02-01-17 Added EXL_DB parameter to allow the user to exclude DBs from having dbalarm script run against. # 04-05-17 Added the ability to disable Database Down Alert through CHKOFFLINEDB variable. # 11-05-17 Added the option to exclude tablespace/ASM Diskgroup from monitoring. # 11-05-17 Tuned the method of reporting OFFLINE databases & checking listener log. # 20-07-17 Modified COLUMNS env variable to fully display top command output. # Neutralize login.sql if found in Oracle user home directory due to bugs. # 19-10-17 Added the function of checking goldengate logfile. # 11-04-18 Added the feature of monitoring the availability of specific service. # 28-04-18 Added the function of printing the script progress. # 30-04-18 Added Paranoid mode, to report EXPORT/IMPORT, ALTER SYSTEM, ALTER DATABASE # instance STARTUP/SHUTDOWN, other DB Major activities. # 05-09-18 Modified the wait in seconds column (Blocking Sessions section) for 11gr2 compatibility, # Added WAIT_FOR_LOCK_THRES threshold to control reporting of sessions blocked for more than N mintes. # 09-10-18 Enclosing OS Network Failure Statistics (Dropped Packets) whenever TIMOUT error get reported by DB or Listener. # 15-10-18 Added RMAN Backup Failure Check. [Recommended by: Rahul Malode] # 22-10-18 Added the Checking of Running RMAN Backup when CPU hit the threshold. # 01-11-18 Fixing a bug in Monitored Services section. # 08-11-18 Show the exist restore points if FRA hits the threshold. # 27-12-18 Checking if another session is running dbalarm script [to avoid performance degradation]. # 14-01-19 Avoid Monitoring the Services if more than one DB instance is running. # 15-01-19 Added the feature of monitoring the ASM instance ALERTLOG. # 15-01-18 Added the feature of monitoring the GRID INFRASTRUCTURE ALERTLOG. # 16-01-19 Added the feature of monitoring Device Driver OS log "dmesg". # 04-02-19 Added HTML feature to send the alert in HTML format [If sendmail installed, otherwise will use TEXT format automatically]. # 24-03-19 Enhanced the DB Service Monitoring Feature to monitor service availability on RAC setup Locally wise. # 26-03-19 Listing the Master Blocking Sessions When a Blocking Lock get detected. # 27-03-19 Used RULE Based Optimizer against all "checking locks" queries for a better performance on RAC instances. # 15-05-19 Replacement of "bc" function for CPU utilization calculation with "awk". # 20-05-19 When "unable to extend temp segment" error get detected the Email alert will show the top temp space consumers in the DB. # 09-04-20 Added Monitoring filesystem inodes features. # 22-08-20 Exclude reporting error "ORA-235 occurred during an un-locked control file" as advised by MOS 2312580.1. # # # # # # ###################################################################################################################################################### EMAIL="youremail@yourcompany.com" export SRV_NAME="`uname -n`" # Check if MAIL_LIST parameter is not set notify the user and exit: case ${EMAIL} in "youremail@yourcompany.com") echo echo "******************************************************************" echo "Buddy! You forgot to edit line# 70 in dbalarm.sh script." echo "Please replace youremail@yourcompany.com with your E-mail address." echo "******************************************************************" echo echo "Script Terminated !" echo exit;; esac # Check if there is another session of dbalarm is running: [Avoid performance impact] DBALARMCNT=`ps -ef|grep -v grep|grep -v vi|grep dbalarm|wc -l` if [ ${DBALARMCNT} -gt 2 ] then echo -e "\033[32;5mdbalarm.sh script is currently running by another session.\033[0m" echo "" echo "Please make sure the following sessions are completed before running dbalarm script: [ps -ef|grep -v grep|grep -v vi|grep dbalarm]" ps -ef|grep -v grep|grep -v vi|grep dbalarm.sh echo "Script Terminated !" echo exit fi # In case your company Emails go through specific SMTP server. Specify it in the below line and UN-HASH it: #export smtp="mailrelay.mycompany.com:25" #This is an example, you have to check with your Network Admin for the SMTP NAME/PORT to use. export MAIL_LIST="${EMAIL}" #export MAIL_LIST="-r ${SRV_NAME} ${EMAIL}" echo echo "[dbalarm Script Started ...]" # ######################### # THRESHOLDS: # ######################### # Modify the THRESHOLDS to the value you prefer: HTMLENABLE=Y # Enable HTML Email Format [DB] FSTHRESHOLD=95 # THRESHOLD FOR FILESYSTEM %USED [OS] FSITHRESHOLD=95 # THRESHOLD FOR FILESYSTEM INODES %USED [OS] CPUTHRESHOLD=95 # THRESHOLD FOR CPU %BUSY [OS] TBSTHRESHOLD=95 # THRESHOLD FOR TABLESPACE %USED [DB] FRATHRESHOLD=95 # THRESHOLD FOR FRA %USED [DB] ASMTHRESHOLD=95 # THRESHOLD FOR ASM DISK GROUPS %USED [DB] BLOCKTHRESHOLD=1 # THRESHOLD FOR THE NUMBER OF BLOCKED SESSIONS [DB] WAIT_FOR_LOCK_THRES=1 # THRESHOLD FOR THE LOCK TIME OF BLOCKED SESSIONS IN MINUTES [DB] CHKRMANBKP=Y # Enable/Disable Checking of RMAN Backup FAILURE. [Default Enabled] [DB] LAST_MIN_BKP_CHK=5 # REPORT RMAN Backup FAILURE in the last N MINUTES. Should be same interval as the interval of dbalarm script execution in crontab.[DB] CHKLISTENER=Y # Enable/Disable Checking Listeners: [Default Enabled] [DB] CHKOFFLINEDB=Y # Enable/Disable Database Down Alert: [Default Enabled] [DB] CHKGOLDENGATE=Y # Enable/Disable Goldengate Alert: [Default Enabled] [GG] CPUDIGMORE=Y # Break down to DB Active sessions when CPU hit the threshold: [RECOMMENDED TO SET =N on VERY BUSY environments]. [Default Enabled][DB] TIMEOUTDIGMORE=Y # Enable/Disable the display of Network Errors when TIMEOUT error get detected. [Default Enabled] [OS] TEMPSPACEDIGMORE=Y # Enable/Disable the display of TOP Temporary space consumers when ORA-1652 get detected. [Default Enabled] [DB] SERVICEMON="" # Monitor Specific Named DB Services. e.g. SERVICEMON="'ORCL_RO','ERP_SRVC','SAP_SERVICE'" [DB] PARANOIDMODE=N # Enable/Disable Paranoid mode will report more events like export/import, instance shutdown/startup. [Default Disabled] [DB] CHKASMALERTLOG=Y # Enable/Disable Monitoring ASM instance ALERTLOG. [Default Enabled] [DB] CHKCLSALERTLOG=Y # Enable/Disable Monitoring GRID INFRASTRUCTURE ALERTLOG. [Default Enabled] [GI] DEVICEDRIVERLOG=Y # Enable/Disable Check "dmesg" Device Driver log for errors. [Default Enabled] [OS] SQLLINESIZE=200 # The LINE SIZE for SQLPLUS outputs. [DB] OSLINESIZE=300 # The LINE SIZE for OS Commands outputs. [Default is 167] [OS] # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances dbalarm will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ######################### # Excluded TABLESPACES: # ######################### # Here you can exclude one or more tablespace if you don't want to be alerted when they hit the threshold: # e.g. to exclude "UNDOTBS1" modify the following variable in this fashion without removing "donotremove" value: # EXL_TBS="donotremove|UNDOTBS1" EXL_TBS="donotremove" #Exclude TABLESPACES from being checked. # ######################### # Excluded ASM Diskgroups: # ######################### # Here you can exclude one or more ASM Disk Groups if you do NOT want to be alerted when they hit the threshold: # e.g. to exclude "FRA" DISKGROUP modify the following variable in this fashion without removing "donotremove" value: # EXL_DISK_GROUP="donotremove|FRA" Please DO NOT REMOVE/REPLACE the value "dontremove". Good boy ;-) EXL_DISK_GROUP="donotremove" #Exclude ASM DISKGROUPS from being checked. # ######################### # Excluded ERRORS: # ######################### # Here you will tell the script to ignore the ERRORS you don't want to be alerted when they come in the logs: # Use pipe "|" between each error. EXL_DB_ALERT_ERR="ORA-2396|ORA-235|TNS-00507|TNS-12502|TNS-12560|TNS-12537|TNS-00505" #Excluded ALERTLOG ERRORS [Will not get reported]. EXL_LSNR_ERR="TNS-00507|TNS-12502|TNS-12560|TNS-12537|TNS-00505" #Excluded LISTENER ERRORS [Will not get reported]. EXL_GRID_ALERT_ERR="donotremove" #Excluded GRID INFRA ERRORS [Will not get reported]. EXL_GG_ERR="donotremove" #Excluded GoldenGate ERRORS [Will not get reported]. EXL_DMESG_ERR=="donotremove|scsmd" #Excluded OS DEVICE DRIVERS ERRORS [Will not get reported]. # ################################# # Excluded FILESYSTEM/MOUNT POINTS: # ################################# # Here you can exclude specific filesystems/mount points from being reported by dbalarm: # e.g. Excluding: /dev/mapper, /dev/asm mount points: Remember to put a forward Slash / before each Backslash \ EXL_FS="\/dev\/mapper\/|\/dev\/asm\/" #Excluded mount points [Will be skipped during the check]. # ########################### # Check the Linux OS version: # ########################### export PATH=${PATH}:/usr/local/bin FILE_NAME=/etc/redhat-release export FILE_NAME if [ -f ${FILE_NAME} ] then LNXVER=`cat /etc/redhat-release | grep -o '[0-9]'|head -1` export LNXVER # Workaround df command output bug "`/root/.gvfs': Permission denied" export DF='df -hPx fuse.gvfs-fuse-daemon' export DFI='df -iPx fuse.gvfs-fuse-daemon' else export DF='df -h' export DFI='df -o i' fi # ######################### # Checking The FILESYSTEM: # ######################### echo "" echo "Checking FILESYSTEM Utilization ..." # Report Partitions that reach the threshold of Used Space: FSLOG=/tmp/filesystem_DBA_BUNDLE.log echo "[Reported By ${SCRIPT_NAME} Script]" > ${FSLOG} echo "" >> ${FSLOG} ${DF} >> ${FSLOG} ${DF} | grep -v "^Filesystem" |awk '{print substr($0, index($0, $2))}'| egrep -v "${EXL_FS}"|awk '{print $(NF-1)" "$NF}'| while read OUTPUT do PRCUSED=`echo ${OUTPUT}|awk '{print $1}'|cut -d'%' -f1` FILESYS=`echo ${OUTPUT}|awk '{print $2}'` if [ ${PRCUSED} -ge ${FSTHRESHOLD} ] then echo "Filesystem [${FILESYS}] has reached ${PRCUSED}% of USED space. Reporting the problem." mail -s "ALARM: Filesystem [${FILESYS}] on Server [${SRV_NAME}] has reached ${PRCUSED}% of USED space" ${MAIL_LIST} < ${FSLOG} fi done echo "" echo "Checking FILESYSTEM Inodes Utilization ..." FSILOG=/tmp/filesystem_inodes_DBA_BUNDLE.log echo "[Reported By ${SCRIPT_NAME} Script]" > ${FSILOG} echo "" >> ${FSILOG} ${DFI} >> ${FSILOG} ${DFI} | grep -v "^Filesystem" | grep -v "not applicable"| awk '{print substr($0, index($0, $2))}'| egrep -v "${EXL_FS}"|awk '{print $(NF-1)" "$NF}'| while read OUTPUT do PRCUSED=`echo ${OUTPUT}|awk '{print $1}'|cut -d'%' -f1` FILESYS=`echo ${OUTPUT}|awk '{print $2}'` if [ ${PRCUSED} -ge ${FSITHRESHOLD} ] then echo "INODES of Filesystem [${FILESYS}] has reached ${PRCUSED}%. Reporting the problem." mail -s "ALARM: INODES of Filesystem [${FILESYS}] on Server [${SRV_NAME}] has reached ${PRCUSED}%" ${MAIL_LIST} < ${FSILOG} fi done rm -f ${FSLOG} rm -f ${FSILOG} # ############################# # Checking The CPU Utilization: # ############################# # LOGFILE PATH: # ############ export PATH=${PATH}:${ORACLE_HOME}/bin export LOG_DIR=/tmp export LOGFILE=${LOG_DIR}/dbalarm.part.log export CPULOG=${LOG_DIR}/CPU_DBA_BUNDLE.log export MPSTATLOG=${LOG_DIR}/mpstat_DBA_BUNDLE.log export VMSTATLOG=${LOG_DIR}/vmstat_DBA_BUNDLE.log export TOPLOG=${LOG_DIR}/top_DBA_BUNDLE.log export UPTIMELOG=${LOG_DIR}/uptime_DBA_BUNDLE.log export CPULOGCONV=${LOG_DIR}/top_processes_DBA_BUNDLE_CONV.log export CPULOGHTML=${LOG_DIR}/top_processes_DBA_BUNDLE_HTML.log if [ -f ${CPULOGHTML} ] then rm ${CPULOGHTML} fi # ######################### # HTML Preparation: # ######################### case ${HTMLENABLE} in y|Y|yes|YES|Yes|ON|On|on) if [ -x /usr/sbin/sendmail ] then export SENDMAIL="/usr/sbin/sendmail -t" export MAILEXEC="echo #" export HASHHTML="" export HASHHTMLOS="" export ENDHASHHTMLOS="" export HASHNONHTML="--" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) export SENDMAILARGS else export SENDMAIL="echo #" export MAILEXEC="mail -s" export HASHHTML="--" export HASHHTMLOS="echo #" export ENDHASHHTMLOS="" export HASHNONHTML="" fi ;; *) export SENDMAIL="echo #" export HASHHTML="--" export HASHHTMLOS="echo #" export ENDHASHHTMLOS="" export HASHNONHTML="" export MAILEXEC="mail -s" ;; esac # SQLPLUS HTML SETTINGS: #export HTMLTITLE="SET MARKUP HTML ON SPOOL ON HEAD ' ' TABLE \"border='3' align='left'\" ENTMAP OFF" #export HTMLTABLE="SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE \"border='2' align='left'\" ENTMAP OFF" echo "Checking CPU Utilization ..." # Report CPU Utilization if reach >= CPUTHRESHOLD: OS_TYPE=`uname -s` CPUUTLLOG=/tmp/CPULOG_DBA_BUNDLE.log # Getting CPU utilization in last 5 seconds: case `uname` in Linux ) CPU_REPORT_SECTIONS=`iostat -c 1 5 | sed -e 's/,/./g' | tr -s ' ' ';' | sed '/^$/d' | tail -1 | grep ';' -o | wc -l` CPU_COUNT=`cat /proc/cpuinfo|grep processor|wc -l` if [ ${CPU_REPORT_SECTIONS} -ge 6 ]; then CPU_IDLE=`iostat -c 1 5 | sed -e 's/,/./g' | tr -s ' ' ';' | sed '/^$/d' | tail -1| cut -d ";" -f 7` else CPU_IDLE=`iostat -c 1 5 | sed -e 's/,/./g' | tr -s ' ' ';' | sed '/^$/d' | tail -1| cut -d ";" -f 6` fi ;; AIX ) CPU_IDLE=`iostat -t $INTERVAL_SEC $NUM_REPORT | sed -e 's/,/./g'|tr -s ' ' ';' | tail -1 | cut -d ";" -f 6` CPU_COUNT=`lsdev -C|grep Process|wc -l` ;; SunOS ) CPU_IDLE=`iostat -c $INTERVAL_SEC $NUM_REPORT | tail -1 | awk '{ print $4 }'` CPU_COUNT=`psrinfo -v|grep "Status of processor"|wc -l` ;; HP-UX) SAR="/usr/bin/sar" CPU_COUNT=`lsdev -C|grep Process|wc -l` if [ ! -x $SAR ]; then echo "sar command is not supported on your environment | CPU Check ignored"; CPU_IDLE=99 else CPU_IDLE=`/usr/bin/sar 1 5 | grep Average | awk '{ print $5 }'` fi ;; *) echo "uname command is not supported on your environment | CPU Check ignored"; CPU_IDLE=99 ;; esac # Getting Utilized CPU (100-%IDLE): #CPU_UTL_FLOAT=`echo "scale=2; 100-($CPU_IDLE)"|bc` CPU_UTL_FLOAT=`awk "BEGIN {print 100-($CPU_IDLE)}"` # Convert the average from float number to integer: CPU_UTL=${CPU_UTL_FLOAT%.*} echo "CPU utilizations is: $CPU_UTL" if [ -z ${CPU_UTL} ] then CPU_UTL=1 fi # Compare the current CPU utilization with the Threshold: if [ ${CPU_UTL} -ge ${CPUTHRESHOLD} ] then export COLUMNS=${OSLINESIZE} #Increase the COLUMNS width to display the full output [Default is 167] echo "*******" > ${MPSTATLOG} echo "mpstat" >> ${MPSTATLOG} echo "*******" >> ${MPSTATLOG} mpstat 1 5|tail -7 >> ${MPSTATLOG} echo "" > ${VMSTATLOG} echo "******" >> ${VMSTATLOG} echo "vmstat" >> ${VMSTATLOG} echo "******" >> ${VMSTATLOG} #echo "[If_the_runqueue_number_in_the_(r)_column_exceeds_the_number_of_CPUs_[${CPU_COUNT}]_this_indicates_a_CPU_bottleneck_on_the_system]." >> ${VMSTATLOG} vmstat 2 5 >> ${VMSTATLOG} echo "" > ${TOPLOG} echo "****************" >> ${TOPLOG} echo "Top10Processes" >> ${TOPLOG} echo "****************" >> ${TOPLOG} top -c -b -n 1|head -17|tail -11 >> ${TOPLOG} echo "" > ${UPTIMELOG} echo "**********" >> ${UPTIMELOG} echo "Load_Avg" >> ${UPTIMELOG} echo "**********" >> ${UPTIMELOG} uptime >> ${UPTIMELOG} echo "" >> ${UPTIMELOG} unset COLUMNS #Set COLUMNS width back to the default value #ps -eo pcpu,pid,user,args | sort -k 1 -r | head -11 >> ${CPULOG} cat ${MPSTATLOG} > ${LOGFILE} cat ${VMSTATLOG} >> ${LOGFILE} cat ${TOPLOG} >> ${LOGFILE} cat ${UPTIMELOG} >> ${LOGFILE} # Convert OS commands output into HTML format: export FONTSIZE=4 export FONT=Arial export FONTCOLOR=BLUE #${HASHHTMLOS} awk 'BEGIN { print ""} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${MPSTATLOG} > ${CPULOGCONV} ${ENDHASHHTMLOS} ${HASHHTMLOS} awk 'BEGIN { print ""} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${MPSTATLOG} > ${CPULOGCONV} ${ENDHASHHTMLOS} ${HASHHTMLOS} awk 'BEGIN { print ""} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${VMSTATLOG} >> ${CPULOGCONV} ${ENDHASHHTMLOS} ${HASHHTMLOS} awk 'BEGIN { print ""} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${TOPLOG} >> ${CPULOGCONV} ${ENDHASHHTMLOS} ${HASHHTMLOS} awk 'BEGIN { print ""} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${UPTIMELOG} >> ${CPULOGCONV} ${ENDHASHHTMLOS} #${HASHHTMLOS} cat /dev/null > ${CPULOGHTML} ${ENDHASHHTMLOS} ${HASHHTMLOS} cp ${CPULOGCONV} ${LOGFILE} # Check ACTIVE SESSIONS on DB side: echo "[CPU Utilization Crossed The Threshold [${CPU_UTL}%]. Sending Email Alert ...]" for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID # Getting ORACLE_HOME: # ################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Check Long Running Transactions if CPUDIGMORE=Y: case ${CPUDIGMORE} in y|Y|yes|YES|Yes|ON|On|on) DBCPUDIGMORE=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize ${SQLLINESIZE} -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF SPOOL ${CPULOGHTML} APPEND prompt ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT SESSIONS STATUS: [Local Instance | ${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT *************** ${HASHNONHTML} PROMPT SESSIONS STATUS: [Local Instance | ${ORACLE_SID}] ${HASHNONHTML} PROMPT *************** set pages 0 select 'ACTIVE: '||count(*) from v\$session where USERNAME is not null and status='ACTIVE'; select 'INACTIVE: '||count(*) from v\$session where USERNAME is not null and status='INACTIVE'; select 'BACKGROUND: '||count(*) from v\$session where USERNAME is null; select 'ALL: '||count(*) from v\$session; ${HASHNONHTML} PROMPT ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} SET PAGES 0 ${HASHHTML} PROMPT

${HASHHTML} PROMPT ACTIVE SESSIONS ON INSTANCE: [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} SET PAGES 1000 --${HASHHTML} PROMPT ${HASHNONHTML} PROMPT *************************** ${HASHNONHTML} PROMPT ACTIVE SESSIONS ON INSTANCE: [${ORACLE_SID}] ${HASHNONHTML} PROMPT *************************** set feedback off linesize ${SQLLINESIZE} pages 1000 col event for a24 col "STATUS|WAIT_STATE|TIME_WAITED" for a31 col "USER|OSID|SID,SER|MACHN|MODULE" for a65 col "ST|WA_ST|WAITD|ACT_SINC|LOGIN" for a44 col "SQLID | FULL_SQL_TEXT" for a75 col "CURR_SQLID" for a35 col "I|BLKD_BY" for a9 select substr(s.USERNAME||'| '||p.spid||'|'||s.sid||','||s.serial#||' |'||substr(s.MACHINE,1,22)||'|'||substr(s.MODULE,1,18),1,65)"USER|OSID|SID,SER|MACHN|MODULE" ,substr(s.status||'|'||w.state||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||to_char(LOGON_TIME,'ddMon'),1,44) "ST|WA_ST|WAITD|ACT_SINC|LOGIN" ,substr(w.event,1,24) "EVENT" --,substr(w.event,1,30)"EVENT",s.SQL_ID ||' | '|| Q.SQL_FULLTEXT "SQLID | FULL_SQL_TEXT" ,s.SQL_ID "CURRENT SQLID" ,s.FINAL_BLOCKING_INSTANCE||'|'||s.FINAL_BLOCKING_SESSION "I|BLKD_BY" from v\$session s, v\$session_wait w, v\$process p where s.USERNAME is not null and s.sid=w.sid and p.addr = s.paddr and s.STATUS='ACTIVE' and w.EVENT NOT IN ('SQL*Net message from client','class slave wait','Streams AQ: waiting for messages in the queue','Streams capture: waiting for archive log' ,'Streams AQ: waiting for time management or cleanup tasks','PL/SQL lock timer','rdbms ipc message') order by "I|BLKD_BY" desc,"CURRENT SQLID",w.event,"USER|OSID|SID,SER|MACHN|MODULE","ST|WA_ST|WAITD|ACT_SINC|LOGIN" desc; --${HASHHTML} PROMPT
${HASHNONHTML} PROMPT ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Long Running Operations On Database: [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT *********************************** ${HASHNONHTML} PROMPT Long Running Operations On Instance: [${ORACLE_SID}] ${HASHNONHTML} PROMPT *********************************** set linesize ${SQLLINESIZE} pages 1000 col OPERATION for a21 col "%DONE" for 999.999 col "STARTED|MIN_ELAPSED|REMAIN" for a30 col MESSAGE for a80 col "USERNAME| SID,SERIAL#" for a26 select USERNAME||'| '||SID||','||SERIAL# "USERNAME| SID,SERIAL#",SQL_ID --,OPNAME OPERATION ,round(SOFAR/TOTALWORK*100,2) "%DONE" ,to_char(START_TIME,'DD-Mon HH24:MI')||'| '||trunc(ELAPSED_SECONDS/60)||'|'||trunc(TIME_REMAINING/60) "STARTED|MIN_ELAPSED|REMAIN" ,MESSAGE from v\$session_longops where SOFAR/TOTALWORK*100 <>'100' and TOTALWORK <> '0' order by "STARTED|MIN_ELAPSED|REMAIN" desc, "USERNAME| SID,SERIAL#"; PROMPT ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Sessions Active Since More Than 1 Hour On Database: [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ************************************************** ${HASHNONHTML} PROMPT Sessions Active Since More Than 1 Hour On Instance: [${ORACLE_SID}] ${HASHNONHTML} PROMPT ************************************************** set lines ${SQLLINESIZE} col module for a30 col DURATION_HOURS for 99999.9 col STARTED_AT for a13 col "USERNAME| SID,SERIAL#" for a30 col "SQL_ID | SQL_TEXT" for a120 select username||'| '||sid ||','|| serial# "USERNAME| SID,SERIAL#",substr(MODULE,1,30) "MODULE", to_char(sysdate-last_call_et/24/60/60,'DD-MON HH24:MI') STARTED_AT, last_call_et/60/60 "DURATION_HOURS" --,SQL_ID ||' | '|| (select SQL_FULLTEXT from v\$sql where address=sql_address) "SQL_ID | SQL_TEXT" ,SQL_ID from v\$session where username is not null and module is not null -- 1 is the number of hours and last_call_et > 60*60*1 and status = 'ACTIVE'; PROMPT ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT RUNNING JOBS On Database: [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ************************ ${HASHNONHTML} PROMPT RUNNING JOBS On Instance: [${ORACLE_SID}] ${HASHNONHTML} PROMPT ************************ col INS for 999 col "JOB_NAME|OWNER|SPID|SID" for a55 col ELAPSED_TIME for a17 col CPU_USED for a17 col "WAIT_SEC" for 9999999999 col WAIT_CLASS for a15 col "BLKD_BY" for 9999999 col "WAITED|WCLASS|EVENT" for a45 select j.RUNNING_INSTANCE INS,j.JOB_NAME ||' | '|| j.OWNER||' |'||SLAVE_OS_PROCESS_ID||'|'||j.SESSION_ID"JOB_NAME|OWNER|SPID|SID" ,s.FINAL_BLOCKING_SESSION "BLKD_BY",ELAPSED_TIME,CPU_USED ,substr(s.SECONDS_IN_WAIT||'|'||s.WAIT_CLASS||'|'||s.EVENT,1,45) "WAITED|WCLASS|EVENT",S.SQL_ID from dba_scheduler_running_jobs j, gv\$session s where j.RUNNING_INSTANCE=S.INST_ID(+) and j.SESSION_ID=S.SID(+) order by INS,"JOB_NAME|OWNER|SPID|SID",ELAPSED_TIME; SPOOL OFF EOF ) BACKUPJOBCOUNTRAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF SPOOL ${CPULOGHTML} APPEND prompt ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Running Backups: [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt *************** ${HASHNONHTML} Prompt Running Backups: [${ORACLE_SID}] ${HASHNONHTML} prompt *************** set feedback off linesize ${SQLLINESIZE} pages 1000 col START_TIME for a15 col END_TIME for a15 col TIME_TAKEN_DISPLAY for a10 col INPUT_BYTES_DISPLAY heading "DATA SIZE" for a10 col OUTPUT_BYTES_DISPLAY heading "Backup Size" for a11 col OUTPUT_BYTES_PER_SEC_DISPLAY heading "Speed/s" for a10 col output_device_type heading "Device_TYPE" for a11 SELECT to_char (start_time,'DD-MON-YY HH24:MI') START_TIME, to_char(end_time,'DD-MON-YY HH24:MI') END_TIME, time_taken_display, status, input_type, output_device_type,input_bytes_display, output_bytes_display, output_bytes_per_sec_display,COMPRESSION_RATIO COMPRESS_RATIO FROM v\$rman_backup_job_details WHERE status like 'RUNNING%'; SPOOL OFF exit; EOF ) fi echo "" ;; esac done echo "CPU utilization has hit the threshold. Reporting the problem." cat ${CPULOGHTML} >> ${LOGFILE} export SRV_NAME="`uname -n`" export MSGSUBJECT="ALERT: CPU Utilization on Server [${SRV_NAME}] has reached [${CPU_UTL}%]" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} fi rm -f ${CPUUTLLOG} rm -f ${CPULOG} echo "CPU CHECK Completed." # ######################### # Getting ORACLE_SID: # ######################### # Exit with sending Alert mail if No DBs are running: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) if [ ${INS_COUNT} -eq 0 ] then echo "[Reported By ${SCRIPT_NAME} Script]" > /tmp/oracle_processes_DBA_BUNDLE.log echo " " >> /tmp/oracle_processes_DBA_BUNDLE.log echo "Current running INSTANCES on server [${SRV_NAME}]:" >> /tmp/oracle_processes_DBA_BUNDLE.log echo "***************************************************" >> /tmp/oracle_processes_DBA_BUNDLE.log ps -ef|grep -v grep|grep pmon >> /tmp/oracle_processes_DBA_BUNDLE.log echo " " >> /tmp/oracle_processes_DBA_BUNDLE.log echo "Current running LISTENERS on server [${SRV_NAME}]:" >> /tmp/oracle_processes_DBA_BUNDLE.log echo "***************************************************" >> /tmp/oracle_processes_DBA_BUNDLE.log ps -ef|grep -v grep|grep tnslsnr >> /tmp/oracle_processes_DBA_BUNDLE.log mail -s "ALARM: No Databases Are Running on Server: ${SRV_NAME} !!!" ${MAIL_LIST} < /tmp/oracle_processes_DBA_BUNDLE.log rm -f /tmp/oracle_processes_DBA_BUNDLE.log exit fi # Avoid Monitoring Running Services if more than one DB instance is running: if [ ${INS_COUNT} -gt 1 ] then export SERVICEMON="" fi # ######################### # Setting ORACLE_SID: # ######################### for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID echo "" echo "[Checking ${ORACLE_SID} Database ...]" # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" mail -s "dbalarm script on Server [${SRV_NAME}] failed to locate ORACLE_HOME for SID [${ORACLE_SID}], Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory" ${MAIL_LIST} < /dev/null exit fi # ############################# # Getting hostname in lowercase: # ############################# HOSTNAMELOWER=$( echo "`hostname --short`"| tr '[A-Z]' '[a-z]' ) export HOSTNAMELOWER # ######################## # Getting GRID_HOME: # ######################## CHECK_OCSSD=`ps -ef|grep 'ocssd.bin'|grep -v grep|wc -l` CHECK_CRSD=`ps -ef|grep 'crsd.bin'|grep -v grep|wc -l` if [ ${CHECK_OCSSD} -gt 0 ] then GRID_HOME=`ps -ef|grep 'ocssd.bin'|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v sed|grep -v "//g"|tail -1` export GRID_HOME if [ ! -d ${GRID_HOME} ] then ASM_INSTANCE_NAME=`ps -ef|grep pmon|grep -v grep|grep asm_pmon_|awk '{print $NF}'|sed -e 's/asm_pmon_//g'|grep -v sed|grep -v "s///g"|tail -1` GRID_HOME=`dbhome ${ASM_INSTANCE_NAME}` export GRID_HOME fi # ######################## # Getting GRID_BASE: # ######################## # Locating GRID_BASE: GRID_BASE=`cat ${GRID_HOME}/crs/install/crsconfig_params|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/crs/utl/appvipcfg|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi fi # ######################### # Variables: # ######################### export PATH=${PATH}:${ORACLE_HOME}/bin export LOG_DIR=${USR_ORA_HOME}/BUNDLE_Logs mkdir -p ${LOG_DIR} chown -R ${ORA_USER} ${LOG_DIR} chmod -R go-rwx ${LOG_DIR} if [ ! -d ${LOG_DIR} ] then mkdir -p /tmp/BUNDLE_Logs export LOG_DIR=/tmp/BUNDLE_Logs chown -R ${ORA_USER} ${LOG_DIR} chmod -R go-rwx ${LOG_DIR} fi touch ${LOG_DIR}/dbalarm.part.log export LOGFILE=${LOG_DIR}/dbalarm.part.log # ######################### # HTML Preparation: # ######################### case ${HTMLENABLE} in y|Y|yes|YES|Yes|ON|On|on) if [ -x /usr/sbin/sendmail ] then export SENDMAIL="/usr/sbin/sendmail -t" export MAILEXEC="echo #" export HASHHTML="" export HASHNONHTML="--" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) export SENDMAILARGS else export SENDMAIL="echo #" export MAILEXEC="mail -s" export HASHHTML="--" export HASHNONHTML="" fi ;; *) export SENDMAIL="echo #" export HASHHTML="--" export HASHNONHTML="" export MAILEXEC="mail -s" ;; esac #export HTMLTITLE="SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE \"border='3' align='left'\" ENTMAP OFF" #export HTMLTABLE="SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE \"border='2' align='left'\" ENTMAP OFF" # ########################## # Neutralize login.sql file: [Bug Fix] # ########################## # Existance of login.sql file under Oracle user Linux home directory eliminates many functions during the execution of this script via crontab: if [ -f ${USR_ORA_HOME}/login.sql ] then echo "login.sql file found and will be neutralized." mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################## # Getting ORACLE_BASE: # ######################## # Get ORACLE_BASE from user's profile if it EMPTY: if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`cat ${ORACLE_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export ORACLE_BASE fi if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`grep -h 'ORACLE_BASE=\/' ${USR_ORA_HOME}/.bash* ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi # ######################### # Getting DB_NAME: # ######################### DB_NAME_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <= the defined threshold then send an email alert: INTEG='^[0-9]+$' # Verify that FRAPRCUSED value is a valid number: if [[ ${FRAPRCUSED} =~ ${INTEG} ]] then echo "Checking FRA For [${ORACLE_SID}] ..." if [ ${FRAPRCUSED} -ge ${FRATHRESHOLD} ] then FRA_RPT=${LOG_DIR}/FRA_REPORT.log FRACHK2=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} ${HASHHTML} set linesize 300 ${HASHNONHTML} col name for a100 ${HASHNONHTML} col TOTAL_MB for 99999999999999999 ${HASHNONHTML} col FREE_MB for 99999999999999999 -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF SPOOL ${FRA_RPT} ${HASHHTML} set pages 0 ${HASHHTML} select ''||'Reported By ${SCRIPT_NAME} Script'||'' from dual; ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT [Reported By ${SCRIPT_NAME} Script] ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT [FLASH RECOVERY AREA Utilization] ${HASHNONHTML} PROMPT ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FLASH RECOVERY AREA Utilization ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 col NAME for a30 SELECT NAME,SPACE_LIMIT/1024/1024 AS TOTAL_MB,(SPACE_LIMIT - SPACE_USED + SPACE_RECLAIMABLE)/1024/1024 AS FREE_MB, ROUND((SPACE_USED - SPACE_RECLAIMABLE)/SPACE_LIMIT * 100, 1) AS "%FULL" FROM V\$RECOVERY_FILE_DEST; ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT [FRA COMPONENTS] ${HASHNONHTML} PROMPT ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FRA COMPONENTS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 select * from v\$flash_recovery_area_usage; ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT [Exist Restore Points: ] ${HASHNONHTML} PROMPT ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Exist Restore Points ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 col SCN for 999999999999999999 col time for a35 col RESTORE_POINT_TIME for a35 col name for a40 select NAME,SCN,TIME,STORAGE_SIZE/1024/1024 STORAGE_SIZE_MB from v\$restore_point; spool off exit; EOF ) echo "FRA has reached ${FRAPRCUSED}%. Reporting the problem." cat ${FRA_RPT} > ${LOGFILE} export MSGSUBJECT="ALERT: FRA has reached ${FRAPRCUSED}% on database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${FRA_RPT} echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} fi fi rm -f ${FRAFULL} rm -f ${FRA_RPT} fi # ################################ # Check ASM Diskgroup Utilization: # ################################ echo "Checking ASM Diskgroup Utilization ..." VAL314=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${ASMFULL} echo " " >> ${ASMFULL} echo "ASM_DISK_GROUP %USED" >> ${ASMFULL} echo "---------------------- --------------" >> ${ASMFULL} echo "${ASMDGNAME} ${ASMPRCUSED}%" >> ${ASMFULL} # Convert ASMPRCUSED from float number to integer: ASMPRCUSED=${ASMPRCUSED%.*} if [ -z ${ASMPRCUSED} ] then ASMPRCUSED=1 fi # If ASM %USED >= the defined threshold send an email for each DISKGROUP: if [ ${ASMPRCUSED} -ge ${ASMTHRESHOLD} ] then ASM_RPT=${LOG_DIR}/ASM_REPORT.log ASMCHK2=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} pages 1000 col name for a35 -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF SPOOL ${ASM_RPT} ${HASHHTML} set pages 0 ${HASHHTML} select ''||'Reported By ${SCRIPT_NAME} Script'||'' from dual; ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT [Reported By ${SCRIPT_NAME} Script] ${HASHNONHTML} PROMPT ${HASHNONHTML} prompt ASM DISK GROUPS: ${HASHNONHTML} PROMPT *************** ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT ASM DISK GROUPS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 select name,total_mb,free_mb,ROUND((1-(free_mb / total_mb))*100, 2) "%FULL" from v\$asm_diskgroup where name='${ASMDGNAME}'; spool off exit; EOF ) echo "ASM DISK GROUP [${ASMDGNAME}] has reached ${ASMPRCUSED}%. Reporting the problem." export MSGSUBJECT="ALERT: ASM DISK GROUP [${ASMDGNAME}] has reached ${ASMPRCUSED}% on database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" cat ${ASM_RPT} > ${LOGFILE} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} fi done rm -f ${ASMFULL} rm -f ${ASM_RPT} fi # ######################### # Tablespaces Size Check: # ######################### echo "Checking TABLESPACES on [${ORACLE_SID}] ..." if [ ${DB_VER} -gt 10 ] then # If The Database Version is 11g Onwards: TBSCHK=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 termout off echo off feedback off col tablespace_name for A25 col y for 999999999 heading 'Total_MB' col z for 999999999 heading 'Used_MB' col bused for 999.99 heading '%Used' spool ${LOG_DIR}/tablespaces_DBA_BUNDLE.log select tablespace_name, (used_space*$blksize)/(1024*1024) Used_MB, (tablespace_size*$blksize)/(1024*1024) Total_MB, used_percent "%Used" from dba_tablespace_usage_metrics; spool off exit; EOF ) else # If The Database Version is 10g Backwards: # Check if AUTOEXTEND OFF (MAXSIZE=0) is set for any of the datafiles divide by ALLOCATED size else divide by MAXSIZE: VAL33=$(${ORACLE_HOME}/bin/sqlplus -S '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_DATA_FILES WHERE MAXBYTES=0; exit; EOF ) VAL44=`echo ${VAL33}| awk '{print $NF}'` case ${VAL44} in "0") CALCPERCENTAGE1="((sbytes - fbytes)*100 / MAXSIZE) bused " ;; *) CALCPERCENTAGE1="round(((sbytes - fbytes) / sbytes) * 100,2) bused " ;; esac VAL55=$(${ORACLE_HOME}/bin/sqlplus -S '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_TEMP_FILES WHERE MAXBYTES=0; exit; EOF ) VAL66=`echo ${VAL55}| awk '{print $NF}'` case ${VAL66} in "0") CALCPERCENTAGE2="((sbytes - fbytes)*100 / MAXSIZE) bused " ;; *) CALCPERCENTAGE2="round(((sbytes - fbytes) / sbytes) * 100,2) bused " ;; esac TBSCHK=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 termout off echo off feedback off col tablespace for A25 col "MAXSIZE MB" format 9999999 col x for 999999999 heading 'Allocated MB' col y for 999999999 heading 'Free MB' col z for 999999999 heading 'Used MB' col bused for 999.99 heading '%Used' --bre on report spool ${LOG_DIR}/tablespaces_DBA_BUNDLE.log select a.tablespace_name tablespace,bb.MAXSIZE/1024/1024 "MAXSIZE MB",sbytes/1024/1024 x,fbytes/1024/1024 y, (sbytes - fbytes)/1024/1024 z, $CALCPERCENTAGE1 --round(((sbytes - fbytes) / sbytes) * 100,2) bused --((sbytes - fbytes)*100 / MAXSIZE) bused from (select tablespace_name,sum(bytes) sbytes from dba_data_files group by tablespace_name ) a, (select tablespace_name,sum(bytes) fbytes,count(*) ext from dba_free_space group by tablespace_name) b, (select tablespace_name,sum(MAXBYTES) MAXSIZE from dba_data_files group by tablespace_name) bb --where a.tablespace_name in (select tablespace_name from dba_tablespaces) where a.tablespace_name = b.tablespace_name (+) and a.tablespace_name = bb.tablespace_name and round(((sbytes - fbytes) / sbytes) * 100,2) > 0 UNION ALL select c.tablespace_name tablespace,dd.MAXSIZE/1024/1024 MAXSIZE_GB,sbytes/1024/1024 x,fbytes/1024/1024 y, (sbytes - fbytes)/1024/1024 obytes, $CALCPERCENTAGE2 from (select tablespace_name,sum(bytes) sbytes from dba_temp_files group by tablespace_name having tablespace_name in (select tablespace_name from dba_tablespaces)) c, (select tablespace_name,sum(bytes_free) fbytes,count(*) ext from v\$temp_space_header group by tablespace_name) d, (select tablespace_name,sum(MAXBYTES) MAXSIZE from dba_temp_files group by tablespace_name) dd --where c.tablespace_name in (select tablespace_name from dba_tablespaces) where c.tablespace_name = d.tablespace_name (+) and c.tablespace_name = dd.tablespace_name order by tablespace; select tablespace_name,null,null,null,null,null||'100.00' from dba_data_files minus select tablespace_name,null,null,null,null,null||'100.00' from dba_free_space; spool off exit; EOF ) fi TBSLOG=${LOG_DIR}/tablespaces_DBA_BUNDLE.log TBSFULL=${LOG_DIR}/full_tbs.log #cat ${TBSLOG}|awk '{ print $1" "$NF }'| while read OUTPUT2 cat ${TBSLOG}|egrep -v ${EXL_TBS} |awk '{ print $1" "$NF }'| while read OUTPUT2 do PRCUSED=`echo ${OUTPUT2}|awk '{print $NF}'` TBSNAME=`echo ${OUTPUT2}|awk '{print $1}'` echo "[Reported By ${SCRIPT_NAME} Script]" > ${TBSFULL} echo " " >> ${TBSFULL} echo "Tablespace_name %USED" >> ${TBSFULL} echo "---------------------- --------------" >> ${TBSFULL} # echo ${OUTPUT2}|awk '{print $1" "$NF}' >> ${TBSFULL} echo "${TBSNAME} ${PRCUSED}%" >> ${TBSFULL} # Convert PRCUSED from float number to integer: PRCUSED=${PRCUSED%.*} if [ -z ${PRCUSED} ] then PRCUSED=1 fi # If the tablespace %USED >= the defined threshold send an email for each tablespace: if [ ${PRCUSED} -ge ${TBSTHRESHOLD} ] then echo "TABLESPACE [${TBSNAME}] reached ${PRCUSED}%. Reporting the problem." mail -s "ALERT: TABLESPACE [${TBSNAME}] reached ${PRCUSED}% on database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" ${MAIL_LIST} < ${TBSFULL} fi done rm -f ${LOG_DIR}/tablespaces_DBA_BUNDLE.log rm -f ${LOG_DIR}/full_tbs.log # ############################################ # Checking Monitored Services: # ############################################ #case ${DB_NAME} in #ORCL) if [ ! -x ${SERVICEMON} ] then echo "Checking Monitored Services on [${ORACLE_SID}] ..." VAL_SRVMON_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off; prompt select count(*) from V\$ACTIVE_SERVICES where lower(NAME) in (${SERVICEMON}) or upper(NAME) in (${SERVICEMON}); exit; EOF ) ONLINE_SERVICES_COUNT=`echo ${VAL_SRVMON_RAW}| awk '{print $NF}'` #echo "Number of ONLINE Services is: $ONLINE_SERVICES_COUNT" MONITORED_SERVICES_COUNT=`echo "${SERVICEMON}" | awk -F "," '{print NF}'` #echo "Number of MONITORED Services is: $MONITORED_SERVICES_COUNT" DOWN_SERVICES_COUNT=`expr ${MONITORED_SERVICES_COUNT} - ${ONLINE_SERVICES_COUNT}` #echo "Number of OFFLINE Services is: $DOWN_SERVICES_COUNT" if [ ${DOWN_SERVICES_COUNT} -gt 0 ] then VAL_SRVNAME_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off; prompt select name from dba_services minus select name from v\$ACTIVE_SERVICES; exit; EOF ) OFFLINE_SRVNAME=`echo ${VAL_SRVNAME_RAW}| awk '{print $NF}'` VAL_SRVMON_EMAIL=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize 160 pages 1000 echo off feedback off -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF spool ${LOG_DIR}/current_running_services.log ${HASHHTML} set pages 0 ${HASHHTML} select ''||'Reported By ${SCRIPT_NAME} Script'||'' from dual; ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT [Reported By ${SCRIPT_NAME} Script] ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT SERVICE [${OFFLINE_SRVNAME}] REPORTED OFFLINE. ${HASHNONHTML} PROMPT ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT SERVICE [${OFFLINE_SRVNAME}] REPORTED OFFLINE ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 select name OFFLINE_SERVICES from dba_services minus select name from v\$active_services; ${HASHHTML} PROMPT
select INST_ID,NAME ONLINE_SERVICE_NAME from GV\$ACTIVE_SERVICES where NAME not in ('SYS\$BACKGROUND','SYS\$USERS') order by ONLINE_SERVICE_NAME; spool off exit; EOF ) echo "Service Down detected [${OFFLINE_SRVNAME}]. Reporting the problem." export MSGSUBJECT="ALERT: SERVICE [${OFFLINE_SRVNAME}] Detected OFFLINE on Instance [${ORACLE_SID}] on Server [${SRV_NAME}]" cat ${LOG_DIR}/current_running_services.log > ${LOGFILE} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOG_DIR}/current_running_services.log echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} rm -f ${LOG_DIR}/current_running_services.log fi fi #;; #esac # ###################################### # Checking RMAN In-Complete Backup Jobs: # ###################################### case ${CHKRMANBKP} in y|Y|yes|YES|Yes|ON|On|on) echo "Checking FAILED RMAN Backup Jobs In The Last ${LAST_MIN_BKP_CHK} Minutes ..." RMANBKPCNTRAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < sysdate - (${LAST_MIN_BKP_CHK}/1440) and status in ('FAILED','COMPLETED WITH ERRORS'); exit; EOF ) RMANBKPCNT=`echo ${RMANBKPCNTRAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` if [ ${RMANBKPCNT} -gt 0 ] then echo "FAILED RMAN Backup Jobs Detected." RMANBKPFAILLOG=${LOG_DIR}/RMANBKPFAILREPORT.log RMANBKPCHK=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 1000 termout off echo off feedback off linesize ${SQLLINESIZE} -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF spool ${RMANBKPFAILLOG} ${HASHNONHTML} PROMPT [FAILED BACKUP REPORT IN THE LAST ${LAST_MIN_BKP_CHK} Minutes] ${HASHNONHTML} PROMPT ${HASHHTML} set pages 0 ${HASHHTML} select ''||'Reported By ${SCRIPT_NAME} Script'||'' from dual; ${HASHHTML} set pages 1000 ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FAILED BACKUP REPORT IN THE LAST ${LAST_MIN_BKP_CHK} Minutes ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 col START_TIME for a15 col END_TIME for a15 col TIME_TAKEN_DISPLAY for a10 col INPUT_BYTES_DISPLAY heading "DATA SIZE" for a10 col OUTPUT_BYTES_DISPLAY heading "Backup Size" for a11 col OUTPUT_BYTES_PER_SEC_DISPLAY heading "Speed/s" for a10 col output_device_type heading "Device_TYPE" for a11 SELECT to_char (start_time,'DD-MON-YY HH24:MI') START_TIME, to_char(end_time,'DD-MON-YY HH24:MI') END_TIME, time_taken_display, status, input_type, output_device_type,input_bytes_display, output_bytes_display, output_bytes_per_sec_display,COMPRESSION_RATIO COMPRESS_RATIO FROM v\$rman_backup_job_details WHERE end_time > sysdate - (${LAST_MIN_BKP_CHK}/1440) and status in ('FAILED','COMPLETED WITH ERRORS'); spool off exit; EOF ) echo "FAILED RMAN Backup Detected. Reporting the problem." cat ${RMANBKPFAILLOG} > ${LOGFILE} export MSGSUBJECT="Info: FAILED RMAN Backup Detected on Database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${RMANBKPFAILLOG} echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} fi esac # ############################################ # Checking BLOCKING SESSIONS ON THE DATABASE: # ############################################ echo "Checking Blocking Sessions on [${ORACLE_SID}] With Wait > 1min..." if [ ${DB_VER} -gt 10 ] then export WAIT_COL="s2.WAIT_TIME_MICRO" export WAIT_DISPLAY="round(${WAIT_COL}/1000000/60,0)" else export WAIT_COL="s2.SECONDS_IN_WAIT" export WAIT_DISPLAY="round(${WAIT_COL}/60)" fi VAL77=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off; select /*+RULE*/ count(*) from gv\$LOCK l1, gv\$SESSION s1, gv\$LOCK l2, gv\$SESSION s2 where s1.sid=l1.sid and s2.sid=l2.sid and l1.BLOCK=1 and l2.request > 0 and l1.id1=l2.id1 and l2.id2=l2.id2 and ${WAIT_DISPLAY} > ${WAIT_FOR_LOCK_THRES}; exit; EOF ) VAL88=`echo ${VAL77}| awk '{print $NF}'` if [ ${VAL88} -ge ${BLOCKTHRESHOLD} ] then echo "BLOCKING SESSIONS detected. Reporting the problem." VAL99=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} pages 1000 echo off feedback off col BLOCKING_STATUS for a90 -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF spool ${LOG_DIR}/blocking_sessions.log ${HASHHTML} set pages 0 ${HASHHTML} select ''||'Reported By ${SCRIPT_NAME} Script'||'' from dual; ${HASHHTML} set pages 1000 ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT MASTER BLOCKING SESSIONS ON DATABASE [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ************************************ ${HASHNONHTML} PROMPT MASTER BLOCKING SESSIONS ON DATABASE: [${ORACLE_SID}] ${HASHNONHTML} PROMPT ************************************ set feedback off linesize ${SQLLINESIZE} pages 1000 col "I|OS/DB USER|SID,SER|MACHN|MOD" for a75 col "PREV|CURRENT_SQL|REMAIN_SEC" for a30 col "ST|WAITD|ACT_SINC|LOGIN" for a34 col event for a24 select /*+RULE*/ substr(s.INST_ID||'|'||s.OSUSER||'/'||s.USERNAME||'| '||s.sid||','||s.serial#||' |'||substr(s.MACHINE,1,22)||'|'||substr(s.MODULE,1,18),1,75)"I|OS/DB USER|SID,SER|MACHN|MOD" ,substr(s.status||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||to_char(LOGON_TIME,'ddMon HH24:MI'),1,34) "ST|WAITD|ACT_SINC|LOGIN" ,substr(w.event,1,24) "EVENT" ,s.PREV_SQL_ID||'|'||s.SQL_ID||'|'||round(w.TIME_REMAINING_MICRO/1000000) "PREV|CURRENT_SQL|REMAIN_SEC" from gv\$session s, gv\$session_wait w where s.sid in (select distinct FINAL_BLOCKING_SESSION from gv\$session where FINAL_BLOCKING_SESSION is not null) and s.USERNAME is not null and s.sid=w.sid and s.FINAL_BLOCKING_SESSION is null / col "KILL MASTER BLOCKING SESSION" for a75 select /*+RULE*/ 'ALTER SYSTEM DISCONNECT SESSION '''||s.sid||','||s.serial#||''' IMMEDIATE;' "KILL MASTER BLOCKING SESSION" from gv\$session s where s.sid in (select distinct FINAL_BLOCKING_SESSION from gv\$session where FINAL_BLOCKING_SESSION is not null) and s.USERNAME is not null and s.FINAL_BLOCKING_SESSION is null / ${HASHNONHTML} prompt ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT List of BLOCKED SESSIONS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} prompt ******************************* ${HASHNONHTML} prompt [List of Victim BLOCKED SESSIONS] ${HASHNONHTML} prompt ******************************* set linesize ${SQLLINESIZE} pages 1000 echo off feedback off col module for a27 col event for a24 col MACHINE for a27 col "WA_ST|WAITD|ACT_SINC|LOG_T" for a38 col "INST|USER|SID,SERIAL#" for a30 col "INS|USER|SID,SER|MACHIN|MODUL" for a65 col "PREV|CURR SQLID" for a27 col "I|BLKD_BY" for a12 col "${WAIT_DISPLAY}" for 99999999.9 select /*+RULE*/ substr(s.INST_ID||'|'||s.USERNAME||'| '||s.sid||','||s.serial#||' |'||substr(s.MACHINE,1,22)||'|'||substr(s.MODULE,1,18),1,65)"INS|USER|SID,SER|MACHIN|MODUL" ,substr(w.state||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||to_char(LOGON_TIME,'ddMon'),1,38) "WA_ST|WAITD|ACT_SINC|LOG_T" ,substr(w.event,1,24) "EVENT" ,s.FINAL_BLOCKING_INSTANCE||'|'||s.FINAL_BLOCKING_SESSION "I|BLKD_BY" from gv\$session s, gv\$session_wait w where s.USERNAME is not null and s.FINAL_BLOCKING_SESSION is not null and s.sid=w.sid and s.STATUS='ACTIVE' order by "I|BLKD_BY" desc,w.event,"INS|USER|SID,SER|MACHIN|MODUL","WA_ST|WAITD|ACT_SINC|LOG_T" desc; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Blocking Locks On Objects Level ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} prompt **************************** ${HASHNONHTML} Prompt [Blocking Locks On Objects Level] ${HASHNONHTML} prompt **************************** --${HASHNONHTML} PROMPT ${HASHHTML} set linesize ${SQLLINESIZE} pages 1000 echo off feedback off ${HASHNONHTML} set linesize ${SQLLINESIZE} pages 100 echo on feedback on column OS_PID format A15 Heading "OS_PID" column ORACLE_USER format A15 Heading "ORACLE_USER" column LOCK_TYPE format A15 Heading "LOCK_TYPE" column LOCK_HELD format A11 Heading "LOCK_HELD" column LOCK_REQUESTED format A11 Heading "LOCK_REQUESTED" column STATUS format A13 Heading "STATUS" column OWNER format A15 Heading "OWNER" column OBJECT_NAME format A35 Heading "OBJECT_NAME" select /*+RULE*/ l.sid, ORACLE_USERNAME oracle_user, decode(TYPE, 'MR', 'Media Recovery', 'RT', 'Redo Thread', 'UN', 'User Name', 'TX', 'Transaction', 'TM', 'DML', 'UL', 'PL/SQL User Lock', 'DX', 'Distributed Xaction', 'CF', 'Control File', 'IS', 'Instance State', 'FS', 'File Set', 'IR', 'Instance Recovery', 'ST', 'Disk Space Transaction', 'TS', 'Temp Segment', 'IV', 'Library Cache Invalidation', 'LS', 'Log Start or Switch', 'RW', 'Row Wait', 'SQ', 'Sequence Number', 'TE', 'Extend Table', 'TT', 'Temp Table', type) lock_type, decode(LMODE, 0, 'None', 1, 'Null', 2, 'Row-S (SS)', 3, 'Row-X (SX)', 4, 'Share', 5, 'S/Row-X (SSX)', 6, 'Exclusive', lmode) lock_held, decode(REQUEST, 0, 'None', 1, 'Null', 2, 'Row-S (SS)', 3, 'Row-X (SX)', 4, 'Share', 5, 'S/Row-X (SSX)', 6, 'Exclusive', request) lock_requested, decode(BLOCK, 0, 'Not Blocking', 1, 'Blocking', 2, 'Global', block) status, OWNER, OBJECT_NAME from v\$locked_object lo, dba_objects do, v\$lock l where lo.OBJECT_ID = do.OBJECT_ID AND l.SID = lo.SESSION_ID AND l.BLOCK='1'; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Long Running Operations On DATABASE [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} prompt ****************************************** ${HASHNONHTML} Prompt [Long Running Operations On DATABASE $ORACLE_SID] ${HASHNONHTML} prompt ****************************************** set linesize ${SQLLINESIZE} pages 1000 col "USERNAME| SID,SERIAL#" for a40 col MESSAGE for a80 col "%COMPLETE" for 999.999 col "SID|SERIAL#" for a12 col "STARTED|MIN_ELAPSED|REMAIN" for a30 select USERNAME||'| '||SID||','||SERIAL# "USERNAME| SID,SERIAL#",SQL_ID --,OPNAME OPERATION ,round(SOFAR/TOTALWORK*100,2) "%DONE" ,to_char(START_TIME,'DD-Mon HH24:MI')||'| '||trunc(ELAPSED_SECONDS/60)||'|'||trunc(TIME_REMAINING/60) "STARTED|MIN_ELAPSED|REMAIN" ,MESSAGE from v\$session_longops where SOFAR/TOTALWORK*100 <>'100' and TOTALWORK <> '0' order by "STARTED|MIN_ELAPSED|REMAIN" desc, "USERNAME| SID,SERIAL#"; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT LOCKING ANALYSIS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 0 lines 300 ${HASHHTML} col blocking_status for a300 ${HASHNONHTML} set linesize ${SQLLINESIZE} pages 0 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ****************** ${HASHNONHTML} PROMPT [LOCKING ANALYSIS] ${HASHNONHTML} PROMPT ****************** select /*+RULE*/ 'User: '||s1.username || '@' || s1.machine || '(SID=' || s1.sid ||' ) running SQL_ID:'||s1.sql_id||' is blocking User: '|| s2.username || '@' || s2.machine || '(SID=' || s2.sid || ') running SQL_ID:'||s2.sql_id||' For '||${WAIT_DISPLAY}||' Minutes [Inform user '||s1.username||' Or Kill his session using:] ALTER SYSTEM KILL SESSION '''||s1.sid||','||s1.serial#||''' immediate;' AS blocking_status from gv\$LOCK l1, gv\$SESSION s1, gv\$LOCK l2, gv\$SESSION s2 where s1.sid=l1.sid and s2.sid=l2.sid and l1.BLOCK=1 and l2.request > 0 and l1.id1 = l2.id1 and l2.id2 = l2.id2 order by ${WAIT_COL} desc; spool off exit; EOF ) cat ${LOG_DIR}/blocking_sessions.log > ${LOGFILE} export MSGSUBJECT="ALERT: BLOCKING SESSIONS detected on database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOG_DIR}/blocking_sessions.log echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} rm -f ${LOG_DIR}/blocking_sessions.log fi # ######################### # Locating DB ALERTLOG path: # ######################### echo "Locating DB Instance ALERTLOG ..." # First Attempt: DUMP=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" </dev/null|sort|tail -1` fi # If HTML OPTION Enabled: #case ${SENDMAIL} in #'/usr/sbin/sendmail -t') #if [ -f ${ALERTLOG} ] #then #ALERTXML=`echo ${ALERTLOG} |awk '{print $NF}'|sed -e 's/\/trace\/alert.*/\/alert\/log.xml/g'` #echo ALERTXML is: $ALERTXML # if [ -f ${ALERTXML} ] # then # export ALERTLOG=${ALERTXML} # fi #export ALERTLOG #echo ALERTLOG is: $ALERTLOG #fi #;; #esac if [ -f ${ALERTLOG} ] then echo "Checking DB ALERTLOG ..." # Rename the old log generated by the script (if exists): if [ -f ${LOG_DIR}/alert_${ORACLE_SID}_new.log ] then mv ${LOG_DIR}/alert_${ORACLE_SID}_new.log ${LOG_DIR}/alert_${ORACLE_SID}_old.log # Create new log: tail -1000 ${ALERTLOG} > ${LOG_DIR}/alert_${ORACLE_SID}_new.log # Extract new entries by comparing old & new logs: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/diff_${ORACLE_SID}.log echo " " >> ${LOG_DIR}/diff_${ORACLE_SID}.log diff ${LOG_DIR}/alert_${ORACLE_SID}_old.log ${LOG_DIR}/alert_${ORACLE_SID}_new.log |grep ">" | cut -f2 -d'>' >> ${LOG_DIR}/diff_${ORACLE_SID}.log # Search for errors: ERRORS=`cat ${LOG_DIR}/diff_${ORACLE_SID}.log | grep 'ORA-\|TNS-' |egrep -v ${EXL_DB_ALERT_ERR}| tail -1` EXPFLAG=`cat ${LOG_DIR}/diff_${ORACLE_SID}.log | grep 'DM00 ' | tail -1` ALTERSFLAG=`cat ${LOG_DIR}/diff_${ORACLE_SID}.log | grep 'ALTER SYSTEM ' | tail -1` ALTERDFLAG=`cat ${LOG_DIR}/diff_${ORACLE_SID}.log | grep 'Completed: ' | tail -1` STARTUPFLAG=`cat ${LOG_DIR}/diff_${ORACLE_SID}.log | grep 'Starting ORACLE instance' | tail -1` SHUTDOWNFLAG=`cat ${LOG_DIR}/diff_${ORACLE_SID}.log | grep 'Instance shutdown complete' | tail -1` FILE_ATTACH=${LOG_DIR}/diff_${ORACLE_SID}.log else # Create new log: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/alert_${ORACLE_SID}_new.log echo " " >> ${LOG_DIR}/alert_${ORACLE_SID}_new.log tail -1000 ${ALERTLOG} >> ${LOG_DIR}/alert_${ORACLE_SID}_new.log # Search for errors: ERRORS=`cat ${LOG_DIR}/alert_${ORACLE_SID}_new.log | grep 'ORA-\|TNS-' |egrep -v ${EXL_DB_ALERT_ERR}| tail -1` FILE_ATTACH=${LOG_DIR}/alert_${ORACLE_SID}_new.log fi # Send mail in case error exist: case "${ERRORS}" in *ORA-*|*TNS-*) # In case time out errors reported enclose the Network Failure Staticits in the same E-mail: case ${TIMEOUTDIGMORE} in y|Y|yes|YES|Yes|true|TRUE|True|on|ON|On) case "${ERRORS}" in *'timed out'*) case `uname` in Linux ) if [ -x /usr/bin/sar ] then echo "Alertlog TIMEOUT errors reported, Checking OS Network Failure Statistics for the last 15 minutes ..." echo -e "Netowrk Statistics are shown at the bottom of this E-mail\n$(cat ${FILE_ATTACH})" > ${FILE_ATTACH} echo "" >> ${FILE_ATTACH} echo "" >> ${FILE_ATTACH} echo "NIC Statistics in the last 15 minutes:" >> ${FILE_ATTACH} echo "*************************************" >> ${FILE_ATTACH} echo "sar -n EDEV -s `date "+%H:%M:%S" -d "20 min ago"` | grep -Ev lo" >> ${FILE_ATTACH} sar -n EDEV -s `date "+%H:%M:%S" -d "20 min ago"` | grep -Ev lo >> ${FILE_ATTACH} fi esac esac esac case ${TEMPSPACEDIGMORE} in y|Y|yes|YES|Yes|true|TRUE|True|on|ON|On) case "${ERRORS}" in *'ORA-1652'*|*'ORA-01652'*) echo -e "TOP TEMP SPACE CONSUMERS are shown at the bottom of this E-mail\n$(cat ${FILE_ATTACH})" > ${FILE_ATTACH} TOP_TEMP_CONSUMERS=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${LOGFILE} export MSGSUBJECT="ALERT: Instance [${ORACLE_SID}] on Server [${SRV_NAME}] reporting errors: ${ERRORS}" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} #echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} ;; esac case ${PARANOIDMODE} in y|Y|yes|YES|Yes|true|TRUE|True|on|ON|On) case "${EXPFLAG}" in *'DM00'*) cat ${FILE_ATTACH} > ${LOGFILE} export MSGSUBJECT="INFO: EXPORT/IMPORT Operation Initiated on Instance [${ORACLE_SID}] on Server [${SRV_NAME}]" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} #echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} ;; esac case "${ALTERSFLAG}" in *'ALTER SYSTEM'*) cat ${FILE_ATTACH} > ${LOGFILE} export MSGSUBJECT="INFO: ALTER SYSTEM Command Executed Against Instance [${ORACLE_SID}] on Server [${SRV_NAME}]" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} #echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} ;; esac case "${ALTERDFLAG}" in *'Completed:'*) cat ${FILE_ATTACH} > ${LOGFILE} export MSGSUBJECT="INFO: MAJOR DB ACTIVITY Completed on Instance [${ORACLE_SID}] on Server [${SRV_NAME}]" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} #echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} ;; esac case "${STARTUPFLAG}" in *'Starting ORACLE instance'*) cat ${FILE_ATTACH} > ${LOGFILE} export MSGSUBJECT="ALERT: Startup Event of Instance [${ORACLE_SID}] Triggered on Server [${SRV_NAME}]" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} #echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} ;; esac case "${SHUTDOWNFLAG}" in *'Instance shutdown complete'*) cat ${FILE_ATTACH} > ${LOGFILE} export MSGSUBJECT="ALARM: Shutdown Event of Instance [${ORACLE_SID}] Triggered on Server [${SRV_NAME}]" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} #echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} ;; esac ;; esac fi # ##################### # Reporting Offline DBs: # ##################### # Populate ${LOG_DIR}/alldb_DBA_BUNDLE.log from ORATAB: # put all running instances in one variable: ALL_RUNNING_INSTANCES=`ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g"` # Exclude all running instances/DB names from getting checked when reading ORATAB file: grep -v '^\#' ${ORATAB} |egrep -v "${EXL_DB}"|egrep -v "${ALL_RUNNING_INSTANCES}"|grep -v "${DB_NAME_LOWER}:"| grep -v "${DB_NAME_UPPER}:"| grep -v '^$' | grep "^" | cut -f1 -d':' > ${LOG_DIR}/alldb_DBA_BUNDLE.log # Populate ${LOG_DIR}/updb_DBA_BUNDLE.log: echo ${ORACLE_SID} >> ${LOG_DIR}/updb_DBA_BUNDLE.log echo ${DB_NAME} >> ${LOG_DIR}/updb_DBA_BUNDLE.log # End looping for databases: echo "" done # Continue Reporting Offline DBs... case ${CHKOFFLINEDB} in y|Y|yes|YES|Yes|ON|On|on) echo "Checking Offline Databases ..." # Sort the lines alphabetically with removing duplicates: sort ${LOG_DIR}/updb_DBA_BUNDLE.log | uniq -d > ${LOG_DIR}/updb_DBA_BUNDLE.log.sort sort ${LOG_DIR}/alldb_DBA_BUNDLE.log > ${LOG_DIR}/alldb_DBA_BUNDLE.log.sort diff ${LOG_DIR}/alldb_DBA_BUNDLE.log.sort ${LOG_DIR}/updb_DBA_BUNDLE.log.sort > ${LOG_DIR}/diff_DBA_BUNDLE.sort echo "The Following Instances are POSSIBLY Down/Hung on [${SRV_NAME}]:" > ${LOG_DIR}/offdb_DBA_BUNDLE.log echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${LOG_DIR}/offdb_DBA_BUNDLE.log grep "^< " ${LOG_DIR}/diff_DBA_BUNDLE.sort | cut -f2 -d'<' >> ${LOG_DIR}/offdb_DBA_BUNDLE.log echo " " >> ${LOG_DIR}/offdb_DBA_BUNDLE.log echo "If above instances are permanently offline, please add their names to 'EXL_DB' parameter at line# 90 or hash their entries in ${ORATAB} to let the script ignore them in the next run." >> ${LOG_DIR}/offdb_DBA_BUNDLE.log OFFLINE_DBS_NUM=`cat ${LOG_DIR}/offdb_DBA_BUNDLE.log| wc -l` # If OFFLINE_DBS is not null: if [ ${OFFLINE_DBS_NUM} -gt 4 ] then echo "" >> ${LOG_DIR}/offdb_DBA_BUNDLE.log echo "Current Running Instances:" >> ${LOG_DIR}/offdb_DBA_BUNDLE.log echo "************************" >> ${LOG_DIR}/offdb_DBA_BUNDLE.log ps -ef|grep pmon|grep -v grep >> ${LOG_DIR}/offdb_DBA_BUNDLE.log echo "" >> ${LOG_DIR}/offdb_DBA_BUNDLE.log VALX1=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <> ${LOG_DIR}/offdb_DBA_BUNDLE.log echo "Offline Database Detected. Reporting the problem." mail -s "ALARM: Database Inaccessible on Server: [${SRV_NAME}]" ${MAIL_LIST} < ${LOG_DIR}/offdb_DBA_BUNDLE.log fi # Wiping Logs: #cat /dev/null > ${LOG_DIR}/updb_DBA_BUNDLE.log #cat /dev/null > ${LOG_DIR}/alldb_DBA_BUNDLE.log #cat /dev/null > ${LOG_DIR}/updb_DBA_BUNDLE.log.sort #cat /dev/null > ${LOG_DIR}/alldb_DBA_BUNDLE.log.sort #cat /dev/null > ${LOG_DIR}/diff_DBA_BUNDLE.sort rm -f ${LOG_DIR}/updb_DBA_BUNDLE.log rm -f ${LOG_DIR}/alldb_DBA_BUNDLE.log rm -f ${LOG_DIR}/updb_DBA_BUNDLE.log.sort rm -f ${LOG_DIR}/alldb_DBA_BUNDLE.log.sort rm -f ${LOG_DIR}/diff_DBA_BUNDLE.sort ;; esac # ########################### # Checking Listeners log: # ########################### # Check if the LISTENER CHECK flag is Y: case ${CHKLISTENER} in y|Y|yes|YES|Yes|ON|On|on) echo "Checking Listener Log ..." # In case there is NO Listeners are running send an (Alarm): LSN_COUNT=$( ps -ef|grep -v grep|grep tnslsnr|wc -l ) if [ ${LSN_COUNT} -eq 0 ] then echo "The following are the LISTENERS running by user ${ORA_USER} on server ${SRV_NAME}:" > ${LOG_DIR}/listener_processes.log echo "************************************************************************************" >> ${LOG_DIR}/listener_processes.log ps -ef|grep -v grep|grep tnslsnr >> ${LOG_DIR}/listener_processes.log mail -s "ALARM: No Listeners Are Running on Server: ${SRV_NAME} !!!" ${MAIL_LIST} < ${LOG_DIR}/listener_processes.log # In case there is listener running analyze its log: else # for LISTENER_NAME in $( ps -ef|grep -v grep|grep tnslsnr|awk '{print $(NF-1)}' ) for LISTENER_NAME in $( ps -ef|grep -v grep|grep tnslsnr|awk '{print $(9)}' ) do # LISTENER_HOME=`ps -ef|grep -v grep|grep tnslsnr|grep "${LISTENER_NAME} "|awk '{print $(NF-2)}' |sed -e 's/\/bin\/tnslsnr//g'|grep -v sed|grep -v "s///g"` LISTENER_HOME=`ps -ef|grep -v grep|grep tnslsnr|grep "${LISTENER_NAME} "|awk '{print $(8)}' |sed -e 's/\/bin\/tnslsnr//g'|grep -v sed|grep -v "s///g"` export LISTENER_HOME TNS_ADMIN=${LISTENER_HOME}/network/admin; export TNS_ADMIN export TNS_ADMIN LISTENER_LOGDIR=`${LISTENER_HOME}/bin/lsnrctl status ${LISTENER_NAME} |grep "Listener Log File"| awk '{print $NF}'| sed -e 's/\/alert\/log.xml//g'` export LISTENER_LOGDIR LISTENER_LOG=${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log export LISTENER_LOG # Determine if the listener name is in Upper/Lower case: if [ ! -f ${LISTENER_LOG} ] then # Listner_name is Uppercase: LISTENER_NAME=$( echo ${LISTENER_NAME} | awk '{print toupper($0)}' ) export LISTENER_NAME LISTENER_LOG=${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log export LISTENER_LOG fi if [ ! -f ${LISTENER_LOG} ] then # Listener_name is Lowercase: LISTENER_NAME=$( echo "${LISTENER_NAME}" | awk '{print tolower($0)}' ) export LISTENER_NAME LISTENER_LOG=${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log export LISTENER_LOG fi if [ -f ${LISTENER_LOG} ] then # Rename the old log (If exists): if [ -f ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log ] then mv ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log ${LOG_DIR}/alert_lis_${LISTENER_NAME}_old.log # Create a new log: tail -1000 ${LISTENER_LOG} > ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log # Get the new entries: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/diff_lis_${LISTENER_NAME}.log echo " " >> ${LOG_DIR}/diff_lis_${LISTENER_NAME}.log diff ${LOG_DIR}/alert_lis_${LISTENER_NAME}_old.log ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log | grep ">" | cut -f2 -d'>' >> ${LOG_DIR}/diff_lis_${LISTENER_NAME}.log # Search for errors: #ERRORS=`cat ${LOG_DIR}/diff_lis_${LISTENER_NAME}.log|grep "TNS-"|egrep -v "${EXL_LSNR_ERR}"|tail -1` ERRORS=`cat ${LOG_DIR}/diff_lis_${LISTENER_NAME}.log|grep "TNS-"|egrep -v "${EXL_LSNR_ERR}"|tail -1` SRVC_REG=`cat ${LOG_DIR}/diff_lis_${LISTENER_NAME}.log| grep "service_register" ` FILE_ATTACH=${LOG_DIR}/diff_lis_${LISTENER_NAME}.log # If no old logs exist: else # Just create a new log without doing any comparison: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log echo " " >> ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log tail -1000 ${LISTENER_LOG} >> ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log # Search for errors: #ERRORS=`cat ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log|grep "TNS-"|egrep -v "${EXL_LSNR_ERR}"|tail -1` ERRORS=`cat ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log | grep "TNS-"|egrep -v "${EXL_LSNR_ERR}"|tail -1` SRVC_REG=`cat ${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log | grep "service_register" ` FILE_ATTACH=${LOG_DIR}/alert_lis_${LISTENER_NAME}_new.log fi # Report TNS Errors (Alert) case "${ERRORS}" in *TNS-*) # In case timeout errors reported enclose the Network Failure Staticits in the same E-mail: case ${TIMEOUTDIGMORE} in y|Y|yes|YES|Yes|true|TRUE|True|on|ON|On) case "${ERRORS}" in *timeout*) case `uname` in Linux ) echo "Listener TIMEOUT errors reported, Checking OS Network Failure Statistics for the last 15 minutes ..." echo -e "Network Statistics are shown at the bottom of this E-mail\n$(cat ${FILE_ATTACH})" > ${FILE_ATTACH} echo "" >> ${FILE_ATTACH} echo "" >> ${FILE_ATTACH} echo "NIC Statistics in the last 15 minutes:" >> ${FILE_ATTACH} echo "*************************************" >> ${FILE_ATTACH} echo "sar -n EDEV -s `date "+%H:%M:%S" -d "20 min ago"` | grep -Ev lo" >> ${FILE_ATTACH} sar -n EDEV -s `date "+%H:%M:%S" -d "20 min ago"` | grep -Ev lo >> ${FILE_ATTACH} esac esac esac mail -s "ALERT: Listener [${LISTENER_NAME}] on Server [${SRV_NAME}] reporting errors: ${ERRORS}" ${MAIL_LIST} < ${FILE_ATTACH} esac # Report Registered Services to the listener (Info) case "${SRVC_REG}" in *service_register*) mail -s "INFO: Service Registered on Listener [${LISTENER_NAME}] on Server [${SRV_NAME}] | TNS poisoning possibility" ${MAIL_LIST} < ${FILE_ATTACH} esac else echo "Cannot find the listener log: <${LISTENER_LOG}> for listener ${LISTENER_NAME} !" fi done fi esac # ############################### # Checking ASM Instance ALERTLOG: # ############################### # Manually Specify ASM Instance alertlog file location: [In case the script failed to find its location] ASMALERT= export ASMALERT # Check if the CHKASMALERTLOG is enabled: case ${CHKASMALERTLOG} in y|Y|yes|YES|Yes|ON|On|on) ASMCOUNT=`ps -ef|grep -v grep|grep asm_pmon_|wc -l` if [ ${ASMCOUNT} -gt 0 ] then echo "[ASM Instance Found] Locating ASM Instance ALERTLOG ..." # Fetching ASM Instance name: ASM_INSTANCE_NAME=`ps -ef|grep pmon|grep -v grep|grep asm_pmon_|awk '{print $NF}'|sed -e 's/asm_pmon_//g'|grep -v sed|grep -v "s///g"|tail -1` export ASM_INSTANCE_NAME # Locating GRID_HOME: GRID_HOME=`ps -ef|grep ocssd|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v "ocssd.bin"|tail -1` export GRID_HOME if [ ! -d ${GRID_HOME} ] then GRID_HOME=`dbhome ${ASM_INSTANCE_NAME}` export GRID_HOME fi # Locating GRID_BASE: GRID_BASE=`cat ${GRID_HOME}/crs/install/crsconfig_params|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/crs/utl/appvipcfg|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi # Locating ASM ALERTLOG: ASMALERT=`ls -rtl ${GRID_BASE}/diag/asm/+asm/${ASM_INSTANCE_NAME}/trace/alert_+ASM*.log|tail -1|awk '{print $NF}'` export ASMALERT if [ ! -f ${ASMALERT} ] then if [ -x /usr/bin/locate ] then ASMALERT=`ls -rtl \`/usr/bin/locate alert_+ASM\`|tail -1|awk '{print $NF}'` export ASMALERT fi fi if [ ! -d ${GRID_BASE} ] then if [ -f ${ASMALERT} ] then GRID_BASE=`grep 'ORACLE_BASE from environment' ${ASMALERT} | awk '{print $(5)}'|tail -1` export GRID_BASE fi fi if [ -f ${ASMALERT} ] then # ASM ALERTLOG Inspection: echo "Checking ASM ALERTLOG ..." if [ -f ${LOG_DIR}/alertASM_new.log ] then mv ${LOG_DIR}/alertASM_new.log ${LOG_DIR}/alertASM_old.log # Create new log: tail -1000 ${ASMALERT} > ${LOG_DIR}/alertASM_new.log # Extract new entries by comparing old & new logs: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/diff_ASMALERT.log echo " " >> ${LOG_DIR}/diff_ASMALERT.log diff ${LOG_DIR}/alertASM_old.log ${LOG_DIR}/alertASM_new.log |grep ">" | cut -f2 -d'>' >> ${LOG_DIR}/diff_ASMALERT.log # Search for errors: ERRORS=`cat ${LOG_DIR}/diff_ASMALERT.log | grep 'ORA-\|TNS-' |egrep -v ${EXL_DB_ALERT_ERR}| tail -1` STARTUPFLAG=`cat ${LOG_DIR}/diff_ASMALERT.log | grep 'Starting ORACLE instance' | tail -1` SHUTDOWNFLAG=`cat ${LOG_DIR}/diff_ASMALERT.log | grep 'Instance shutdown complete' | tail -1` FILE_ATTACH=${LOG_DIR}/diff_ASMALERT.log else # If dbalarm is running for the first time against ASM ALERTLOG, Create a new staging log: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/alertASM_new.log echo " " >> ${LOG_DIR}/alertASM_new.log tail -1000 ${ASMALERT} >> ${LOG_DIR}/alertASM_new.log # Search for errors: ERRORS=`cat ${LOG_DIR}/alertASM_new.log | grep 'ORA-\|TNS-' |egrep -v ${EXL_DB_ALERT_ERR}| tail -1` FILE_ATTACH=${LOG_DIR}/alertASM_new.log fi # Send E-mail alert in case any of the following errors detected: case "${ERRORS}" in *ORA-*|*TNS-*) mail -s "ALERT: ASM Instance on Server [${SRV_NAME}] reporting errors: ${ERRORS}" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALERT: ASM Instance on Server [${SRV_NAME}] reporting errors: ${ERRORS}" esac case "${STARTUPFLAG}" in *'Starting ORACLE instance'*) mail -s "ALERT: Startup Event of ASM Instance Triggered on Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALERT: Startup Event of ASM Instance Triggered on Server [${SRV_NAME}]" esac case "${SHUTDOWNFLAG}" in *'Instance shutdown complete'*) mail -s "ALARM: Shutdown Event of ASM Instance Triggered on Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALARM: Shutdown Event of ASM Instance Triggered on Server [${SRV_NAME}]" esac else echo "Cannot find ASM ALERTLOG, locate utility is not installed on this system." echo "Please manually export the ASM ALERTLOG full path inside dbalarm.sh: e.g. ASMALERT=/u01/app/grid/diag/asm/+asm/+ASM/trace/alert_+ASM.log" fi fi esac # ###################################### # Checking GRID INFRASTRUCTURE ALERTLOG: # ###################################### # Manually Specify GRID INFRASTRUCTURE alertlog file location: [In case the script failed to find its location] GRIDLOGFILE= export GRIDLOGFILE # Check if the CHKCLSALERTLOG flag is enabled: case ${CHKCLSALERTLOG} in y|Y|yes|YES|Yes|ON|On|on) # Locate ADR BASE: VAL_ADR_BASE=$(${ORACLE_HOME}/bin/adrci < ${LOG_DIR}/alertGRID_new.log # Extract the new entries by comparing old & new logs: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/diff_GRIDALERT.log echo " " >> ${LOG_DIR}/diff_GRIDALERT.log diff ${LOG_DIR}/alertGRID_old.log ${LOG_DIR}/alertGRID_new.log |grep ">" | cut -f2 -d'>' >> ${LOG_DIR}/diff_GRIDALERT.log # Search for errors: ERRORS=`cat ${LOG_DIR}/diff_GRIDALERT.log | grep 'ORA-\|TNS-\| error \|error:\|errors with\|Errors\|failed\|fatal error\|Unable to failover\|disconnected from server\|Maximum restart attempts' |egrep -v ${EXL_GRID_ALERT_ERR}| tail -1` STARTUPFLAG=`cat ${LOG_DIR}/diff_GRIDALERT.log | grep 'is starting' | tail -1` SHUTDOWNFLAG=`cat ${LOG_DIR}/diff_GRIDALERT.log | grep 'is exiting' | tail -1` NODEEVECTFLAG=`cat ${LOG_DIR}/diff_GRIDALERT.log | grep 'Node down event' | tail -1` IPCONFLICTFLAG=`cat ${LOG_DIR}/diff_GRIDALERT.log | grep 'is already in use in the network' | tail -1` HEARTBEATFLAG=`cat ${LOG_DIR}/diff_GRIDALERT.log | grep 'not scheduled for' | tail -1` SERVICEFAILFLAG=`cat ${LOG_DIR}/diff_GRIDALERT.log | grep 'has been removed from pool' | tail -1` FILE_ATTACH=${LOG_DIR}/diff_GRIDALERT.log else # If dbalarm is running for the first time against GRID ALERTLOG, Create a new staging log: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/alertGRID_new.log echo " " >> ${LOG_DIR}/alertGRID_new.log tail -1000 ${GRIDALERT} >> ${LOG_DIR}/alertGRID_new.log # Search for errors: ERRORS=`cat ${LOG_DIR}/alertGRID_new.log | grep 'ORA-\|TNS-' |egrep -v ${EXL_DB_ALERT_ERR}| tail -1` FILE_ATTACH=${LOG_DIR}/alertGRID_new.log fi # Send E-mail alert in case any of the following errors detected: case "${ERRORS}" in *'ORA-'*|*'TNS-'*|*' error '*|*'error:'*|*'errors with'*|*'Errors'*|*'failed'*|*'fatal error'*|*'Unable to failover'*|*'disconnected from server'*|*'Maximum restart attempts'*) mail -s "ALERT: GRID on Server [${SRV_NAME}] reporting errors: ${ERRORS}" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALERT: GRID on Server [${SRV_NAME}] reporting errors: ${ERRORS}" esac case "${STARTUPFLAG}" in *'is starting'*) mail -s "ALARM: GRID Startup Event Detected on Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALARM: GRID Startup Event Detected." esac case "${SHUTDOWNFLAG}" in *'is exiting'*) mail -s "ALARM: GRID SHUTDOWN Event Detected on Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALARM: GRID SHUTDOWN Event Detected." esac case "${NODEEVECTFLAG}" in *'Node down event'*) mail -s "ALARM: GRID Node Eviction Event Detected on Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALARM: GRID Node Eviction Event Detected." esac case "${IPCONFLICTFLAG}" in *'is already in use in the network'*) mail -s "ALARM: IP CONFLICT Detected In The Network Impacting The GRID On Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALARM: IP CONFLICT Detected In The Network Impacting The GRID." esac case "${HEARTBEATFLAG}" in *'not scheduled for'*) mail -s "ALARM: GRID HEARTBEAT Failure Detected on Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALARM: GRID HEARTBEAT Failure Detected." esac case "${SERVICEFAILFLAG}" in *'has been removed from pool'*) mail -s "ALARM: GRID SERVICE Down Event Detected on Server [${SRV_NAME}]" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALARM: GRID SERVICE Down Event Detected." esac else echo "Unable to locate the GRID INFRASTRUCTURE ALERTLOG." echo "Please export it manually inside dbalarm script. e.g. GRIDLOGFILE=/u01/app/grid/diag/crs/databasemachinename/crs/trace/alert.log" fi fi esac # ########################### # Checking Goldengate Errors: # ########################### # Manually Specify goldengate logfile location: [In case the script failed to find its location] ALERTGGPATH= export ALERTGGPATH # Check if the Goldengate CHECK flag is Y: case ${CHKGOLDENGATE} in y|Y|yes|YES|Yes|ON|On|on) echo "Checking GoldenGate log ..." # Determine goldengate log path: if [ ! -z ${ALERTGGPATH} ] then GGLOG=${ALERTGGPATH} export GGLOG else GGLOG=`/bin/ps -ef|grep ggserr.log|grep -v grep|tail -1|awk '{print $NF}'` export GGLOG fi # Second Attempt: [Expensive search with locate command] if [ -z ${GGLOG} ] then if [ -x /usr/bin/locate ] then GGLOG=`ls -rtl \`/usr/bin/locate ggserr.log\`|tail -1|awk '{print $NF}'` export GGLOG fi fi if [ ! -z ${GGLOG} ] then # Rename the old log generated by the script (if exists): if [ -f ${LOG_DIR}/ggserr_new.log ] then mv ${LOG_DIR}/ggserr_new.log ${LOG_DIR}/ggserr_old.log # Create new staging log in case it's the first run of dbalarm.sh: tail -1000 ${GGLOG} > ${LOG_DIR}/ggserr_new.log # Extract new entries by comparing old & new logs: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/diff_ggserr.log echo " " >> ${LOG_DIR}/diff_ggserr.log diff ${LOG_DIR}/ggserr_old.log ${LOG_DIR}/ggserr_new.log |grep ">" | cut -f2 -d'>' >> ${LOG_DIR}/diff_ggserr.log # Search for errors: #ERRORS=`cat ${LOG_DIR}/diff_ggserr.log | grep 'ERROR' |egrep -v ${EXL_GG_ERR}| tail -1` ERRORS=`cat ${LOG_DIR}/diff_ggserr.log | grep 'ERROR' | tail -1` FILE_ATTACH=${LOG_DIR}/diff_ggserr.log else # Create new log: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/ggserr_new.log echo " " >> ${LOG_DIR}/ggserr_new.log tail -1000 ${GGLOG} >> ${LOG_DIR}/ggserr_new.log # Search for errors: #ERRORS=`cat ${LOG_DIR}/ggserr_new.log | grep 'ERROR' |egrep -v ${EXL_GG_ERR}| tail -1` ERRORS=`cat ${LOG_DIR}/ggserr_new.log | grep 'ERROR' | tail -1` FILE_ATTACH=${LOG_DIR}/ggserr_new.log fi # Send mail in case error exist: case ${ERRORS} in *' ERROR '*) echo "Goldengate Error Detected. Reporting the problem." mail -s "Goldengate Error on Server [${SRV_NAME}]: ${ERRORS}" ${MAIL_LIST} < ${FILE_ATTACH} esac fi esac # ############################# # Check Device Driver Messages: [dmesg] # ############################# case ${DEVICEDRIVERLOG} in y|Y|yes|YES|Yes|ON|On|on) echo "Checking Device Driver [dmesg] ..." if [ -f ${LOG_DIR}/dmesg_new.log ] then mv ${LOG_DIR}/dmesg_new.log ${LOG_DIR}/dmesg_old.log # Generate a new log to compare the old with: dmesg > ${LOG_DIR}/dmesg_new.log # Extract new entries by comparing old & new logs: echo "[Reported By ${SCRIPT_NAME} Script]" > ${LOG_DIR}/diff_dmesg.log echo " " >> ${LOG_DIR}/diff_dmesg.log diff ${LOG_DIR}/dmesg_old.log ${LOG_DIR}/dmesg_new.log |grep ">" | cut -f2 -d'>' >> ${LOG_DIR}/diff_dmesg.log # Search for Errors: ERRORS=`cat ${LOG_DIR}/diff_dmesg.log | grep 'error' |egrep -v ${EXL_DMESG_ERR}| tail -1` FILE_ATTACH=${LOG_DIR}/diff_dmesg.log else # If dbalarm is running for the first time against dmesg log, create a new staging log and use it for the next execution: dmesg > ${LOG_DIR}/dmesg_new.log fi case "${ERRORS}" in *error*) mail -s "ALERT: OS DEVICE DRIVER Error Detected on Server [${SRV_NAME}] | ${ERRORS}" ${MAIL_LIST} < ${FILE_ATTACH} echo "ALERT: OS DEVICE DRIVER Error Detected | ${ERRORS}" esac esac # ############################### # De-Neutralize login.sql file: # ############################### # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi echo "" echo "[dbalarm Script Completed]" echo "" # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/backup_ctrl_spf_AWR.sh 0000740 0152073 0152061 00000030603 13775064052 016664 0 ustar oracle oinstall # ################################################################################# # Backup Controlfile & SPFILE & Generate AWR Report on ALL Running Databases # ################################################################################# VER="[1.3]" # # # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 11-04-16 # # # # # # # 22-01-18 Added CONTROLFILE RMAN compressed backup. # 23-01-18 Defaulted the AWR auto generation to NO: AWRFLAG=N # # # # ################################################################################# SCRIPT_NAME="backup_ctrl_spf_AWR" SRV_NAME=`uname -n` # Receive an Email notification if the backup location filesystem hit the threshold: MAIL_LIST="youremail@yourcompany.com" # ################### # SCRIPT CONTROLS: # ################### # Enable/Disable CONTROLFILE & SPFILE Backup: [Default ENABLED] CTRLSPFFLAG=Y export CTRLSPFFLAG # Enable/Disable AWR Report Generation: [Default DISABLED] AWRFLAG=N export AWRFLAG # ######################### # THRESHOLDS: # ######################### # Don't run the backup if the Filesystem where the backup will be located has reached the following threshold: FSTHRESHOLD=90 # FILESYSTEM %USED THRESHOLD IF THE BACKUP LOCATION REACHED THE SCRIPT WILL TERMINATE TO AVOID FILLING THE FILESYSTEM. # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances dbalarm will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" # ######################### # Setting ORACLE_SID: # ######################### # Exit with sending Alert mail if No DBs are running: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) if [ $INS_COUNT -eq 0 ] then exit fi for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" mail -s "${SCRIPT_NAME} Script on Server [${SRV_NAME}] failed to locate ORACLE_HOME for SID [${ORACLE_SID}], Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory" ${MAIL_LIST} < /dev/null exit fi # ######################### # Variables: # ######################### export PATH=$PATH:${ORACLE_HOME}/bin # #################### # BACKUP DIRECTORY: # #################### # CONTORLFILE & SPFILE backup directory location: BKP_DIR=${USR_ORA_HOME}/backup_ctl_spfile export BKP_DIR if [ ! -d ${BKP_DIR} ] then mkdir -p ${BKP_DIR} chown -R ${ORA_USER} ${BKP_DIR} chmod -R o-rwx ${BKP_DIR} fi # Exit if the backup location is not accessible: if [ ! -d ${BKP_DIR} ] then echo "Location Path \"${BKP_DIR}\" is NOT EXIST!" echo "Script Terminated!" exit fi # AWR report directory location: case ${AWRFLAG} in Y|y|YES|yes|Yes|ON|on) AWR_DIR=${BKP_DIR}/AWRs export AWR_DIR if [ ! -d ${AWR_DIR} ] then mkdir -p ${AWR_DIR} chown -R ${ORA_USER} ${AWR_DIR} chmod -R o-rwx ${AWR_DIR} fi if [ ! -d ${AWR_DIR} ] then echo "Location Path \"${AWR_DIR}\" is NOT EXIST!" echo "Script Terminated!" exit fi echo "AWR report will be stored under ${AWR_DIR}";; esac echo "CONTROLFILE & SPFILE Backup will be stored under: ${BKP_DIR}" # ####################################### # Checking The FILESYSTEM Available Size: # ####################################### # Workaround df command output bug "`/root/.gvfs': Permission denied" if [ -f /etc/redhat-release ] then export DF='df -hPx fuse.gvfs-fuse-daemon' else export DF='df -h' fi cd ${BKP_DIR} FSLOG=/tmp/backup_ctl_spf_filesystem_used.log echo "Reported By Script: ${SCRIPT_NAME}" > ${FSLOG} echo "" >> ${FSLOG} #echo "Controfile, SPFILE and AWR BACKUP has failed because the filesystem that hold the backup has hit the identified threshold ${FSTHRESHOLD}%" >> ${FSLOG} echo "" >> ${FSLOG} echo "Filesystem Utilization Details" >> ${FSLOG} echo ".................................." >> ${FSLOG} ${DF} . >> ${FSLOG} ${DF} .| grep -v "^Filesystem" |awk '{print substr($0, index($0, $2))}'| grep -v "/dev/mapper/"| grep -v "/dev/asm/"|awk '{print $(NF-1)" "$NF}'| while read OUTPUT do PRCUSED=`echo ${OUTPUT}|awk '{print $1}'|cut -d'%' -f1` FILESYS=`echo ${OUTPUT}|awk '{print $2}'` # Terminate the script and send notification to the user incase the THRESHOLD REACHED: if [ ${PRCUSED} -ge ${FSTHRESHOLD} ] then mail -s "WARNING: Controlfile/SPFILE/AWR Backup FAILED on Server [${SRV_NAME}] | Filesystem [${FILESYS}] has reached ${PRCUSED}% of USED space" ${MAIL_LIST} < ${FSLOG} echo "Script Terminated! Please check the space on the backup location." fi done LAST_PCTUSED=`cat ${FSLOG}|awk '{print $5}'|cut -d'%' -f1|tail -1` if [ ${LAST_PCTUSED} -ge ${FSTHRESHOLD} ] then exit fi rm -f ${FSLOG} # ######################## # Getting ORACLE_BASE: # ######################## # Get ORACLE_BASE from user's profile if it EMPTY: if [ -z "${ORACLE_BASE}" ] then ORACLE_BASE=`grep -h 'ORACLE_BASE=\/' $USR_ORA_HOME/.bash* $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` fi # ######################### # Getting DB_NAME: # ######################### VAL1=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 'SYS' and blocks>10 and round(blocks * ${blksize}/1024/1024) > 10 -- List only the tables with Fragmented Space > 30%: and ((round((blocks * ${blksize}/1024/1024)) - round((num_rows * avg_row_len/1024/1024))) / round((blocks * ${blksize}/1024/1024))) * 100 > 30 order by "FRAGMENTED_SPACE_MB" desc) where rownum<51; PROMPT EOF echo "";; esac # Checking FORCE LOGGING mode: # ########################### VAL1=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF select force_logging from v\$database; EOF ) VAL2=`echo ${VAL1}| awk '{print $NF}'` case ${VAL2} in YES) echo echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" echo "INFO: THE DATABASE IS IN FORCE LOGGING MODE." echo "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv" echo;sleep 2;; *);; esac echo echo "Enter the OWNER of The Table:" echo "=============================" while read OWNER do case ${OWNER} in "")echo echo "Enter the OWNER of the Table:" echo "============================";; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('${OWNER}'); EOF ) VAL22=`echo ${VAL11}| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "ERROR: USER [${OWNER}] IS NOT EXIST ON DATABASE [${ORACLE_SID}] !" echo; echo "Searching For Users Match The Provided String ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off select username "Users Match Provided String" from dba_users where username like upper ('%${OWNER}%'); EOF echo;echo "Enter A Valid Table Owner:" echo "=========================";; *) break;; esac esac done echo echo "Enter the TABLE Name:" echo "====================" while read OBJECT_NAME do case ${OBJECT_NAME} in "")echo echo "Enter the TABLE NAME:" echo "====================";; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_TABLES WHERE OWNER=upper('${OWNER}') AND TABLE_NAME=UPPER('${OBJECT_NAME}'); EOF ) VAL22=`echo ${VAL11}| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "INFO: TABLE [${OBJECT_NAME}] IS NOT EXIST UNDER SCHEMA [${OWNER}] !" echo;echo "Searching for tables match the provided string ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off select table_name "Tables Match Provided String:" from dba_tables where owner=upper('${OWNER}') and table_name like upper ('%${OBJECT_NAME}%'); EOF echo;echo "Enter A VALID TABLE NAME:" echo "========================";; *) break;; esac esac done VALLASTANALYZED=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < DBMS_REDEFINITION.CONS_USE_ROWID); exit; EOF ) USEREDEFINITION=`echo ${USEREDEFINITIONRAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` case ${USEREDEFINITIONRAW} in *'currently being redefined'*) echo "Looks you already ran the script against the same table and didn't complete." echo -e "\033[33;5mPlease run the following command to CLEANUP the STATE of the previous execution then run rebuild_table script again:\033[0m" echo "" echo "EXEC DBMS_REDEFINITION.abort_redef_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper(''));" echo "" echo "SCRIPT TERMINATED!" echo "" exit 1;; esac case ${USEREDEFINITION} in *completed*) echo "" echo -e "\033[33;5mVoila! TABLE [${OBJECT_NAME}] is eligible to be rebuild ONLINE using DBMS_REDEFINITION [with a Very Minimal Downtime on the table].\033[0m" echo "" echo "Do you want to use DBMS_REDEFINITION for ONLINE Table REBUILD with a MINIMAL DOWNTIME on the table? [Y|N] Y" echo "===================================================================================================" echo "Enter NO in case you want to use ALTER TABLE MOVE option." while read ANS do case $ANS in ""|y|Y|yes|YES|Yes) # Creating the INTERIM TABLE: export OBJECT_NAME_INT=${OBJECT_NAME}_INT # Check if the INTERIM TABLE is already exist: INTERIM_TABLE_EXIST_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off echo off; SELECT count(*) from dba_tables where owner=upper('${OWNER}') and table_name=upper('${OBJECT_NAME_INT}'); exit; EOF ) INTERIM_TABLE_EXIST=`echo ${INTERIM_TABLE_EXIST_RAW} | awk '{print $NF}'` if [ ${INTERIM_TABLE_EXIST} -eq 1 ] then echo -e "\033[33;5mThe INTERIM table [${OWNER}.${OBJECT_NAME_INT}] IS ALREADY EXIST!\033[0m" echo "Changing the INTERIM TABLE NAME to [${OBJECT_NAME}_XNT]." export OBJECT_NAME_INT=${OBJECT_NAME}_XNT # Second Attempt of checking the existance of INTERIM table: INTERIM_TABLE_EXIST2_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off echo off; SELECT count(*) from dba_tables where owner=upper('${OWNER}') and table_name=upper('${OBJECT_NAME_INT}'); exit; EOF ) INTERIM_TABLE_EXIST2=`echo ${INTERIM_TABLE_EXIST2_RAW} | awk '{print $NF}'` if [ ${INTERIM_TABLE_EXIST2} -eq 1 ] then echo -e "\033[33;5mAgain! A table with same name of the INTERIM table [${OBJECT_NAME_INT}] IS ALREADY EXIST!\033[0m" echo "Most probably you ran this script multiple times against the same table, if this is the case; then please DROP the old INTERIM tables|MATERIALIZED VIEWS." echo "SCRIPT TERMINATED!" echo "" exit 1 fi fi # SETTING PCT_FREE FOR THE TABLE AFTER THE REBUILD: # ################################################# VALDEFAULTPCTFREE=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${REBUILDTABLESCRIPT} echo "PROMPT THIS OPERATION IS LOGGED IN: [${REBUILDTABLESPOOL}]" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "set pages 0 feedback off lines 168" >> ${REBUILDTABLESCRIPT} echo "EXEC DBMS_SESSION.set_identifier('REBUILDING_${OWNER}.${OBJECT_NAME}');" >> ${REBUILDTABLESCRIPT} echo "PROMPT ***************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT Session Details:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ***************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select 'OSPID: '||p.spid from v\$session s, v\$process p where s.sid=(select sid from v\$mystat where rownum=1) and s.paddr=p.addr;" >> ${REBUILDTABLESCRIPT} echo "select 'SID: '||sid from v\$mystat where rownum = 1;" >> ${REBUILDTABLESCRIPT} echo "select 'Serial#: '||s.serial# from v\$session s where s.sid = (select sid from v\$mystat where rownum = 1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT You can KILL this session using this command:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ********************************************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select 'ALTER SYSTEM DISCONNECT SESSION '''||sid||','||serial#||''' IMMEDIATE;' from v\$session where sid = (select sid from v\$mystat where rownum = 1);" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT TABLE INFO BEFORE THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT *****************************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set linesize 168 pages 1000 heading on feedback on" >> ${REBUILDTABLESCRIPT} echo "col \"OWNER.TABLE\" for a35" >> ${REBUILDTABLESCRIPT} echo "col tablespace_name for a20" >> ${REBUILDTABLESCRIPT} echo "col \"READONLY\" for a8" >> ${REBUILDTABLESCRIPT} echo "col \"%RECLAIM\" for 999" >> ${REBUILDTABLESCRIPT} echo "col LAST_ANALYZED for a13" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select /*+RULE*/ t.owner||'.'||t.table_name \"OWNER.TABLE\",t.TABLESPACE_NAME,d.extents,t.LOGGING" >> ${REBUILDTABLESCRIPT} echo ",t.COMPRESSION,t.READ_ONLY \"READONLY\",o.created,to_char(t.LAST_ANALYZED, 'DD-MON-YYYY') LAST_ANALYZED" >> ${REBUILDTABLESCRIPT} echo ",round(d.bytes/1025/1024) SIZE_MB," >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2) \"FRAGMENTED_SPACE_MB\"," >> ${REBUILDTABLESCRIPT} echo "((round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2)) /" >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2)) * 100 \"%RECLAIM\"" >> ${REBUILDTABLESCRIPT} echo "from dba_tables t, dba_objects o, dba_segments d" >> ${REBUILDTABLESCRIPT} echo "where t.owner= upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "and t.table_name = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "and o.owner=t.owner" >> ${REBUILDTABLESCRIPT} echo "and o.object_name=t.table_name" >> ${REBUILDTABLESCRIPT} echo "and o.owner=d.owner" >> ${REBUILDTABLESCRIPT} echo "and t.table_name=d.SEGMENT_NAME;" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT LOBS:" >> ${REBUILDTABLESCRIPT} echo "PROMPT -----" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "col SEGMENT_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col INDEX_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col SECUREFILE for a10" >> ${REBUILDTABLESCRIPT} echo "col COLUMN_NAME for a40" >> ${REBUILDTABLESCRIPT} echo "select SEGMENT_NAME,COLUMN_NAME,TABLESPACE_NAME,INDEX_NAME,SECUREFILE,COMPRESSION from dba_lobs" >> ${REBUILDTABLESCRIPT} echo "where owner=upper('${OWNER}') and table_name = upper('${OBJECT_NAME}');" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT INDEXES BEFORE THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ---------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "COLUMN OWNER FORMAT A25 heading \"Index Owner\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN INDEX_NAME FORMAT A30 heading \"Index Name\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_NAME FORMAT A25 heading \"On Column\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_POSITION FORMAT 9999 heading \"Pos\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN \"INDEX\" FORMAT A35" >> ${REBUILDTABLESCRIPT} echo "COLUMN INDEX_TYPE FOR A16" >> ${REBUILDTABLESCRIPT} echo "SELECT /*+RULE*/ IND.OWNER||'.'||IND.INDEX_NAME \"INDEX\"," >> ${REBUILDTABLESCRIPT} echo " IND.INDEX_TYPE," >> ${REBUILDTABLESCRIPT} echo " COL.COLUMN_NAME," >> ${REBUILDTABLESCRIPT} echo " COL.COLUMN_POSITION," >> ${REBUILDTABLESCRIPT} echo " IND.TABLESPACE_NAME," >> ${REBUILDTABLESCRIPT} echo " IND.STATUS," >> ${REBUILDTABLESCRIPT} echo " IND.UNIQUENESS," >> ${REBUILDTABLESCRIPT} echo " IND.LAST_ANALYZED,round(d.bytes/1024/1024) SIZE_MB" >> ${REBUILDTABLESCRIPT} echo "FROM SYS.DBA_INDEXES IND," >> ${REBUILDTABLESCRIPT} echo " SYS.DBA_IND_COLUMNS COL," >> ${REBUILDTABLESCRIPT} echo " DBA_SEGMENTS d" >> ${REBUILDTABLESCRIPT} echo "WHERE IND.TABLE_NAME = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_OWNER = upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_NAME = COL.TABLE_NAME" >> ${REBUILDTABLESCRIPT} echo "AND IND.OWNER = d.OWNER(+)" >> ${REBUILDTABLESCRIPT} echo "AND IND.OWNER = COL.INDEX_OWNER" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_OWNER = COL.TABLE_OWNER" >> ${REBUILDTABLESCRIPT} echo "AND IND.INDEX_NAME = COL.INDEX_NAME" >> ${REBUILDTABLESCRIPT} echo "AND IND.INDEX_NAME = d.SEGMENT_NAME(+);" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT CONSTRAINTS BEFORE THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT -------------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "col CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "col R_CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "select CONSTRAINT_NAME,CONSTRAINT_TYPE,R_CONSTRAINT_NAME,STATUS,DEFERRED,INDEX_NAME from dba_constraints where">> ${REBUILDTABLESCRIPT} echo "OWNER=upper('${OWNER}') and TABLE_NAME=upper('${OBJECT_NAME}') order by CONSTRAINT_TYPE;" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Setting the PARALLELISM FACTOR to ${PARALLEL_DEGREE}] ..." >> ${REBUILDTABLESCRIPT} echo "alter session enable parallel dml;" >> ${REBUILDTABLESCRIPT} echo "alter session enable parallel ddl;" >> ${REBUILDTABLESCRIPT} echo "alter session enable parallel query;" >> ${REBUILDTABLESCRIPT} echo "alter session force parallel dml parallel ${PARALLEL_DEGREE};" >> ${REBUILDTABLESCRIPT} echo "alter session force parallel ddl parallel ${PARALLEL_DEGREE};" >> ${REBUILDTABLESCRIPT} echo "alter session force parallel query parallel ${PARALLEL_DEGREE};" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Setting the SESSION DDL WAIT FOR LOCK to 5 minutes] ..." >> ${REBUILDTABLESCRIPT} echo "alter session set ddl_lock_timeout=300;" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Setting the SESSION RESUMABLE TIMEOUT to 6 Hours] ..." >> ${REBUILDTABLESCRIPT} echo "ALTER SESSION ENABLE RESUMABLE TIMEOUT 21600 NAME 'REBUILD_OF_TABLE_${OBJECT_NAME}';" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Starting REBUILDING the table using DBMS_REDEFINITION] ..." >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT At anytime you can abort the REBUILD process by executing this command:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ----------------------------------------------------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT exec dbms_redefinition.abort_redef_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'));;" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT REBUILDING TABLE PROCEDURE WILL START WITHIN 5 Seconds ..." >> ${REBUILDTABLESCRIPT} echo "PROMPT -------------------------------------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "SET FEEDBACK OFF" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(4);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [5]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [4]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [3]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [2]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [1]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "SET FEEDBACK ON" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT Keep checking the progress using this statement:" >>${REBUILDTABLESCRIPT} echo "PROMPT ------------------------------------------------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT col OPERATION for a21" >>${REBUILDTABLESCRIPT} echo "PROMPT col \"%DONE\" for 999.999" >>${REBUILDTABLESCRIPT} echo "PROMPT col \"STARTED|MIN_ELAPSED|REMAIN\" for a26" >>${REBUILDTABLESCRIPT} echo "PROMPT col MESSAGE for a90" >>${REBUILDTABLESCRIPT} echo "PROMPT col \"USERNAME| SID,SERIAL#\" for a28" >>${REBUILDTABLESCRIPT} echo "PROMPT select USERNAME||'| '||SID||','||SERIAL# \"USERNAME| SID,SERIAL#\",SQL_ID,round(SOFAR/TOTALWORK*100,2) \"%DONE\"" >>${REBUILDTABLESCRIPT} echo "PROMPT ,to_char(START_TIME,'DD-Mon HH24:MI')||'| '||trunc(ELAPSED_SECONDS/60)||'|'||trunc(TIME_REMAINING/60) \"STARTED|MIN_ELAPSED|REMAIN\" ,MESSAGE" >>${REBUILDTABLESCRIPT} echo "PROMPT from v\$session_longops" >>${REBUILDTABLESCRIPT} echo "PROMPT where TARGET LIKE UPPER('%${OBJECT_NAME}%') and TOTALWORK <> '0' and SOFAR/TOTALWORK*100 <>'100'" >>${REBUILDTABLESCRIPT} echo "PROMPT order by \"STARTED|MIN_ELAPSED|REMAIN\" desc, \"USERNAME| SID,SERIAL#\";;" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "--Exit the script if any failure encountered at any stage:" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "set serveroutput on" >>${REBUILDTABLESCRIPT} echo "WHENEVER SQLERROR EXIT SQL.SQLCODE;" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT START DUPLICATING THE TABLE TO [${OBJECT_NAME_INT}]: [The execution time is dependant on the size of the table and its indexes]" >>${REBUILDTABLESCRIPT} echo "PROMPT ---------------------------------------------------------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT EXEC DBMS_REDEFINITION.start_redef_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'),options_flag => DBMS_REDEFINITION.CONS_USE_ROWID);;" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT [AN ORA-NOTIFICATION MESSAGE WILL BE WRITTEN TO THE ALERTLOG ONEC THE REBUILD OPERATION IS COMPLETED.]" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT NOTE: Feel free to exit from this session as the script is running in the BACKGROUND." >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "SET TIMING ON" >>${REBUILDTABLESCRIPT} echo "EXEC DBMS_REDEFINITION.start_redef_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'),options_flag => DBMS_REDEFINITION.CONS_USE_ROWID);" >>${REBUILDTABLESCRIPT} echo "SET TIMING OFF" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT [INTERIM TABLE INITIAL COPY COMPLETED.]" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT Creating Dependant Objects [Including Indexes] ..." >>${REBUILDTABLESCRIPT} echo "PROMPT ----------------------------------------------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT DECLARE" >>${REBUILDTABLESCRIPT} echo "PROMPT num_errors PLS_INTEGER;;" >>${REBUILDTABLESCRIPT} echo "PROMPT BEGIN" >>${REBUILDTABLESCRIPT} echo "PROMPT DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS (upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}')," >>${REBUILDTABLESCRIPT} echo "PROMPT DBMS_REDEFINITION.CONS_ORIG_PARAMS, TRUE, TRUE, TRUE, TRUE, num_errors, TRUE);;" >>${REBUILDTABLESCRIPT} echo "PROMPT END;;" >>${REBUILDTABLESCRIPT} echo "PROMPT /" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "SET TIMING ON" >>${REBUILDTABLESCRIPT} echo "DECLARE" >>${REBUILDTABLESCRIPT} echo "num_errors PLS_INTEGER;" >>${REBUILDTABLESCRIPT} echo "BEGIN" >>${REBUILDTABLESCRIPT} echo "DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS (upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}')," >>${REBUILDTABLESCRIPT} echo "DBMS_REDEFINITION.CONS_ORIG_PARAMS, TRUE, TRUE, TRUE, TRUE, num_errors, TRUE);" >>${REBUILDTABLESCRIPT} echo "END;" >>${REBUILDTABLESCRIPT} echo "/" >>${REBUILDTABLESCRIPT} echo "SET TIMING OFF" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT [DEPENDANT OBJECTS CREATED.]" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT [Checking the ERROR Log:]" >>${REBUILDTABLESCRIPT} echo "PROMPT SELECT OBJECT_NAME,DDL_TEXT FROM DBA_REDEFINITION_ERRORS WHERE BASE_TABLE_NAME=UPPER('${OBJECT_NAME}');;" >>${REBUILDTABLESCRIPT} echo "set long 200" >>${REBUILDTABLESCRIPT} echo "col DDL_TXT for a150" >>${REBUILDTABLESCRIPT} echo "select object_name, ddl_txt from DBA_REDEFINITION_ERRORS where base_table_name=upper('${OBJECT_NAME}') and ddl_txt not like '%NULL ENABLE NOVALIDATE%';" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT Running the FINAL SYNC of the INTERIM TABLE Before the Actual SWAP:" >>${REBUILDTABLESCRIPT} echo "PROMPT ------------------------------------------------------------------">>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT EXEC DBMS_REDEFINITION.sync_interim_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'));;">>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "SET TIMING ON" >>${REBUILDTABLESCRIPT} echo "EXEC DBMS_REDEFINITION.sync_interim_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'));" >>${REBUILDTABLESCRIPT} echo "SET TIMING OFF" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT Running a COMPARISON between the OLD and NEW TABLE:" >>${REBUILDTABLESCRIPT} echo "PROMPT ***************************************************" >>${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT TABLES:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set linesize 168 pages 1000 heading on feedback off" >> ${REBUILDTABLESCRIPT} echo "col \"TABLE_NAME\" for a55" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "col tablespace_name for a20" >> ${REBUILDTABLESCRIPT} echo "col \"READONLY\" for a8" >> ${REBUILDTABLESCRIPT} echo "col DEGREE for a7" >> ${REBUILDTABLESCRIPT} echo "col \"%RECLAIM\" for 999" >> ${REBUILDTABLESCRIPT} echo "COLUMN TABLE_NAME FORMAT A40 heading \"Table Name\"" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select /*+RULE*/ 'ORIGINAL_TABLE: '||t.table_name \"TABLE_NAME\",t.TABLESPACE_NAME,d.extents," >> ${REBUILDTABLESCRIPT} echo "t.COMPRESSION,t.READ_ONLY \"READONLY\"" >> ${REBUILDTABLESCRIPT} echo ",round(d.bytes/1025/1024) SIZE_MB," >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2) \"FRAGMENTED_SPACE_MB\"," >> ${REBUILDTABLESCRIPT} echo "((round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2)) /" >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2)) * 100 \"%RECLAIM\"" >> ${REBUILDTABLESCRIPT} echo "from dba_tables t, dba_objects o, dba_segments d" >> ${REBUILDTABLESCRIPT} echo "where t.owner= upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "and t.table_name = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "and o.owner=t.owner" >> ${REBUILDTABLESCRIPT} echo "and o.object_name=t.table_name" >> ${REBUILDTABLESCRIPT} echo "and o.owner=d.owner" >> ${REBUILDTABLESCRIPT} echo "and t.table_name=d.SEGMENT_NAME" >> ${REBUILDTABLESCRIPT} echo "union" >> ${REBUILDTABLESCRIPT} echo "select /*+RULE*/ 'NEW_TABLE: '||t.table_name TABLE_NAME,t.TABLESPACE_NAME,d.extents" >> ${REBUILDTABLESCRIPT} echo ",t.COMPRESSION,t.READ_ONLY \"READONLY\"" >> ${REBUILDTABLESCRIPT} echo ",round(d.bytes/1025/1024) SIZE_MB" >> ${REBUILDTABLESCRIPT} echo ",round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2) \"FRAGMENTED_SPACE_MB\"" >> ${REBUILDTABLESCRIPT} echo ",((round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2)) /" >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2)) * 100 \"%RECLAIM\"" >> ${REBUILDTABLESCRIPT} echo "from dba_tables t, dba_objects o, dba_segments d" >> ${REBUILDTABLESCRIPT} echo "where t.owner= upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "and t.table_name = upper('${OBJECT_NAME_INT}')" >> ${REBUILDTABLESCRIPT} echo "and o.owner=t.owner" >> ${REBUILDTABLESCRIPT} echo "and o.object_name=t.table_name" >> ${REBUILDTABLESCRIPT} echo "and o.owner=d.owner" >> ${REBUILDTABLESCRIPT} echo "and t.table_name=d.SEGMENT_NAME" >> ${REBUILDTABLESCRIPT} echo "order by 1 desc;" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "set pages 0" >> ${REBUILDTABLESCRIPT} echo "select 'ORIGINAL_TABLE NUMBER OF ROWS: '||count(*) from ${OWNER}.${OBJECT_NAME};" >> ${REBUILDTABLESCRIPT} echo "select 'NEW_TABLE NUMBER OF ROWS: '||count(*) from ${OWNER}.${OBJECT_NAME_INT};" >> ${REBUILDTABLESCRIPT} echo "set pages 1000" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT LOBS:" >> ${REBUILDTABLESCRIPT} echo "PROMPT -----" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "col SEGMENT_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col INDEX_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "col SECUREFILE for a10" >> ${REBUILDTABLESCRIPT} echo "col COLUMN_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "select 'ORIGINAL_TABLE: '||TABLE_NAME,SEGMENT_NAME,COLUMN_NAME,TABLESPACE_NAME,INDEX_NAME,SECUREFILE,COMPRESSION from dba_lobs" >> ${REBUILDTABLESCRIPT} echo "where owner=upper('${OWNER}') and table_name = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "union" >> ${REBUILDTABLESCRIPT} echo "select 'NEW_TABLE: '||TABLE_NAME,SEGMENT_NAME,COLUMN_NAME,TABLESPACE_NAME,INDEX_NAME,SECUREFILE,COMPRESSION from dba_lobs" >> ${REBUILDTABLESCRIPT} echo "where owner=upper('${OWNER}') and table_name = upper('${OBJECT_NAME_INT}');" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT INDEXES:" >>${REBUILDTABLESCRIPT} echo "PROMPT --------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "COLUMN TABLE_NAME FORMAT A45 heading \"Table Name\"" >>${REBUILDTABLESCRIPT} echo "COLUMN INDEX_NAME FORMAT A30 heading \"Index Name\"" >>${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_NAME FORMAT A25 heading \"On Column\"" >>${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_POSITION FORMAT 9999 heading \"Pos\"" >>${REBUILDTABLESCRIPT} echo "COLUMN \"INDEX\"FORMAT A35" >>${REBUILDTABLESCRIPT} echo "COLUMN TABLESPACE_NAME FOR A25" >>${REBUILDTABLESCRIPT} echo "COLUMN INDEX_TYPE FOR A14" >>${REBUILDTABLESCRIPT} echo "SELECT /*+RULE*/ 'ORIGINAL_TABLE: '||I.TABLE_NAME \"TABLE_NAME\", I.INDEX_NAME \"INDEX\",I.STATUS,I.INDEX_TYPE,C.COLUMN_NAME,C.COLUMN_POSITION," >>${REBUILDTABLESCRIPT} echo "I.UNIQUENESS \"UNIQUE\",round(d.bytes/1024/1024) SIZE_MB FROM DBA_INDEXES I, DBA_IND_COLUMNS C, DBA_SEGMENTS d" >>${REBUILDTABLESCRIPT} echo "WHERE I.TABLE_NAME = upper('${OBJECT_NAME}') AND I.TABLE_OWNER = upper('${OWNER}') AND I.TABLE_NAME = C.TABLE_NAME" >>${REBUILDTABLESCRIPT} echo "AND I.OWNER = d.OWNER AND I.OWNER = C.INDEX_OWNER AND I.TABLE_OWNER = C.TABLE_OWNER AND I.INDEX_NAME = C.INDEX_NAME" >>${REBUILDTABLESCRIPT} echo "AND I.INDEX_NAME = d.SEGMENT_NAME" >>${REBUILDTABLESCRIPT} echo "union" >>${REBUILDTABLESCRIPT} echo "SELECT 'NEW_TABLE: '||I.TABLE_NAME \"TABLE_NAME\", I.INDEX_NAME \"INDEX\",I.STATUS,I.INDEX_TYPE,C.COLUMN_NAME,C.COLUMN_POSITION," >>${REBUILDTABLESCRIPT} echo "I.UNIQUENESS \"UNIQUE\",round(d.bytes/1024/1024) SIZE_MB FROM DBA_INDEXES I, DBA_IND_COLUMNS C, DBA_SEGMENTS d" >>${REBUILDTABLESCRIPT} echo "WHERE I.TABLE_NAME = upper('${OBJECT_NAME_INT}') AND I.TABLE_OWNER = upper('${OWNER}') AND I.TABLE_NAME = C.TABLE_NAME" >>${REBUILDTABLESCRIPT} echo "AND I.OWNER = d.OWNER AND I.OWNER = C.INDEX_OWNER AND I.TABLE_OWNER = C.TABLE_OWNER AND I.INDEX_NAME = C.INDEX_NAME" >>${REBUILDTABLESCRIPT} echo "AND I.INDEX_NAME = d.SEGMENT_NAME AND COLUMN_NAME <> 'M_ROW\$\$'" >>${REBUILDTABLESCRIPT} echo "order by 1 desc;" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT Dependant Objects:" >>${REBUILDTABLESCRIPT} echo "PROMPT ------------------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "select 'ORIGINAL_TABLE: '||NAME \"TABLE_NAME\",REFERENCED_OWNER,REFERENCED_NAME,REFERENCED_TYPE from DBA_DEPENDENCIES where">>${REBUILDTABLESCRIPT} echo "OWNER=upper('${OWNER}') and NAME=upper('${OBJECT_NAME_INT}')" >>${REBUILDTABLESCRIPT} echo "union" >>${REBUILDTABLESCRIPT} echo "select 'NEW_TABLE: '||NAME \"TABLE_NAME\",REFERENCED_OWNER,REFERENCED_NAME,REFERENCED_TYPE from DBA_DEPENDENCIES where">>${REBUILDTABLESCRIPT} echo "OWNER=upper('${OWNER}') and NAME=upper('${OBJECT_NAME}')" >>${REBUILDTABLESCRIPT} echo "order by 1 desc;" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT CONSTRAINTS:" >>${REBUILDTABLESCRIPT} echo "PROMPT ------------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "col CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "col R_CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "select 'ORIGINAL_TABLE: '||TABLE_NAME \"TABLE_NAME\",CONSTRAINT_NAME,CONSTRAINT_TYPE,R_CONSTRAINT_NAME,STATUS,DEFERRED,INDEX_NAME from dba_constraints where">>${REBUILDTABLESCRIPT} echo "OWNER=upper('${OWNER}') and TABLE_NAME=upper('${OBJECT_NAME_INT}')" >>${REBUILDTABLESCRIPT} echo "union" >>${REBUILDTABLESCRIPT} echo "select 'NEW_TABLE: '||TABLE_NAME \"TABLE_NAME\",CONSTRAINT_NAME,CONSTRAINT_TYPE,R_CONSTRAINT_NAME,STATUS,DEFERRED,INDEX_NAME from dba_constraints where">>${REBUILDTABLESCRIPT} echo "OWNER=upper('${OWNER}') and TABLE_NAME=upper('${OBJECT_NAME}')" >>${REBUILDTABLESCRIPT} echo "order by 1 desc,CONSTRAINT_TYPE;" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT [Checking the ERROR Log ...]" >>${REBUILDTABLESCRIPT} echo "select object_name, ddl_txt from DBA_REDEFINITION_ERRORS where base_table_name=upper('${OBJECT_NAME}');" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT ***********************" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT Running the ACTUAL SWAP [FINAL STAGE]:" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT ***********************" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT [AN ORA-NOTIFICATION MESSAGE WILL BE WRITTEN TO THE ALERTLOG ONEC THE SWAP IS COMPLETED.]" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT EXEC DBMS_REDEFINITION.finish_redef_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'));;">>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} SET TIMING ON" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} EXEC DBMS_REDEFINITION.finish_redef_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'));" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} SET TIMING OFF" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} SET FEEDBACK OFF" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} exec dbms_system.ksdwrt(3,'ORA-NOTIFICATION: THE REBUILD OF TABLE [${OWNER}.${OBJECT_NAME}] USING DBMS_REDEFINITION COMPLETED.');">>${REBUILDTABLESCRIPT} echo "${HASHSWAP} SET FEEDBACK On" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} PROMPT [THE SWAP BETWEEN THE INTERIM AND ACTUAL TABLE IS COMPLETED.]" >>${REBUILDTABLESCRIPT} echo "${HASHSWAP} exec dbms_system.ksdwrt(3,'ORA-NOTIFICATION: ALL REBUILD STEPS OF TABLE [${OWNER}.${OBJECT_NAME}] COMPLETED. PLEASE CHECK THE LOGFILE: [${REBUILDTABLESPOOL}]');" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT ALL REBUILD STEPS ARE COMPLETED EXCEPT THE ACTUAL SWAP BETWEEN THE ORIGINAL AND INTERIM TABLE." >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT **************************************************" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT EXECUTE THE FOLLOWING ACTUAL SWAP COMMAND MANUALLY: [Minimal DOWNTIME will happen]" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT **************************************************" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT EXEC DBMS_REDEFINITION.finish_redef_table(upper('${OWNER}'), upper('${OBJECT_NAME}'), upper('${OBJECT_NAME_INT}'));;">>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} exec dbms_system.ksdwrt(3,'ORA-NOTIFICATION: ALL PRE-STEPS OF REBUILDING TABLE [${OWNER}.${OBJECT_NAME}] ARE COMPLETED PLEASE RUN THE FINAL SWAP COMMAND ASAP TO FINALISE THE REBUILD OPERATION: EXEC DBMS_REDEFINITION.finish_redef_table(upper(''${OWNER}''), upper(''${OBJECT_NAME}''), upper(''${OBJECT_NAME_INT}''));');" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT [Note: It's recommended to GATHER NEW STATISTICS on the table after the execution of the above SWAP command.]">>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT BEGIN" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT DBMS_STATS.GATHER_TABLE_STATS (" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT ownname => upper('${OWNER}')," >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT TABNAME => upper('${OBJECT_NAME}')," >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT DEGREE => DBMS_STATS.AUTO_DEGREE," >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT CASCADE => TRUE," >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE);;" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT END;;" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT /" >>${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} PROMPT" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} PROMPT [GATHERING STATISTICS on the NEW TABLE] ..." >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} SET TIMING ON" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} BEGIN" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} DBMS_STATS.GATHER_TABLE_STATS (" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} ownname => upper('${OWNER}')," >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} TABNAME => upper('${OBJECT_NAME}')," >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} DEGREE => DBMS_STATS.AUTO_DEGREE," >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} CASCADE => TRUE," >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE);" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} END;" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} /" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} SET TIMING OFF" >>${REBUILDTABLESCRIPT} echo "${HASHSTATS} PROMPT" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT FINALLY: PLEASE DOUBLE CHECK THE PROCESS, IF YOU ARE SATISFIED, DROP THE OLD TABLE USING THIS COMMAND:" >>${REBUILDTABLESCRIPT} echo "PROMPT -------- --------------------------------------------------------------------------------------------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT [DROP TABLE ${OWNER}.${OBJECT_NAME_INT} CASCADE CONSTRAINTS PURGE;]">>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT [SCRIPT COMPLETED.]" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT SCRIPT: [${REBUILDTABLESCRIPT}]" >>${REBUILDTABLESCRIPT} echo "PROMPT LOGFILE: [${REBUILDTABLESPOOL}]" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "EXIT" >>${REBUILDTABLESCRIPT} echo "#!/bin/bash" > ${REBUILDTABLESCRIPTRUNNER} echo "nohup ${ORACLE_HOME}/bin/sqlplus \"/ as sysdba\" @${REBUILDTABLESCRIPT} | tee ${REBUILDTABLESPOOL} 2>&1 &" >>${REBUILDTABLESCRIPTRUNNER} chmod 740 ${REBUILDTABLESCRIPTRUNNER} echo "" echo -e "\033[33;5mFeel free to EXIT from this session as the REBUILD operation is running in the BACKGROUND.]\033[0m" echo "" source ${REBUILDTABLESCRIPTRUNNER} exit 1 ;; esac break ;; n|N|no|NO|No) echo "Moving to Other REBUILD Options..."; break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done ;; *object*) echo "The INTERIM TABLE [${OWNER}.${OBJECT_NAME_INT}] is already exist!";echo "Please check and run the script again.";echo "Script Terminated!"; exit 1;; *) echo "";echo -e "\033[33;5mDBMS_REDEIFINITION cannot be used: The INTERIM table [${OWNER}.${OBJECT_NAME_INT}] cannot be created! Moving to 'ALTER TABLE MOVE' option ...\033[0m";; esac else echo "" echo -e "\033[33;5mDBMS_REDEIFINITION is NOT AVAILABLE in this Database Edition!\033[0m" fi # ######################################## # SQLPLUS: TABLE REBUILD: # ######################################## echo "" echo "Exploring \"ALTER TABLE MOVE\" Option ..." case ${ORACLE12_ONLINE} in "ONLINE UPDATE INDEXES") echo -e "\033[33;5mVoila! The Database Version & Edition Support The Online Table Rebuild [Minimal Downtime On The Table!]\033[0m" echo "" echo "Entering ALTER TABLE MOVE ONLINE Mode ..." echo "";; *) echo "" echo "ALTER TABLE MOVE ONLINE is NOT available in this DB Edition!" echo "" printf "`echo "Entering ALTER TABLE MOVE ["` `echo -e "\033[33;5mLegacy Mode\033[0m"` `echo "] ..."`\n" echo "";; esac # Checking if the table has any of NON SUPPORTED data types for ALTER TABLE MOVE operation: VALDATATYPENOSUPPORTRAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${REBUILDTABLESCRIPT} echo "PROMPT THIS OPERATION IS LOGGED IN: [${REBUILDTABLESPOOL}]" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT ********************************************************************************">> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT It's HIGHLY RECOMMENDED to run this script within a DOWNTIME WINDOW, ">> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT To AVOID INTERRUPTING long running queries against the table during the rebuild.">> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT ********************************************************************************">> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} exec dbms_lock.sleep(9);" >> ${REBUILDTABLESCRIPT} echo "set pages 0 feedback off lines 168" >> ${REBUILDTABLESCRIPT} echo "EXEC DBMS_SESSION.set_identifier('REBUILDING_${OWNER}.${OBJECT_NAME}');" >> ${REBUILDTABLESCRIPT} echo "PROMPT ***************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT Session Details:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ***************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select 'OSPID: '||p.spid from v\$session s, v\$process p where s.sid=(select sid from v\$mystat where rownum=1) and s.paddr=p.addr;" >> ${REBUILDTABLESCRIPT} echo "select 'SID: '||sid from v\$mystat where rownum = 1;" >> ${REBUILDTABLESCRIPT} echo "select 'Serial#: '||s.serial# from v\$session s where s.sid = (select sid from v\$mystat where rownum = 1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT You can KILL this session using this command:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ********************************************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select 'ALTER SYSTEM DISCONNECT SESSION '''||sid||','||serial#||''' IMMEDIATE;' from v\$session where sid = (select sid from v\$mystat where rownum = 1);" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "set feedback on" >> ${REBUILDTABLESCRIPT} echo "PROMPT TABLE INFO BEFORE THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT *****************************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set linesize 168 pages 1000 heading on" >> ${REBUILDTABLESCRIPT} echo "col \"OWNER.TABLE\" for a35" >> ${REBUILDTABLESCRIPT} echo "col tablespace_name for a20" >> ${REBUILDTABLESCRIPT} echo "col \"READONLY\" for a8" >> ${REBUILDTABLESCRIPT} echo "col \"%RECLAIM\" for 999" >> ${REBUILDTABLESCRIPT} echo "col LAST_ANALYZED for a13" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select /*+RULE*/ t.owner||'.'||t.table_name \"OWNER.TABLE\",t.TABLESPACE_NAME,d.extents,t.logging," >> ${REBUILDTABLESCRIPT} echo "t.COMPRESSION,t.READ_ONLY \"READONLY\",o.created,to_char(t.LAST_ANALYZED, 'DD-MON-YYYY') LAST_ANALYZED" >> ${REBUILDTABLESCRIPT} echo ",round(d.bytes/1025/1024) SIZE_MB," >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2) \"FRAGMENTED_SPACE_MB\"," >> ${REBUILDTABLESCRIPT} echo "((round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2)) /" >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2)) * 100 \"%RECLAIM\"" >> ${REBUILDTABLESCRIPT} echo "from dba_tables t, dba_objects o, dba_segments d" >> ${REBUILDTABLESCRIPT} echo "where t.owner= upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "and t.table_name = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "and o.owner=t.owner" >> ${REBUILDTABLESCRIPT} echo "and o.object_name=t.table_name" >> ${REBUILDTABLESCRIPT} echo "and o.owner=d.owner" >> ${REBUILDTABLESCRIPT} echo "and t.table_name=d.SEGMENT_NAME;" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT LOBS:" >> ${REBUILDTABLESCRIPT} echo "PROMPT -----" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "col SEGMENT_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col INDEX_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "col SECUREFILE for a10" >> ${REBUILDTABLESCRIPT} echo "col COLUMN_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "select SEGMENT_NAME,COLUMN_NAME,TABLESPACE_NAME,INDEX_NAME,SECUREFILE,COMPRESSION from dba_lobs" >> ${REBUILDTABLESCRIPT} echo "where owner=upper('${OWNER}') and table_name = upper('${OBJECT_NAME}');" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set feedback on" >> ${REBUILDTABLESCRIPT} echo "PROMPT INDEXES BEFORE THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ---------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "COLUMN OWNER FORMAT A25 heading \"Index Owner\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN INDEX_NAME FORMAT A30 heading \"Index Name\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_NAME FORMAT A25 heading \"On Column\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_POSITION FORMAT 9999 heading \"Pos\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN \"INDEX\" FORMAT A35" >> ${REBUILDTABLESCRIPT} echo "COLUMN INDEX_TYPE FOR A16" >> ${REBUILDTABLESCRIPT} echo "SELECT /*+RULE*/ IND.OWNER||'.'||IND.INDEX_NAME \"INDEX\"," >> ${REBUILDTABLESCRIPT} echo " IND.INDEX_TYPE," >> ${REBUILDTABLESCRIPT} echo " COL.COLUMN_NAME," >> ${REBUILDTABLESCRIPT} echo " COL.COLUMN_POSITION," >> ${REBUILDTABLESCRIPT} echo " IND.TABLESPACE_NAME," >> ${REBUILDTABLESCRIPT} echo " IND.STATUS," >> ${REBUILDTABLESCRIPT} echo " IND.UNIQUENESS," >> ${REBUILDTABLESCRIPT} echo " IND.LOGGING," >> ${REBUILDTABLESCRIPT} echo " IND.LAST_ANALYZED,round(d.bytes/1024/1024) SIZE_MB" >> ${REBUILDTABLESCRIPT} echo "FROM SYS.DBA_INDEXES IND," >> ${REBUILDTABLESCRIPT} echo " SYS.DBA_IND_COLUMNS COL," >> ${REBUILDTABLESCRIPT} echo " DBA_SEGMENTS d" >> ${REBUILDTABLESCRIPT} echo "WHERE IND.TABLE_NAME = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_OWNER = upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_NAME = COL.TABLE_NAME" >> ${REBUILDTABLESCRIPT} echo "AND IND.OWNER = d.OWNER(+)" >> ${REBUILDTABLESCRIPT} echo "AND IND.OWNER = COL.INDEX_OWNER" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_OWNER = COL.TABLE_OWNER" >> ${REBUILDTABLESCRIPT} echo "AND IND.INDEX_NAME = COL.INDEX_NAME" >> ${REBUILDTABLESCRIPT} echo "AND IND.INDEX_NAME = d.SEGMENT_NAME(+);" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT CONSTRAINTS BEFORE THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT -------------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "col CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "col R_CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "select CONSTRAINT_NAME,CONSTRAINT_TYPE,R_CONSTRAINT_NAME,STATUS,DEFERRED,INDEX_NAME from dba_constraints where">> ${REBUILDTABLESCRIPT} echo "OWNER=upper('${OWNER}') and TABLE_NAME=upper('${OBJECT_NAME}') order by CONSTRAINT_TYPE;" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Setting the PARALLELISM FACTOR to ${PARALLEL_DEGREE}] ..." >> ${REBUILDTABLESCRIPT} echo "alter session enable parallel dml;" >> ${REBUILDTABLESCRIPT} echo "alter session enable parallel ddl;" >> ${REBUILDTABLESCRIPT} echo "alter session enable parallel query;" >> ${REBUILDTABLESCRIPT} echo "alter session force parallel dml parallel ${PARALLEL_DEGREE};" >> ${REBUILDTABLESCRIPT} echo "alter session force parallel ddl parallel ${PARALLEL_DEGREE};" >> ${REBUILDTABLESCRIPT} echo "alter session force parallel query parallel ${PARALLEL_DEGREE};" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Setting the SESSION DDL WAIT FOR LOCK to 5 minutes] ..." >> ${REBUILDTABLESCRIPT} echo "alter session set ddl_lock_timeout=300;" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Setting the SESSION RESUMABLE TIMEOUT to 6 Hours] ..." >> ${REBUILDTABLESCRIPT} echo "ALTER SESSION ENABLE RESUMABLE TIMEOUT 21600 NAME 'REBUILD_OF_TABLE_${OBJECT_NAME}';" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT [Start REBUILDING the table using: ALTER TABLE MOVE ${ORACLE12_ONLINE} command] ..." >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT TABLE REBUILD PROCEDURE WILL START WITHIN 5 Seconds ..." >> ${REBUILDTABLESCRIPT} echo "PROMPT ---------------------------------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "SET FEEDBACK OFF" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(4);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [5]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [4]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [3]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [2]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "PROMPT [1]" >> ${REBUILDTABLESCRIPT} echo "exec dbms_lock.sleep(1);" >> ${REBUILDTABLESCRIPT} echo "--Exit the script if any failure encountered at any stage:" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set serveroutput on" >> ${REBUILDTABLESCRIPT} echo "WHENEVER SQLERROR EXIT SQL.SQLCODE;" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT [START REBUILDING TABLE [${OWNER}.${OBJECT_NAME}]] ..." >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT [SETTING TABLE [${OWNER}.${OBJECT_NAME}] IN NOLOGGING MODE] ..." >> ${REBUILDTABLESCRIPT} echo "ALTER TABLE ${OWNER}.${OBJECT_NAME} NOLOGGING;" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT [REBUILDING TABLE [${OWNER}.${OBJECT_NAME}] [This may take quite long depending on the table size] ..." >> ${REBUILDTABLESCRIPT} echo "SET FEEDBACK ON" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT Keep checking the progress using this statement:" >>${REBUILDTABLESCRIPT} echo "PROMPT -----------------------------------------------" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT col OPERATION for a21" >>${REBUILDTABLESCRIPT} echo "PROMPT col \"%DONE\" for 999.999" >>${REBUILDTABLESCRIPT} echo "PROMPT col \"STARTED|MIN_ELAPSED|REMAIN\" for a26" >>${REBUILDTABLESCRIPT} echo "PROMPT col MESSAGE for a90" >>${REBUILDTABLESCRIPT} echo "PROMPT col \"USERNAME| SID,SERIAL#\" for a28" >>${REBUILDTABLESCRIPT} echo "PROMPT select USERNAME||'| '||SID||','||SERIAL# \"USERNAME| SID,SERIAL#\",SQL_ID,round(SOFAR/TOTALWORK*100,2) \"%DONE\"" >>${REBUILDTABLESCRIPT} echo "PROMPT ,to_char(START_TIME,'DD-Mon HH24:MI')||'| '||trunc(ELAPSED_SECONDS/60)||'|'||trunc(TIME_REMAINING/60) \"STARTED|MIN_ELAPSED|REMAIN\" ,MESSAGE" >>${REBUILDTABLESCRIPT} echo "PROMPT from v\$session_longops" >>${REBUILDTABLESCRIPT} echo "PROMPT where TARGET LIKE UPPER('%${OBJECT_NAME}%') and TOTALWORK <> '0' and SOFAR/TOTALWORK*100 <>'100'" >>${REBUILDTABLESCRIPT} echo "PROMPT order by \"STARTED|MIN_ELAPSED|REMAIN\" desc, \"USERNAME| SID,SERIAL#\";;" >>${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "PROMPT EXECUTING: [ALTER TABLE ${OWNER}.${OBJECT_NAME} MOVE ${ORACLE12_ONLINE} ${TABLESPACE_NAME} PARALLEL ${PARALLEL_DEGREE} PCTFREE ${TABPCTFREE} ${COMPRESS};]">> ${REBUILDTABLESCRIPT} echo "ALTER TABLE ${OWNER}.${OBJECT_NAME} MOVE ${ORACLE12_ONLINE} ${TABLESPACE_NAME} PARALLEL ${PARALLEL_DEGREE} PCTFREE ${TABPCTFREE} ${COMPRESS};">> ${REBUILDTABLESCRIPT} echo "PROMPT COMPLETED: [ALTER TABLE ${OWNER}.${OBJECT_NAME} MOVE ${ORACLE12_ONLINE} ${TABLESPACE_NAME} PARALLEL ${PARALLEL_DEGREE} PCTFREE ${TABPCTFREE} ${COMPRESS};]" >>${REBUILDTABLESCRIPT} echo "PROMPT" >>${REBUILDTABLESCRIPT} echo "${DISABLELOGGING} PROMPT [SETTING TABLE [${OWNER}.${OBJECT_NAME}] IN LOGGING MODE] ..." >> ${REBUILDTABLESCRIPT} echo "${DISABLELOGGING} ALTER TABLE ${OWNER}.${OBJECT_NAME} LOGGING ;" >> ${REBUILDTABLESCRIPT} echo "${DISABLELOGGING} PROMPT" >>${REBUILDTABLESCRIPT} echo "${DISABLEPARALLELISM} PROMPT [SETTING TABLE [${OWNER}.${OBJECT_NAME}] TO ITS ORIGINAL PARALLELISM DEGREE ${VALTABPARALLELDEGREE}] ...">> ${REBUILDTABLESCRIPT} echo "${DISABLEPARALLELISM} ALTER TABLE ${OWNER}.${OBJECT_NAME} PARALLEL ${VALTABPARALLELDEGREE};" >> ${REBUILDTABLESCRIPT} echo "" >>${REBUILDTABLESCRIPT} echo "SET TERMOUT OFF PAGES 1000 LINESIZE 167 HEADING OFF FEEDBACK OFF VERIFY OFF ECHO OFF" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} SPOOL ${REBUILDINDEXSCRIPT}" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} select 'SPOOL ${REBUILDINDEXSPOOL}' from dual;" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} select 'ALTER INDEX '||owner||'.\"'||index_name||'\" REBUILD ${ONLINE_REBUILD} ${TABLESPACE_NAME} PARALLEL ${PARALLEL_DEGREE} PCTFREE ${IDXPCTFREE} ${COMPRESS};'">> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} from dba_indexes where TABLE_OWNER=upper('${OWNER}') and TABLE_NAME=upper('${OBJECT_NAME}');" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} select 'ALTER INDEX '||owner||'.\"'||index_name||'\" PARALLEL ${VALTABPARALLELDEGREE};'from dba_indexes where TABLE_OWNER=upper('${OWNER}') and TABLE_NAME=upper('${OBJECT_NAME}');" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} select 'spool off' from dual;" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} SPOOL OFF" >>${REBUILDTABLESCRIPT} echo "SET TERMOUT ON ECHO OFF FEEDBACK ON VERIFY OFF" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT [REBUILDING INDEXES] ..." >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} @${REBUILDINDEXSCRIPT}" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT [INDEXES REBUILD COMPLETED.]" >> ${REBUILDTABLESCRIPT} echo "${ORACLE12_HASH} PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT [GATHERING STATISTICS ON TABLE [${OWNER}.${OBJECT_NAME}] AND ITS INDEXES] ..." >> ${REBUILDTABLESCRIPT} echo "BEGIN" >> ${REBUILDTABLESCRIPT} echo "DBMS_STATS.GATHER_TABLE_STATS (" >> ${REBUILDTABLESCRIPT} echo "ownname => upper('${OWNER}')," >> ${REBUILDTABLESCRIPT} echo "tabname => upper('${OBJECT_NAME}')," >> ${REBUILDTABLESCRIPT} echo "cascade => TRUE," >> ${REBUILDTABLESCRIPT} echo "METHOD_OPT => 'FOR ALL COLUMNS SIZE SKEWONLY'," >> ${REBUILDTABLESCRIPT} echo "DEGREE => DBMS_STATS.AUTO_DEGREE," >> ${REBUILDTABLESCRIPT} echo "estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE);" >> ${REBUILDTABLESCRIPT} echo "END;" >> ${REBUILDTABLESCRIPT} echo "/" >> ${REBUILDTABLESCRIPT} echo "PROMPT [GATHER STATISTICS COMPLETED.]" >> ${REBUILDTABLESCRIPT} echo "${HASHNOTIFY} exec dbms_system.ksdwrt(3,'ORA-NOTIFICATION: REBUILD OF TABLE [${OWNER}.${OBJECT_NAME}] COMPLETED. LOGFILE: ${REBUILDTABLESPOOL}');">>${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set feedback on" >> ${REBUILDTABLESCRIPT} echo "PROMPT TABLE INFO AFTER THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ****************************" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set linesize 168 pages 1000 heading on" >> ${REBUILDTABLESCRIPT} echo "col \"OWNER.TABLE\" for a35" >> ${REBUILDTABLESCRIPT} echo "col tablespace_name for a20" >> ${REBUILDTABLESCRIPT} echo "col \"READONLY\" for a8" >> ${REBUILDTABLESCRIPT} echo "col \"%RECLAIM\" for 999" >> ${REBUILDTABLESCRIPT} echo "col LAST_ANALYZED for a13" >> ${REBUILDTABLESCRIPT} echo "col PCT_FREE for 99999999" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "select /*+RULE*/ t.owner||'.'||t.table_name \"OWNER.TABLE\",t.TABLESPACE_NAME,d.extents,t.PCT_FREE,t.logging" >> ${REBUILDTABLESCRIPT} echo ",t.COMPRESSION,t.READ_ONLY \"READONLY\",to_char(t.LAST_ANALYZED, 'DD-MON-YYYY') LAST_ANALYZED" >> ${REBUILDTABLESCRIPT} echo ",round(d.bytes/1025/1024) SIZE_MB," >> ${REBUILDTABLESCRIPT} echo "round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2) \"FRAGMENTED_SPACE_MB\"," >> ${REBUILDTABLESCRIPT} echo "((round((t.blocks * ${blksize}/1024/1024), 2) - round((t.num_rows * t.avg_row_len/1024/1024), 2)) / round((t.blocks * ${blksize}/1024/1024), 2)) * 100 \"%RECLAIM\"" >> ${REBUILDTABLESCRIPT} echo "from dba_tables t, dba_objects o, dba_segments d" >> ${REBUILDTABLESCRIPT} echo "where t.owner= upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "and t.table_name = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "and o.owner=t.owner" >> ${REBUILDTABLESCRIPT} echo "and o.object_name=t.table_name" >> ${REBUILDTABLESCRIPT} echo "and o.owner=d.owner" >> ${REBUILDTABLESCRIPT} echo "and t.table_name=d.SEGMENT_NAME;" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT LOBS:" >> ${REBUILDTABLESCRIPT} echo "PROMPT -----" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "col SEGMENT_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col INDEX_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "col COMPRESSION for a8" >> ${REBUILDTABLESCRIPT} echo "col SECUREFILE for a10" >> ${REBUILDTABLESCRIPT} echo "col COLUMN_NAME for a35" >> ${REBUILDTABLESCRIPT} echo "select SEGMENT_NAME,COLUMN_NAME,TABLESPACE_NAME,INDEX_NAME,SECUREFILE,COMPRESSION from dba_lobs" >> ${REBUILDTABLESCRIPT} echo "where owner=upper('${OWNER}') and table_name = upper('${OBJECT_NAME}');" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT INDEXES AFTER THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT --------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "set feedback on" >> ${REBUILDTABLESCRIPT} echo "COLUMN OWNER FORMAT A25 heading \"Index Owner\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN INDEX_NAME FORMAT A30 heading \"Index Name\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_NAME FORMAT A25 heading \"On Column\"" >> ${REBUILDTABLESCRIPT} echo "COLUMN COLUMN_POSITION FORMAT 999 heading Pos" >> ${REBUILDTABLESCRIPT} echo "COLUMN INDEX FORMAT A35" >> ${REBUILDTABLESCRIPT} echo "COLUMN INDEX_TYPE FORMAT A13" >> ${REBUILDTABLESCRIPT} echo "SELECT /*+RULE*/ IND.OWNER||'.'||IND.INDEX_NAME \"INDEX\"," >> ${REBUILDTABLESCRIPT} echo " IND.INDEX_TYPE," >> ${REBUILDTABLESCRIPT} echo " IND.PCT_FREE," >> ${REBUILDTABLESCRIPT} echo " COL.COLUMN_NAME," >> ${REBUILDTABLESCRIPT} echo " COL.COLUMN_POSITION," >> ${REBUILDTABLESCRIPT} echo " IND.TABLESPACE_NAME," >> ${REBUILDTABLESCRIPT} echo " IND.STATUS," >> ${REBUILDTABLESCRIPT} echo " IND.UNIQUENESS," >> ${REBUILDTABLESCRIPT} echo " IND.LOGGING," >> ${REBUILDTABLESCRIPT} echo " IND.LAST_ANALYZED,round(d.bytes/1024/1024) SIZE_MB" >> ${REBUILDTABLESCRIPT} echo "FROM SYS.DBA_INDEXES IND," >> ${REBUILDTABLESCRIPT} echo " SYS.DBA_IND_COLUMNS COL," >> ${REBUILDTABLESCRIPT} echo " DBA_SEGMENTS d" >> ${REBUILDTABLESCRIPT} echo "WHERE IND.TABLE_NAME = upper('${OBJECT_NAME}')" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_OWNER = upper('${OWNER}')" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_NAME = COL.TABLE_NAME" >> ${REBUILDTABLESCRIPT} echo "AND IND.OWNER = d.OWNER(+)" >> ${REBUILDTABLESCRIPT} echo "AND IND.OWNER = COL.INDEX_OWNER" >> ${REBUILDTABLESCRIPT} echo "AND IND.TABLE_OWNER = COL.TABLE_OWNER" >> ${REBUILDTABLESCRIPT} echo "AND IND.INDEX_NAME = COL.INDEX_NAME" >> ${REBUILDTABLESCRIPT} echo "AND IND.INDEX_NAME = d.SEGMENT_NAME(+);" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT CONSTRAINTS AFTER THE REBUILD:" >> ${REBUILDTABLESCRIPT} echo "PROMPT ------------------------------" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "col CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "col R_CONSTRAINT_NAME for a30" >> ${REBUILDTABLESCRIPT} echo "select CONSTRAINT_NAME,CONSTRAINT_TYPE,R_CONSTRAINT_NAME,STATUS,DEFERRED,INDEX_NAME from dba_constraints where">> ${REBUILDTABLESCRIPT} echo "OWNER=upper('${OWNER}') and TABLE_NAME=upper('${OBJECT_NAME}') order by CONSTRAINT_TYPE;" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT [TABLE REBUILD OPERATION COMPLETED.]" >> ${REBUILDTABLESCRIPT} echo "" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT [SCRIPT COMPLETED.]" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "PROMPT SCRIPT: [${REBUILDTABLESCRIPT}]" >> ${REBUILDTABLESCRIPT} echo "PROMPT LOGFILE: [${REBUILDTABLESPOOL}]" >> ${REBUILDTABLESCRIPT} echo "PROMPT" >> ${REBUILDTABLESCRIPT} echo "EXIT" >> ${REBUILDTABLESCRIPT} echo "#!/bin/bash" > ${REBUILDTABLESCRIPTRUNNER} echo "nohup ${ORACLE_HOME}/bin/sqlplus \"/ as sysdba\" @${REBUILDTABLESCRIPT} | tee ${REBUILDTABLESPOOL} 2>&1 &" >>${REBUILDTABLESCRIPTRUNNER} chmod 740 ${REBUILDTABLESCRIPTRUNNER} echo "" echo -e "\033[33;5mFeel free to EXIT from this session as the REBUILD operation is running in the BACKGROUND.\033[0m" echo "" source ${REBUILDTABLESCRIPTRUNNER} # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/start_tracing.sh 0000740 0152073 0152061 00000023002 13775601424 015651 0 ustar oracle oinstall # ##################################################################################################### # Script to Enable the trace on an Oracle Session. # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-12-11 # # # # # # # Modified: 31-12-13 Customized the script to run on various environments. # 04-05-14 Enhanced trace file search criteria. # 16-06-20 Enhanced trace file search criteria. # # ##################################################################################################### # ########### # Description: # ########### echo echo "==================================================" echo "This script Enables tracing for an Oracle Session." echo "==================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################### # Getting BDUMP Location: # ######################### VAL_DUMP=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < '$SESSIONID', serial_num => '$SESSIONSERIAL', waits => true, binds => true ); end; / EOF ) VAL2=`echo $VAL1| grep "successfully completed"` if [ -z "${VAL2}" ] then echo echo "The Session with Provided SID & SERIAL# is NOT EXIST!" echo "Script Terminated." echo exit fi echo VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT p.spid FROM v\$session s,v\$process p WHERE p.addr = s.paddr and s.sid='$SESSIONID' and s.serial#='$SESSIONSERIAL'; EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` VAL33=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT INSTANCE_NAME FROM V\$INSTANCE; EOF ) VAL44=`echo $VAL33| awk '{print $NF}'` echo "TRACING has been ENABLED for session SID:${SESSIONID} / SERIAL#:${SESSIONSERIAL}" TRACEFILE=`find ${BDUMP}/${VAL44}_ora_${VAL22}.trc -mmin -10|tail -1` sleep 1 echo echo "Trace File Location:" echo "-------------------" if [ -z ${TRACEFILE} ] then echo "Once the session start doing activities, try to find the TRACE FILE using the following command:" echo "find ${BDUMP}/${VAL44}_ora_${VAL22}.trc -mmin -10" else echo "Trace File is: ${TRACEFILE}" fi echo sleep 2 echo -e "\033[33;9mDon't forget to STOP the Tracing once you Finish, Using 'stoptrace' Script.\033[0m" echo # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/schedule_rman_full_bkp.sh 0000740 0152073 0152061 00000025151 13775064321 017502 0 ustar oracle oinstall # ############################################################################################## # Script to be used on the crontab to schedule an RMAN Full Backup VER="[1.3]" # ############################################################################################## # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 04-10-17 # # # # # # # Modified: # 10-03-19 Add the option of deleting old CONTROLFILE AUTOBACKUP files. # 16-06-20 Add Backup tag option. # 16-06-20 Add the option of deleting the last backup taken by the same script. # 16-06-20 Add the check of ORACLE HOME validity. # ############################################################################################## # ############################################################## # VARIABLES To be Modified by the user to match the Environment: # ############################################################## # INSTANCE Name: [Replace ${ORACLE_SID} with your instance SID] ORACLE_SID=${ORACLE_SID} # ORACLE_HOME Location: [Replace ${ORACLE_HOME} with the right ORACLE_HOME path] ORACLE_HOME=${ORACLE_HOME} # Backup Name: [TAG] [Replace DAILYBKP with the backup name you want to tag] BACKUPTAG=DAILYBKP # Backup Location: [Replace /backup/rmanfull with the backup location path] BACKUPLOC=/backup/rmanfull # Backup LOG location: RMANLOG=${BACKUPLOC}/rmanfull.log # COMPRESSED BACKUP option:[Y|N] [Default Y] COMPRESSION=Y # Perform Maintenance based on below Backup & Archivelog Retention: [Y|N] [Default DISABLED] MAINTENANCEFLAG=N # Delete the last backup taken by the same script: [Y|N] [Default Y] DELETE_LAST_BKP=Y # Backup Retention "In Days": [Backups older than this retention will be deleted] BKP_RETENTION=7 # Archives Deletion "In Days": [Archivelogs older than this retention will be deleted] ARCH_RETENTION=7 # CONTROLFILE AUTOBACKUP Retention "In Days": [AUTOBACKUP of CONTROLFILE older than this retention will be deleted] CTRL_AUTOBKP_RETENTION=7 # ################## # GENERIC VARIABLES: [Can be left without modification] # ################## # MAX BACKUP Piece Size: [To be considered, it should be BIGGER than the size of the biggest datafile in the database] MAX_BKP_PIECE_SIZE=33g # Show the full DATE and TIME details in the backup log: NLS_DATE_FORMAT='DD-MON-YYYY HH24:MI:SS' export ORACLE_SID export ORACLE_HOME export BACKUPTAG export BACKUPLOC export COMPRESSION export BKP_RETENTION export ARCH_RETENTION export MAX_BKP_PIECE_SIZE export RMANLOG export NLS_DATE_FORMAT export MAINTENANCEFLAG # Check if the backup location is writable: if [ ! -w ${BACKUPLOC} ]; then echo echo -e "\033[32;5mERROR: THE PROVIDED BACKUP LOCATION [${BACKUPLOC}] IS NOT WRITABLE !\033[0m" echo echo "Please provide a valid backup location by editing the value of variable 'BACKUPLOC' inside the script." echo exit fi # Check the selected COMPRESSION option: case ${COMPRESSION} in Y|y|YES|Yes|yes|ON|on) COMPRESSED_BKP="AS COMPRESSED BACKUPSET" export COMPRESSED_BKP ;; *) COMPRESSED_BKP="" export COMPRESSED_BKP ;; esac # Check DELETE LAST BACKUP option: case ${DELETE_LAST_BKP} in Y|y|YES|Yes|yes|ON|on) HASH_DELETE_LAST_BKP="" export HASH_DELETE_LAST_BKP ;; *) HASH_DELETE_LAST_BKP="#" export HASH_DELETE_LAST_BKP ;; esac # Check the selected MAINTENANCE option: case ${MAINTENANCEFLAG} in Y|y|YES|Yes|yes|ON|on) HASH_MAINT="" export HASH_MAINT ;; *) HASH_MAINT="#" export HASH_MAINT ;; esac # Check if ORACLE_SID was missed by the user: # ########################################## if [ ! -z ${ORACLE_SID} ]; then echo "ORACLE_SID was missed, the script will set it to the only running instance if found ..." # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database is Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) echo "Script found only 1 running instance." echo "Script will run against [${ORACLE_SID}] DB ..." else echo "Script is unable to identify which instance to run against!" echo "Please provide a value for ORACLE_SID inside the script." echo "Script Terminated!" exit fi fi # Check if the given ORACLE_HOME is valid: # ####################################### if [ ! -d ${ORACLE_HOME} ]; then echo "ORACLE HOME is not valid, the script will search for the right ORACLE HOME ..." ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi fi # Append the date to the backup log for each script execution: echo "----------------------------" >> ${RMANLOG} date >> ${RMANLOG} echo "----------------------------" >> ${RMANLOG} # ################### # RMAN SCRIPT Section: # ################### ${ORACLE_HOME}/bin/rman target / msglog=${RMANLOG} < ${LOGFILE} fi fi # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ############################### # SQLPLUS: Getting Session Info: # ############################### echo echo "Enter the USERNAME or SESSION SID: [Blank value means list all sessions on the current instance]" echo "==================================" while read ANS do case $ANS in # case the input is non-numeric value: *[!0-9]*) echo if [ -z "${ANS}" ] then ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off linesize 210 pages 1000 col "USERNAME|UNIX_PID|SID,SERIAL#" for a45 col "MACHINE | MODULE" for a40 col event for a28 col "STATUS|WAITD|ACT_SINC|LOG_T" for a45 col "I|BLKD_BY" for a9 select s.USERNAME||' | ' ||p.spid ||' | '||s.sid||','||s.serial# "USERNAME|UNIX_PID|SID,SERIAL#",s.MACHINE||' | '||s.MODULE "MACHINE | MODULE" --,w.event,substr(s.status||'|'||w.seconds_in_wait||'sec',1,30) "STATUS|TIME_WAITED" ,substr(s.status||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||LOGON_TIME,1,45) "ST|WAITD|ACT_SINC|LOG_T" ,substr(w.event,1,28)"EVENT" --,s.CLIENT_IDENTIFIER ,s.PREV_SQL_ID "PREV_SQL_ID",s.sql_id "CURR_SQL_ID" ,s.FINAL_BLOCKING_INSTANCE||'|'||s.FINAL_BLOCKING_SESSION "I|BLKD_BY" from v\$session s,v\$process p, v\$session_wait w,v\$sql q where s.USERNAME like upper ('%$ANS%') and p.addr = s.paddr and s.sid=w.sid order by s.USERNAME||' | '||s.sid||','||s.serial#||' | '||p.spid,MODULE; EOF else ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF col "Previous SQL" for a210 col "Current SQL" for a210 set feedback off linesize 210 pages 1000 col "USER|UNXPID|SID,SER|MACH|MOD" for a54 col event for a23 col "STATUS|WAITD|ACT_SINC|LOG_T" for a45 col "I|BLKD_BY" for a9 select s.USERNAME||'|'||p.spid ||'|'||s.sid||','||s.serial#||'|'||s.MACHINE||'|'||s.MODULE "USER|UNXPID|SID,SER|MACH|MOD" ,substr(s.status||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||s.LAST_CALL_ET||'|'||s.LOGON_TIME,1,45) "ST|WAITD|ACT_SINC|LOG_T" ,substr(w.event,1,23)"EVENT" ,s.PREV_SQL_ID "PREV_SQL_ID" ,s.sql_id "CURR_SQL_ID" ,s.FINAL_BLOCKING_INSTANCE||'|'||s.FINAL_BLOCKING_SESSION "I|BLKD_BY" --,s.CLIENT_IDENTIFIER from v\$session s,v\$process p, v\$session_wait w where s.USERNAME like upper ('%$ANS%') and p.addr = s.paddr and s.sid=w.sid; --order by "INS|USER|SID,SER|MACHIN|MODUL"; Prompt Previous SQL Statement: prompt ----------------------- select s.PREV_SQL_ID,q.SQL_FULLTEXT "Previous SQL" from v\$session s,v\$process p,v\$sql q, v\$session_wait w where s.USERNAME like upper ('%$ANS%') and p.addr = s.paddr and s.sid=w.sid and q.child_number=0 and q.sql_id=s.PREV_SQL_ID; prompt Prompt Current Running SQL Statement: prompt ------------------------------ select s.SQL_ID CURR_SQL_ID,q.SQL_FULLTEXT "Current SQL" from v\$process p,v\$session s ,v\$sql q, v\$session_wait w where s.USERNAME like upper ('%$ANS%') and p.addr = s.paddr and s.sid=w.sid and q.child_number=0 and q.sql_id=s.sql_id; EOF fi echo; # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi exit ;; *) echo if [ -z "${ANS}" ] then ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off set pages 0 spool ${LOGFILE} APPEND prompt select 'Timestamp: '||to_char(sysdate, 'DD-Mon-YYYY HH24:MI:SS') from dual; prompt =================================== prompt ALL sessions in the Database... prompt =================================== prompt set feedback off linesize 220 pages 1000 col inst for 99 col module for a27 col event for a28 col MACHINE for a27 col "STATUS|WAITD|ACT_SINC|LOG_T" for a45 col "INST|USER|SID,SERIAL#" for a30 col "INS|USER|SID,SER|MACHIN|MODUL" for a72 select substr(S.USERNAME||' | '||p.spid||'|'||s.sid||','||s.serial#||' | '||substr(s.MACHINE,1,27)||' | '||substr(s.MODULE,1,27),1,72)"USER|SPID|SID,SER|MACHIN|MODUL" --select s.INST_ID||'|'||s.USERNAME||' | '||s.sid||','||s.serial# "INST|USER|SID,SERIAL#" --,substr(s.MODULE,1,27)"MODULE" --,substr(s.MACHINE,1,27)"MACHINE" --,substr(s.status||'|'||w.state||'|'||w.WAIT_TIME_MICRO||'|'||LAST_CALL_ET||'|'||LOGON_TIME,1,50) "ST|WA_ST|WAITD|ACT_SINC|LOG_T" ,substr(s.status||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||LOGON_TIME,1,45) "STATUS|WAITD|ACT_SINC|LOG_T" ,substr(w.event,1,28)"EVENT" --,s.PREV_SQL_ID ,s.SQL_ID CURR_SQL_ID from v\$session s, v\$session_wait w ,v\$process p where s.USERNAME is not null and p.addr = s.paddr and s.sid=w.sid order by "USER|SPID|SID,SER|MACHIN|MODUL","STATUS|WAITD|ACT_SINC|LOG_T" desc; set pages 1000 col MACHINE for a70 col MODULE for a70 PROMPT PROMPT SESSIONS Distribution: PROMPT ---------------------- PROMPT PER MODULE: select INST_ID,MODULE,count(*) "TOTAL_SESSIONS" from gv\$session group by INST_ID,module order by INST_ID,count(*) desc,MODULE; PROMPT PROMPT PER MACHINE: select INST_ID,MACHINE,count(*) "TOTAL_SESSIONS" from gv\$session group by INST_ID,MACHINE order by INST_ID,count(*) desc,MACHINE; PROMPT set pages 0 select 'ACTIVE SESSIONS: '||count(*) from gv\$session where USERNAME is not null and status='ACTIVE'; select 'INACTIVE SESSIONS: '||count(*) from gv\$session where USERNAME is not null and status='INACTIVE'; select 'BACKGROUND SESSIONS: '||count(*) from gv\$session where USERNAME is null; PROMPT -------------------- ------ select 'TOTAL SESSIONS: '||count(*) from gv\$session; PROMPT EOF else ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off linesize 210 pages 1000 col "DBUSER|OSUSER|UNXPID|SID,SER" for a50 col "MACHINE | MODULE" for a40 col event for a28 col "STATUS|WAITD|ACT_SINC|LOG_T" for a45 col "I|BLKD_BY" for a12 select s.USERNAME||'|'||s.OSUSER||' |'||p.spid ||' |'||s.sid||','||s.serial# "DBUSER|OSUSER|UNXPID|SID,SER",s.MACHINE||' | '||s.MODULE "MACHINE | MODULE" --,w.event,substr(s.status||'|'||w.state||'|'||w.seconds_in_wait||'sec',1,30) "STATUS|WAIT_STATE|TIME_WAITED" ,substr(s.status||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||LOGON_TIME,1,45) "STATUS|WAITD|ACT_SINC|LOG_T" ,substr(w.event,1,28)"EVENT" ,s.FINAL_BLOCKING_INSTANCE||'|'||s.FINAL_BLOCKING_SESSION "I|BLKD_BY" ,s.CLIENT_IDENTIFIER ,s.PREV_SQL_ID "PREV_SQL_ID",s.sql_id "CURR_SQL_ID" from v\$session s,v\$process p, v\$session_wait w where s.SID ='$ANS' and p.addr = s.paddr and s.sid=w.sid; prompt col "Previous SQL" for a140 select q.SQL_ID,q.SQL_FULLTEXT "Previous SQL" from v\$process p,v\$session s ,v\$sql q where s.SID ='$ANS' and p.addr = s.paddr and q.sql_id=s.PREV_SQL_ID; prompt col "Current SQL" for a140 select q.SQL_ID,q.SQL_FULLTEXT "Current SQL" from v\$process p,v\$session s ,v\$sql q where s.SID ='$ANS' and p.addr = s.paddr and q.sql_id=s.sql_id; EOF fi echo; # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi exit ;; esac done # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/db_locks.sh 0000740 0152073 0152061 00000040325 14012446125 014562 0 ustar oracle oinstall # #################################################################################################################################### # Script to Check the BLOCKING Locks on the DB. VER="[2.3]" # Author: Mahmmoud ADEL # # # # Created: 24-05-08 # # # # ### # Modified: 31-12-13 # # # # # # Customized the script to run on various environments. # 05-09-18 Modified the wait in seconds column for 11gr2 compatibility. # 20-10-18 Fixed divide by zero bug when TOTALWORK=0 in v$session_longops # 26-03-19 Listing the Master Blocking Session details. # 27-03-19 Used RULE Based Optimizer against all "checking locks" queries for a better performance on RAC instances. # 01-08-19 Add more information to object level locks result. # 01-10-20 Simplify Script output and use ALTER SYSTEM DISCONNECT for 11g+. # # # #################################################################################################################################### SCRIPT_NAME="db_locks" SQLLINESIZE=200 export SCRIPT_NAME export SQLLINESIZE ############# # Description: ############# echo echo "===================================================" echo "This script shows ALL BLOCKING LOCKS on a database." echo "===================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -f /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ################### # Getting DB Version: # ################### VAL311=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 0 and l1.id1 = l2.id1 and l2.id2 = l2.id2 order by ${WAIT_COL} desc; prompt prompt ------------------------------------------------- Prompt Blocking Locks On Object Level: prompt ------------------------------------------------- set linesize 1000 pages 100 echo on feedback off column LOCK_TYPE format A30 column LOCK_HELD format A18 column LOCK_REQUESTED format A11 column STATUS format A13 column LOCK_HELD_SEC format 99999999 column "DB_SID | OS_PID" format A15 column "LOCKED_OBJECT" format A39 column "LOCK HOLDER: DB_USER | OS_USER" format A30 select /*+RULE*/ OWNER||'.'||OBJECT_NAME "LOCKED_OBJECT", ORACLE_USERNAME||' | '||lo.OS_USER_NAME "LOCK HOLDER: DB_USER | OS_USER",l.sid||' | '|| lo.PROCESS "DB_SID | OS_PID", decode(TYPE, 'MR', 'Media Recovery', 'RT', 'Redo Thread', 'UN', 'User Name', 'TX', 'Transaction', 'TM', 'DML', 'UL', 'PL/SQL User Lock', 'DX', 'Distributed Xaction', 'CF', 'Control File', 'IS', 'Instance State', 'FS', 'File Set', 'IR', 'Instance Recovery', 'ST', 'Disk Space Transaction', 'TS', 'Temp Segment', 'IV', 'Library Cache Invalidation', 'LS', 'Log Start or Switch', 'RW', 'Row Wait', 'SQ', 'Sequence Number', 'TE', 'Extend Table', 'TT', 'Temp Table', type)||' | '|| decode(LMODE, 0, 'None', 1, 'Null', 2, 'row share lock', 3, 'row exclusive lock', 4, 'Share', 5, '(SSX)exclusive lock', 6, 'Exclusive', lmode) lock_type, l.CTIME LOCK_HELD_SEC, decode(REQUEST, 0, 'None', 1, 'Null', 2, 'row share lock', 3, 'row exclusive lock', 4, 'Share', 5, '(SSX)exclusive lock', 6, 'Exclusive', request) lock_requested, decode(BLOCK, 0, 'Not Blocking', 1, 'Blocking', 2, 'Global', block) status from v\$locked_object lo, dba_objects do, v\$lock l where lo.OBJECT_ID = do.OBJECT_ID AND l.SID = lo.SESSION_ID AND l.BLOCK='1' order by OWNER,OBJECT_NAME; prompt prompt ------------------------------------------------- Prompt Long Running Operations: prompt ------------------------------------------------- set linesize ${SQLLINESIZE} pages 1000 col OPERATION for a21 col "%DONE" for 999.999 col "STARTED|MIN_ELAPSED|REMAIN" for a26 col MESSAGE for a75 col "USERNAME| SID,SERIAL#" for a28 select USERNAME||'| '||SID||','||SERIAL# "USERNAME| SID,SERIAL#",SQL_ID --,OPNAME OPERATION --,substr(SOFAR/TOTALWORK*100,1,5) "%DONE" ,round(SOFAR/TOTALWORK*100,2) "%DONE" ,to_char(START_TIME,'DD-Mon HH24:MI')||'| '||trunc(ELAPSED_SECONDS/60)||'|'||trunc(TIME_REMAINING/60) "STARTED|MIN_ELAPSED|REMAIN" ,MESSAGE from v\$session_longops where SOFAR/TOTALWORK*100 <>'100' and TOTALWORK <> '0' order by "STARTED|MIN_ELAPSED|REMAIN" desc, "USERNAME| SID,SERIAL#"; prompt prompt prompt ------------ prompt TOP BLOCKER: [First Good Candidate for KILL] prompt ------------ set linesize 169 pages 0 col "TOP BLOCKERS" for a180 SELECT * FROM (select /*+RULE*/ 'ALTER SYSTEM ${KILL} SESSION '''||s1.sid||','||s1.serial#||''' immediate;' AS "TOP BLOCKERS" from gv\$LOCK l1, gv\$SESSION s1, gv\$LOCK l2, gv\$SESSION s2 where s1.sid=l1.sid and s2.sid=l2.sid and l1.BLOCK=1 and l2.request > 0 and l1.id1 = l2.id1 and l2.id2 = l2.id2 order by ${WAIT_COL} desc) WHERE ROWNUM = 1; prompt prompt --------------- prompt OTHER BLOCKERs: [Second Good Candidate for KILL] prompt --------------- col "KILL MASTER BLOCKING SESSION" for a75 select /*+RULE*/ 'ALTER SYSTEM DISCONNECT SESSION '''||s.sid||','||s.serial#||''' IMMEDIATE;' "KILL MASTER BLOCKING SESSION" from gv\$session s where s.sid in (select distinct FINAL_BLOCKING_SESSION from gv\$session where FINAL_BLOCKING_SESSION is not null) and s.USERNAME is not null and s.FINAL_BLOCKING_SESSION is null / prompt EOF # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/unlock_user.sh 0000740 0152073 0152061 00000023740 14070574161 015343 0 ustar oracle oinstall # ####################################################################################### # Script to unlock locked users # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-12-11 # # # # # # Modified: 31-12-13 Customized the script to run on various environments. # 16-09-14 Removed User Confirmation. # 12-10-20 Increased the length/complexity of the default password. # # ####################################################################################### SCRIPT_NAME="unlock_user" # ########### # Description: # ########### echo echo "==========================================" echo "This script UNLOCKS locked database users." echo "==========================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # ######################### # Existance of login.sql file under Oracle user Linux home directory eliminates many functions during the execution of this script from crontab: if [ -f ${USR_ORA_HOME}/login.sql ] then mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ############################### # SQLPLUS: Unlock An Oracle User: # ############################### # Variables echo echo "Please enter the USERID:" echo "=======================" while read USERNAME2 do VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('$USERNAME2'); EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` case ${VAL22} in # If the provided value match an exist username in the DB: 1) ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set lines 169 col username for a45 col ACCOUNT_STATUS for a35 SELECT USERNAME,ACCOUNT_STATUS FROM DBA_USERS WHERE USERNAME=upper('$USERNAME2'); PROMPT PROMPT Unlocking user [${USERNAME2}] ... PROMPT EOF VAL1=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF ALTER user $USERNAME2 ACCOUNT UNLOCK; EOF ) VAL2=`echo $VAL1| grep "User altered"` if [ -z "${VAL2}" ] then echo "Failed to unlock User \"${USERNAME2}\" !" echo exit else echo echo User ${USERNAME2} Unlocked Successfully. echo echo "Enter a New Password for User [${USERNAME2}]: " echo "=============================" read PASS1 if [ -z $PASS1 ] then # Setting new password: PASSHALF=`date '+%s'`_UnLoCk\# PASS1=BNDL\#${PASSHALF} echo The Password will be RESET to: ${PASS1} sleep 1 fi VAL3=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF Alter user ${USERNAME2} identified by "$PASS1"; EOF ) VAL4=`echo $VAL3| grep "User altered"` if [ -z "${VAL4}" ] then echo echo Password Reset Failed ! echo $VAL3 | perl -lpe'$_ = reverse' | cut -c-53 | perl -lpe'$_ = reverse' exit else echo echo The Password For User \"${USERNAME2}\" Has Been Reset Successfully. fi ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set lines 169 col username for a45 col ACCOUNT_STATUS for a35 SELECT USERNAME,ACCOUNT_STATUS FROM DBA_USERS WHERE USERNAME=upper('$USERNAME2'); EOF fi; break;; # If no value provided or the value doesn't match any user in the DB try to search for matching: *) echo; echo "INFO: USER [${USERNAME2}] IS NOT EXIST ON DATABASE [$ORACLE_SID] !" echo; echo "Searching ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off col USERNAME for a30 col account_status for a23 col profile for a35 select username,account_status,profile,LOCK_DATE,EXPIRY_DATE from dba_users where username like upper ('%$USERNAME2%'); EOF echo; echo "Please Enter the FULL USERID:" echo "=============================" ;; esac done # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/process_info.sh 0000740 0152073 0152061 00000013451 13775601731 015506 0 ustar oracle oinstall # ################################################## # Script to Show Previous & Current Running SQL STMT # Author: Mahmmoud ADEL # # # # Created: 24-01-11 # # # # ### # Modified: 24-12-13 # # # # # # Customized the script to run on # various environments. # 01-05-14 Added wait details. # 01-05-14 Fix bug of more than # process contain the # same process ID. # # ################################################## # ########### # Description: # ########### echo echo "=================================================================" echo "This script Displays Oracle session Details for an OS process ID." echo "=================================================================" echo sleep 1 # Variables: echo "Please Enter the Unix Process ID:" echo "=================================" read "SPID" # ########################### # Getting ORACLE_SID: # ########################### #CHK1=`ps -ef| grep ${SPID} | grep -v grep | grep LOCAL` CHK1=`ps -ef| grep ${SPID} | grep -v grep` if [ -z "${CHK1}" ] then echo "This Script Is Not Designed For Such Proccess!" echo "This Script Works With Oracle Sessions PIDs Having (LOCAL=YES) or (LOCAL=NO) attribute." exit fi ORACLE_SID=`ps -ef | grep " ${SPID} " | grep -v grep | awk '{print $(NF-1)}'| sed -e 's/oracle//g' | grep -v sed | grep -v "s///g"` if [ -z "${ORACLE_SID}" ] then echo "Can Not Obtain A Valid ORACLE_SID, Please check the process ID you have entered and try again." exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|grep -v ASM|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ############################################# # SQLPLUS: Show Previous/Current SQL Statement: # ############################################# # SQL Script: ${ORACLE_HOME}/bin/sqlplus -s "/ as sysdba" << EOF Prompt Session Details: Prompt ---------------- set feedback off linesize 180 pages 1000 col module for a27 col "USERNAME | SID,SERIAL#" for a35 col "ST|WA_ST|WAITD|ACT_SINC|LOG_T" for a35 col event for a28 select s.USERNAME||' | '||s.sid||','||s.serial# "USERNAME | SID,SERIAL#",s.MODULE, substr(s.status||'|'||w.state||'|'||w.seconds_in_wait||'|'||LAST_CALL_ET||'|'||to_char(LOGON_TIME,'ddMon HH24:MI'),1,40) "ST|WA_ST|WAITD|ACT_SINC|LOG_T", w.event,s.PREV_SQL_ID,s.SQL_ID CURR_SQL_ID from v\$session s,v\$process p, v\$session_wait w where p.spid=$SPID and p.addr = s.paddr and p.addr = s.paddr and s.sid=w.sid; Prompt col "Previous SQL" for a156 select q.SQL_FULLTEXT "Previous SQL" from v\$process p,v\$session s ,v\$sql q where p.spid=$SPID and p.addr = s.paddr and q.sql_id=s.PREV_SQL_ID; prompt col "Current SQL" for a156 select q.SQL_FULLTEXT "Current SQL" from v\$process p,v\$session s ,v\$sql q where p.spid=$SPID and p.addr = s.paddr and q.sql_id=s.sql_id; EOF # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/tablespaces.sh 0000740 0152073 0152061 00000036250 13775601541 015304 0 ustar oracle oinstall # ################################################################### # VER [3.3] # Checking ASM Diskgroups, FRA and Tablespaces Size # # # # # Author: Mahmmoud ADEL # # # # ##### # Created: 18-12-13 # # # # # # # Modified: 04-04-16 dba_tablespace_usage_metrics view # will be used for 11g onwards versions # for checking tablespaces size # As advised by: Satyajit Mohapatra # 02-01-17 Added FRA size check. # # # ################################################################### SCRIPT_NAME="tablespaces" # ########### # Description: # ########### echo echo "=========================================================================" echo "This script Checks ASM Diskgroups, FRA & TABLESPACES Size on the database ..." echo "=========================================================================" echo sleep 1 # ############### # SCRIPT SETTINGS: # ############### # Allow the script to use the legacy tablespace size calculation in case some tablespaces are NOT presented in dba_tablespace_usage_metrics: # Although enabling this setting will make sure all tablespaces will be listed, the legacy calculation method is NOT ACCURATE! SUPPORT_LEGACY=N export SUPPORT_LEGACY # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -f /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # Existance of login.sql file under Oracle user Linux home directory eliminates many functions during the execution of this script from crontab: if [ -f ${USR_ORA_HOME}/login.sql ] then mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ################### # Getting DB Version: # ################### VAL311=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 0 UNION ALL select c.tablespace_name tablespace,dd.MAXSIZE/1024/1024 MAXSIZE_GB,sbytes/1024/1024 x,fbytes/1024/1024 y, (sbytes - fbytes)/1024/1024 obytes, $CALCPERCENTAGE2 from (select tablespace_name,sum(bytes) sbytes from dba_temp_files group by tablespace_name having tablespace_name in (select tablespace_name from dba_tablespaces)) c, (select tablespace_name,sum(bytes_free) fbytes,count(*) ext from v\$temp_space_header group by tablespace_name) d, (select tablespace_name,sum(MAXBYTES) MAXSIZE from dba_temp_files group by tablespace_name) dd --where c.tablespace_name in (select tablespace_name from dba_tablespaces) where c.tablespace_name = d.tablespace_name (+) and c.tablespace_name = dd.tablespace_name order by tablespace; set feed off set pages 0 -- 100% used tablespaces will not appear in dba_free_space, The following is to eliminate this BUG: select 'ALARM: TABLESPACE '||tablespace_name||' IS 100% FULL !' from dba_tablespaces minus select 'ALARM: TABLESPACE '||tablespace_name||' IS 100% FULL !' from dba_free_space; prompt EOF fi # De-Neutralize login.sql file: # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/zAngA_zAngA.sh 0000740 0152073 0152061 00000025231 13775601507 015075 0 ustar oracle oinstall # ############################################################################################## # This script shows AUDIT records for DB User. # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 25-04-2013 # # # # # # # Modified: 07-03-2019 Allow the user to control the display of LOGIN/LOGOFF data. # 10-03-2019 Added the option of excluding specific audit action from the report. # ############################################################################################## # ########################### # Listing Available Instances: # ########################### echo echo "==================================================================" echo "This Script Retreives AUDIT data for a user if auditing is enabled." echo "==================================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Run this script Against:[Enter the number]" echo "-------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################### # SQLPLUS Section: # ######################### # PROMPT FOR VARIABLES: # #################### echo echo "Enter The USERNAME you want to retrieve its Audit Data: [Blank Value means ALL Users]" echo "======================================================" while read DB_USERNAME do case $DB_USERNAME in # NO VALUE PROVIDED: "") USERNAME_COND="";break ;; #*) USERNAME_COND="USERNAME=upper('${DB_USERNAME}') or OS_USERNAME='${DB_USERNAME}' AND";break ;; *) USERNAME_COND="USERNAME=upper('${DB_USERNAME}') AND";break ;; esac done echo echo "Do you want to include LOGIN/LOGOFF information: [Y|N Default [N]]" echo "===============================================" while read LOGININFO do case ${LOGININFO} in # NO VALUE PROVIDED: ""|N|n|NO|no|No) export EXCLUDELOGINDATA="AND ACTION_NAME not like 'LOGO%' AND";break ;; Y|y|YES|yes|Yes) export EXCLUDELOGINDATA="";break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done echo echo "Do you want to EXCLUDE a specific Action from the list:" echo "======================================================" echo "[Blank means INCLUDE ALL Actions Or Provide One of These Action to exclude: SELECT, ALTER, DROP, CREATE, TRUNCATE, GRANT or REVOKE]" while read EXCLUDEDACTION do case ${EXCLUDEDACTION} in # NO VALUE PROVIDED: "") export EXCLUDEDACTION="null";break ;; *) export EXCLUDEDACTION;break ;; esac done echo echo "How [MANY DAYS BACK] you want to retrieve AUDIT data? [Default 1]" echo "=====================================================" echo "OR: Enter A Specific DATE in this FORMAT [DD-MM-YYYY] e.g. 25-01-2011" echo "== =================================================================" while read NUM_DAYS do case $NUM_DAYS in # User PROVIDED a NON NUMERIC value: *[!0-9]*) echo;echo "Retreiving AUDIT data for User [${DB_USERNAME}] on [${NUM_DAYS}] ..." ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < SYSDATE-${NUM_DAYS} ${EXCLUDELOGINDATA} ACTION_NAME not like upper ('%${EXCLUDEDACTION}%') --AND TRUNC(extended_timestamp) = TO_DATE('${NUM_DAYS}','DD-MM-YYYY') order by EXTENDED_TIMESTAMP; PROMPT EOF exit break ;; # NO VALUE PROVIDED: "") export NUM_DAYS=1;echo;echo "Retreiving AUDIT data in the last 24 Hours ... [Please Wait]";break ;; # A NUMERIC VALUE PROVIDED: *) export NUM_DAYS;echo;echo "Retreiving AUDIT data in the last ${NUM_DAYS} Days ... [Please Wait]";break ;; esac done # Execution of SQL Statement: # ########################## ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < SYSDATE-${NUM_DAYS} ${EXCLUDELOGINDATA} ACTION_NAME not like upper ('%${EXCLUDEDACTION}%') order by EXTENDED_TIMESTAMP; PROMPT EOF # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/asmdisks.sh 0000740 0152073 0152061 00000017242 13775063655 014644 0 ustar oracle oinstall ################################################### # Script to show ASM disks info and their group. VER="1.0" # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 27-12-17 # # # # # # # # ################################################### SCRIPT_NAME="asmdisks" # ########### # Description: # ########### echo echo "============================================================" echo "This script Show ASM DISKS information and their ASM Groups." echo "============================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. The following line is Excluding: -MGMTDB and ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ ${INS_COUNT} -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ ${INS_COUNT} -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ ${INS_COUNT} -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ##################### # SQLPLUS SCRIPT: # ##################### ${ORACLE_HOME}/bin/sqlplus -S '/ as sysdba' <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/check_standby_lag.sh 0000740 0152073 0152061 00000011617 14040030261 016417 0 ustar oracle oinstall #!/bin/bash # ######################################################################################### # This script MUST run from the Primary DB server. # It checks the LAG between Primary & Standby database # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 29-10-2015 # # # # # # Modified: 21-04-2021 allowed a DBA user to be used for SQLPLUS login instead of SYSDBA # 21-04-2021 Simplified the Variables section for the end user. # # ######################################################################################### # ###################################### # Variables MUST be modified by the user: [Otherwise the script will not work] # ###################################### # Here you replace youremail@yourcompany.com with your Email address: EMAIL="youremail@yourcompany.com" # Replace ${ORACLE_SID} with the Primary DB instance SID: ORACLE_SID=${ORACLE_SID} # Replace STANDBY_TNS_ENTRY with the Standby Instance TNS entry you configured in the primary site tnsnames.ora file: DRDBNAME=STANDBY_DB # Replace ${ORACLE_HOME} with the ORACLE_HOME path on the primary server: ORACLE_HOME=${ORACLE_HOME} # Log Directory Location: LOG_DIR='/tmp' # Here you replace DBA_USER with a real user having DBA privlege: ID=DBA_USER # Here you replace ABC123 with the DBA user password on the standby DB: CRD='ABC123' # Replace "5" with the number of LAGGED ARCHIVELOGS if reached an Email alert will be sent to the receiver: LAGTHRESHOLD=5 export EMAIL export ORACLE_SID export DRDBNAME export ORACLE_HOME export LOG_DIR export ID export CRD export LAGTHRESHOLD # ############################################# # Other variables will be picked automatically: # ############################################# SCRIPT_NAME="check_standby_lag.sh" export SCRIPT_NAME SRV_NAME=`uname -n` export SRV_NAME LNXVER=`cat /etc/redhat-release | grep -o '[0-9]'|head -1` export LNXVER MAIL_LIST="-r ${SRV_NAME} ${EMAIL}" export MAIL_LIST # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################################### # Script part to execute On the Primary: # ######################################### # Check the current Redolog sequence number: PRDBNAME_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF select name from v\$database; exit; EOF ) PRDBNAME=`echo ${PRDBNAME_RAW} | awk '{print $NF}'` PRSEQ_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF select max(sequence#) from v\$archived_log; exit; EOF ) PRSEQ=`echo ${PRSEQ_RAW} | awk '{print $NF}'` export PRSEQ # ######################################### # Script part to execute On the STANDBY: # ######################################### # Get the last applied Archive Sequence number from the Standby DB: DRSEQ_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF conn ${ID}/"${CRD}"@${DRDBNAME} select max(sequence#) from v\$archived_log where applied='YES'; exit; EOF ) DRSEQ=`echo ${DRSEQ_RAW} | awk '{print $NF}'` export DRSEQ # Compare Both PRSEQ & DRSEQ to detect the lag: # ############################################ LAG=$((${PRSEQ}-${DRSEQ})) export LAG if [ ${LAG} -ge ${LAGTHRESHOLD} ] then ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize 1000 pages 100 spool ${LOG_DIR}/DR_LAST_APPLIED_SEQ.log PROMPT Current Log Sequence on the Primary DB: PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ archive log list PROMPT PROMPT Last Applied Log Sequence# on the Standby DB: PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conn ${ID}/"${CRD}"@${DRDBNAME} set linesize 1000 pages 100 select THREAD#,max(SEQUENCE#) from V\$ARCHIVED_LOG where APPLIED='YES' group by THREAD#; exit; EOF # Send Email with LAG details: echo "Sending an Email alert ..." mail -s "ALARM: DR DB [${DRDBNAME}] is LAGGING ${LAG} sequences behind Primary DB [${PRDBNAME}] on Server [${SRV_NAME}]" ${MAIL_LIST} < ${LOG_DIR}/DR_LAST_APPLIED_SEQ.log fi echo echo Primary DB Sequence is: ${PRSEQ} echo Standby DB Sequence is: ${DRSEQ} echo Number of Lagged Archives Between Primary and Standby is: ${LAG} echo # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/oracle_cleanup.sh 0000740 0152073 0152061 00000056736 14064274662 016007 0 ustar oracle oinstall # ################################################################################### # This script Backup & Cleanup the database logs. [To be run as Oracle user] # [Ver 2.1] # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 03-06-2013 # # # # # # Modified: 02-07-2013 # 14-01-2014 Customized the script to run on various environments. # 14-06-2017 Increased the script accuracy and elimiated tar bug. # 15-05-2018 Added the option of archiving Audit log files. # 27-12-2018 Verify the trace/log locations are valid before cleaning. # 23-01-2019 Added the option of Skipping backing up the trace/logs. # 03-07-2020 Enhance locating the listener's log. # 03-07-2020 Enhance locating the alertlog/bdump/cdump location. # 21-06-2021 Added an option to control the retention time of logs. # # ################################################################################### SCRIPT_NAME="oracle_cleanup" # ########### # Description: # ########### echo echo "==================================================================" echo "This script will Back up & Delete the database logs and Audit logs ..." echo "==================================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Instances: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Backup & Delete It's Logs: [Enter the Number]" echo "----------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################## # Getting ORACLE_BASE: # ######################## echo "Setting ORACLE_BASE ..." # Get ORACLE_BASE from user's profile if it EMPTY: if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`cat ${ORACLE_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export ORACLE_BASE fi if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`grep -h 'ORACLE_BASE=\/' ${USR_ORA_HOME}/.bash* ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi if [ -f ${USR_ORA_HOME}/login.sql ] then mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################### # Getting DB_NAME: # ######################### echo "Getting DB NAME ..." DB_NAME_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${BDUMP}/alert_${INS}.log.keep echo echo -e "\033[32;5mAlertlog Cleanup\033[0m" echo "Zipping the Alertlog ..." gzip -f9 ${BDUMP}/alert_${INS}.log ${HASH_BKP} echo "Backing up the Alertlog ..." ${HASH_BKP} mv -f ${BDUMP}/alert_${INS}.log.gz ${BKP_LOC_DB} echo "Rotating the Alertlog ..." mv -f ${BDUMP}/alert_${INS}.log.keep ${BDUMP}/alert_${INS}.log #tar zcvfP ${BKP_LOC_DB}/${INS}-dump-logs.tar.gz ${DUMP} ${HASH_BKP} echo "Backing up ${DUMP} ..." #find ${DUMP} -name '*' -print > ${BKP_LOC_DB}/dump_files_list.txt #tar zcfP ${BKP_LOC_DB}/${INS}-dump-logs.tar.gz --files-from ${BKP_LOC_DB}/dump_files_list.txt cd ${DUMP} ${HASH_BKP} tar zcfP ${BKP_LOC_DB}/${INS}-dump-logs.tar.gz * # Delete DB logs older than ${KEEPDAYSRAW} days: echo echo -e "\033[32;5mDatabase Logs Cleanup\033[0m" echo "Deleting DB logs older than ${KEEPDAYSRAW} days under ${BDUMP} ..." find ${BDUMP} -type f -name '*.trc' ${KEEPDAYS} -exec rm -f {} \; find ${BDUMP} -type f -name '*.trm' ${KEEPDAYS} -exec rm -f {} \; find ${BDUMP} -type f -name '*.log' ${KEEPDAYS} -exec rm -f {} \; echo "Deleting DB logs older than ${KEEPDAYSRAW} days under ${DUMP}/alert ..." find ${DUMP}/alert -type f -name '*.xml' ${KEEPDAYS} -exec rm -f {} \; echo "Deleting DB logs older than ${KEEPDAYSRAW} days under ${DUMP}/incident ..." find ${DUMP}/incident -type f -name '*.trc' ${KEEPDAYS} -exec rm -f {} \; find ${DUMP}/incident -type f -name '*.trm' ${KEEPDAYS} -exec rm -f {} \; find ${DUMP}/incident -type f -name '*.log' ${KEEPDAYS} -exec rm -f {} \; echo "Deleting DB logs older than ${KEEPDAYSRAW} days under ${CDUMP} ..." find ${CDUMP} -type f -name '*.trc' ${KEEPDAYS} -exec rm -f {} \; find ${CDUMP} -type f -name '*.trm' ${KEEPDAYS} -exec rm -f {} \; find ${CDUMP} -type f -name '*.log' ${KEEPDAYS} -exec rm -f {} \; # Backup & Delete listener's logs: # ################################ #LISTENER_HOME=`ps -ef|grep -v grep|grep tnslsnr|grep -i ${LSNR_NAME}|awk '{print $(NF-2)}' |sed -e 's/\/bin\/tnslsnr//g'|grep -v sed|grep -v "s///g"|head -1` echo echo -e "\033[32;5mListener Logs Cleanup\033[0m" LISTENER_HOME=`ps -ef|grep -v grep|grep tnslsnr|grep "${LSNR_NAME} "|awk '{print $(8)}' |sed -e 's/\/bin\/tnslsnr//g'|grep -v sed|grep -v "s///g"|head -1` TNS_ADMIN=${LISTENER_HOME}/network/admin export TNS_ADMIN LISTENER_LOGDIR=`${LISTENER_HOME}/bin/lsnrctl status ${LISTENER_NAME}|grep "Listener Log File"| awk '{print $NF}'| sed -e 's/\/alert\/log.xml//g'` LISTENER_LOG=${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log echo LISTENER_NAME: $LISTENER_NAME echo LISTENER_HOME: $LISTENER_HOME echo TNS_ADMIN: $TNS_ADMIN # Determine if the listener name is in Upper/Lower case: if [ ! -r ${LISTENER_LOG} ] then # Listner_name is lowercase: LISTENER_NAME=$( echo ${LISTENER_NAME} | awk '{print tolower($0)}' ) export LISTENER_NAME LISTENER_LOG=${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log export LISTENER_LOG if [ ! -r ${LISTENER_LOG} ] then # Listener_name is Uppercase: LISTENER_NAME=$( echo "${LISTENER_NAME}" | awk '{print toupper($0)}' ) export LISTENER_NAME LISTENER_LOG=${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log export LISTENER_LOG echo LISTENER_LOG: $LISTENER_LOG else echo LISTENER_LOG: $LISTENER_LOG fi fi # Exit if LISTENER LOG directory is NULL: if [ -z "${LISTENER_LOGDIR}" ] then echo "LISTENER_LOGDIR variable is NULL." echo "Script Terminated." exit fi # Exit if LISTENER LOG directory is IN-ACCESSIBLE: if [ ! -d ${LISTENER_LOGDIR} ] then echo 'Listener Logs Location Cannot be Found!' echo "Script Terminated." exit fi ${HASH_BKP} echo "Backing up listener logs under: ${LISTENER_LOGDIR}/trace ..." ${HASH_BKP} cd ${LISTENER_LOGDIR}/trace ${HASH_BKP} tar zcfP ${BKP_LOC_DB}/${LISTENER_NAME}_trace.tar.gz * ${HASH_BKP} echo "Backing up listener logs under: ${LISTENER_LOGDIR}/alert ..." ${HASH_BKP} cd ${LISTENER_LOGDIR}/alert ${HASH_BKP} tar zcfP ${BKP_LOC_DB}/${LISTENER_NAME}_alert.tar.gz * tail -10000 ${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log > ${LISTENER_LOGDIR}/${LISTENER_NAME}.log.keep echo "Deleting listener logs older than ${KEEPDAYSRAW} days under: ${LISTENER_LOGDIR}/trace ..." find ${LISTENER_LOGDIR}/trace -type f -name '*.trc' ${KEEPDAYS} -exec rm -f {} \; find ${LISTENER_LOGDIR}/trace -type f -name '*.trm' ${KEEPDAYS} -exec rm -f {} \; find ${LISTENER_LOGDIR}/trace -type f -name '*.log' ${KEEPDAYS} -exec rm -f {} \; echo "Deleting listener logs older than ${KEEPDAYSRAW} days under: ${LISTENER_LOGDIR}/alert ..." find ${LISTENER_LOGDIR}/alert -type f -name '*.xml' ${KEEPDAYS} -exec rm -f {} \; echo "Rotating listener log ${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log ..." mv -f ${LISTENER_LOGDIR}/${LISTENER_NAME}.log.keep ${LISTENER_LOGDIR}/trace/${LISTENER_NAME}.log # ############################ # Backup & Delete AUDIT logs: # ############################ # Getting Audit Files Location: # ############################ case ${AUDIT_FILES_CLEANUP} in Y) echo echo -e "\033[32;5mAudit Logs Cleanup\033[0m" VAL_AUD=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${BKP_LOC_DB}/audit_files_list.txt #tar zcvfP ${BKP_LOC_DB}/${INS}-audit-logs.tar.gz --files-from ${BKP_LOC_DB}/audit_files_list.txt ${HASH_BKP} echo "Backing up Audit files under: ${AUD_LOC} ..." ${HASH_BKP} cd ${AUD_LOC} ${HASH_BKP} tar zcfP ${BKP_LOC_DB}/${INS}-audit-logs.tar.gz ${ORACLE_SID}_*.aud # Delete Audit logs older than ${KEEPDAYSRAW} days echo "Deleting Audit files older than ${KEEPDAYSRAW} days under: ${AUD_LOC} ..." find ${AUD_LOC} -type f -name "${ORACLE_SID}_*.aud" ${KEEPDAYS} -exec rm -f {} \; else # Exit if AUDIT LOG directory is IN-ACCESSIBLE: echo "Audit Files Location Cannot be Found!" exit fi ;; esac echo "" echo "------------------------------------" ${HASH_BKP} echo "Old logs are backed up under: ${BKP_LOC_DB}" echo "The Last 5 Days Logs are KEPT." echo "CLEANUP COMPLETED." echo "------------------------------------" echo # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/RMAN_full.sh 0000740 0152073 0152061 00000030732 14106737667 014604 0 ustar oracle oinstall # ################################################################################################# # This script takes an on-demand RMAN Backup. # [Ver 4.2] # # # # # Author: Mahmmoud ADEL # # # # ### # # # # # # # Created: 24-09-11 # Modified: 31-12-13 Customized the script to run on various environments. # 12-03-16 Run RMAN command in the background to avoid job fail when session terminate. # 23-08-16 Added Backup Encryption Option. # 17-11-16 Added Channels Number feature. # 22-01-18 Added Controlfile compressed backup option. # 22-06-20 Restricting the user from skipping the backup location. # 03-07-20 Changing Backup date format to DD-Mon-YY. # ################################################################################################# # ########### # Description: # ########### echo echo "===================================================" echo "This script Takes a RMAN FULL Backup of a database." echo "===================================================" echo sleep 1 # ########################### # CPU count check: # ########################### # Count of CPUs: CPU_NUM=`cat /proc/cpuinfo|grep CPU|wc -l` export CPU_NUM # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ############################### # RMAN: Script Creation: # ############################### # Last RMAN Backup Info: # ##################### export NLS_DATE_FORMAT='DD-Mon-YYYY HH24:MI:SS' ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 170 pages 200 PROMPT PROMPT LAST 14 DAYS RMAN BACKUP DETAILS: PROMPT --------------------------------- set linesize 160 set feedback off col START_TIME for a15 col END_TIME for a15 col TIME_TAKEN_DISPLAY for a10 col INPUT_BYTES_DISPLAY heading "DATA SIZE" for a10 col OUTPUT_BYTES_DISPLAY heading "Backup Size" for a11 col OUTPUT_BYTES_PER_SEC_DISPLAY heading "Speed/s" for a10 col output_device_type heading "Device_TYPE" for a11 SELECT to_char (start_time,'DD-MON-YY HH24:MI') START_TIME, to_char(end_time,'DD-MON-YY HH24:MI') END_TIME, time_taken_display, status, input_type, output_device_type,input_bytes_display, output_bytes_display, output_bytes_per_sec_display,COMPRESSION_RATIO COMPRESS_RATIO FROM v\$rman_backup_job_details WHERE end_time > sysdate -14; EOF # Variables: export NLS_DATE_FORMAT="DD-MON-YY HH24:MI:SS" # Building the RMAN BACKUP Script: echo;echo echo Please enter the Backup Location: [e.g. /backup/DB] echo "================================" while read BKPLOC1 do if [ ! -w "${BKPLOC1}" ]; then echo "Provided Backup Location is NOT Exist/Writable !" echo echo "Please Provide a VALID Backup Location:" echo "--------------------------------------" else BKPLOC=${BKPLOC1}/RMANBKP_${ORACLE_SID}/`date +%d-%b-%y` /bin/mkdir -p ${BKPLOC} break fi done # Exit if the user has pressed Ctrl+D: if [ ! -w "${BKPLOC}" ]; then exit fi echo echo "Backup Location is: ${BKPLOC}" echo echo "How many CHANNELS do you want to allocate for this backup? [${CPU_NUM} CPUs Available On This Machine]" echo "=========================================================" while read CHANNEL_NUM do integ='^[0-9]+$' if ! [[ ${CHANNEL_NUM} =~ $integ ]] ; then echo "Error: Not a valid number !" echo echo "Please Enter a VALID NUMBER:" echo "---------------------------" else break fi done echo echo "Number Of Channels is: ${CHANNEL_NUM}" echo echo "---------------------------------------------" echo "COMPRESSED BACKUP will allocate SMALLER space" echo "but it's a bit SLOWER than REGULAR BACKUP." echo "---------------------------------------------" echo echo "Do you want a COMPRESSED BACKUP? [Y|N]: [Y]" echo "================================" while read COMPRESSED do case $COMPRESSED in ""|y|Y|yes|YES|Yes) COMPRESSED=" AS COMPRESSED BACKUPSET "; echo "COMPRESSED BACKUP ENABLED.";break ;; n|N|no|NO|No) COMPRESSED="";break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done echo echo "Do you want to ENCRYPT the BACKUP by Password? [Available in Enterprise Edition only] [Y|N]: [N]" echo "==============================================" while read ENCR_BY_PASS_ANS do case ${ENCR_BY_PASS_ANS} in y|Y|yes|YES|Yes) echo echo "Please Enter the password that will be used to Encrypt the backup:" echo "-----------------------------------------------------------------" read ENCR_PASS ENCR_BY_PASS="SET ENCRYPTION ON IDENTIFIED BY '${ENCR_PASS}' ONLY;" export ENCR_BY_PASS echo echo "BACKUP ENCRYPTION ENABLED." echo echo "Later, To RESTORE this backup please use the following command to DECRYPT it, placing it just before the RESTORE Command:" echo " e.g." echo " SET DECRYPTION IDENTIFIED BY '${ENCR_PASS}';" echo " restore database ...." echo break ;; ""|n|N|no|NO|No) ENCR_BY_PASS="";break ;; *) echo "Please enter a VALID answer [Y|N]" ;; esac done RMANSCRIPT=${BKPLOC}/RMAN_FULL_${ORACLE_SID}.rman RMANSCRIPTRUNNER=${BKPLOC}/RMAN_FULL_nohup.sh RMANLOG=${BKPLOC}/rmanlog.`date +%d-%b-%y`.log echo "${ENCR_BY_PASS}" > ${RMANSCRIPT} echo "run {" >> ${RMANSCRIPT} CN=1 while [[ ${CN} -le ${CHANNEL_NUM} ]] do echo "allocate channel C${CN} type disk;" >> ${RMANSCRIPT} ((CN = CN + 1)) done echo "CHANGE ARCHIVELOG ALL CROSSCHECK;" >> ${RMANSCRIPT} #echo "DELETE NOPROMPT EXPIRED ARCHIVELOG ALL;" >> ${RMANSCRIPT} echo "BACKUP ${COMPRESSED} FORMAT '${BKPLOC}/%d_%I_%t_%s_%p' TAG='FULLBKP'" >> ${RMANSCRIPT} echo "FILESPERSET 100 DATABASE include current controlfile PLUS ARCHIVELOG;" >> ${RMANSCRIPT} #echo "BACKUP FORMAT '${BKPLOC}/%d_%t_%s_%p.ctl' TAG='CONTROL_BKP' CURRENT CONTROLFILE;" >> ${RMANSCRIPT} echo "BACKUP ${COMPRESSED} FORMAT '${BKPLOC}/CONTROLFILE_%d_%I_%t_%s_%p.bkp' REUSE TAG='CONTROL_BKP' CURRENT CONTROLFILE;" >> ${RMANSCRIPT} echo "SQL \"ALTER DATABASE BACKUP CONTROLFILE TO TRACE AS ''${BKPLOC}/controlfile.trc'' REUSE\";" >> ${RMANSCRIPT} echo "SQL \"CREATE PFILE=''${BKPLOC}/init${ORACLE_SID}.ora'' FROM SPFILE\";" >> ${RMANSCRIPT} echo "}" >> ${RMANSCRIPT} echo "RMAN BACKUP SCRIPT CREATED." echo sleep 1 echo "Backup Location is: ${BKPLOC}" echo sleep 1 echo "Starting Up RMAN Backup Job ..." echo sleep 1 echo "#!/bin/bash" > ${RMANSCRIPTRUNNER} echo "nohup ${ORACLE_HOME}/bin/rman target / cmdfile=${RMANSCRIPT} | tee ${RMANLOG} 2>&1 &" >> ${RMANSCRIPTRUNNER} chmod 740 ${RMANSCRIPTRUNNER} source ${RMANSCRIPTRUNNER} echo echo " The RMAN backup job is currently running in the background. Disconnecting the current session will NOT interrupt the backup job :-)" echo " Now, viewing the backup job log:" echo echo "Backup Location is: ${BKPLOC}" echo "Check the LOGFILE: ${RMANLOG}" echo # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/goldengate_lag_mon.sh 0000740 0152073 0152061 00000017351 13526474761 016632 0 ustar oracle oinstall # #################################################################################################################### # This Script Detects GOLDENGATE LAG If The LAG Hits the Pre-defined Threshold # [Ver 1.0] # # To get this script work you need to Define the following variables: # ORACLE_HOME # Must be set to the ORACLE_HOME path of the database where GoldenGate is running against. # GG_HOME # Should be set to the Goldengate installation home directory path. # LAG=xxxx # The number of minutes of lag, if reached an email alert will be sent [10 minutes is the default]. # EXL_PROC_NAME="DONOTREMOVE|REP11|REP12" In case you want to exclude specific processes e.g. REP11 & REP12 # LOG_DIR # The location of script logs [/tmp by default]. # # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 26-02-17 # # # # # # Modified: # # # # # # # # # # # # # # #################################################################################################################### MAIL_LIST="youremail@yourcompany.com" export MAIL_LIST case ${MAIL_LIST} in "youremail@yourcompany.com") echo echo "******************************************************************" echo "Buddy! You forgot to edit line# 30 in the script." echo "Please replace youremail@yourcompany.com with your E-mail address." echo "******************************************************************" echo esac SERVER_NAME=`uname -n` export SERVER_NAME # ########################################### # Mandatory Parameters To Be Set By The User: # ########################################### ORACLE_HOME= # ORACLE_HOME path of the database where GoldenGate is running against. GG_HOME= # GoldenGate Installation Home path. e.g. GG_HOME=/goldengate/gghome # ################ # Script Settings: # ################ # LAG THRESHOLD in minutes: [If reached an e-mail alert will be sent. Default 10 minutes] LAG_IN_MINUTES=10 # Excluded Specific PROCESSES NAME: # e.g. If you want to exclude two replicate processes with names REP_11 and REP_12 from being reported then add them to below parameter as shown: # EXL_PROC_NAME="DONOTREMOVE|REP_11|REP_12" EXL_PROC_NAME="DONOTREMOVE" # ############### # VARIABLES: # ############### LOG_DIRECTORY=/tmp # Log Location LAG=$((LAG_IN_MINUTES * 100)) export LAG export EXL_PROC_NAME # ############################################# # Finding GoldenGate Installation Home Location: [In case the user didn't set it up above] # ############################################# if [ ! -f ${GG_HOME}/ggsci ] then GG_PID=`pgrep -lf mgr.prm|awk '{print $1}'` export GG_PID GG_HOME=`pwdx ${GG_PID}|awk '{print $NF}'` export GG_HOME fi if [ ! -f ${GG_HOME}/ggsci ] then GG_HOME=`ps -ef|grep "./mgr"|grep -v grep|awk '{print $10}'|sed -e 's/\/dirprm\/mgr\.prm//g'|grep -v sed|grep -v "//g"|tail -1` export GG_HOME fi if [ ! -f ${GG_HOME}/ggsci ] then echo "The script cannot find GoldenGate installation home path, please export it inside the script just before \"VARIABLES\" section" echo "e.g." echo "export GG_HOME=/u01/goldengate" fi # ############### # Script Engine: # ############### # ################### # Getting ORACLE_HOME: [In case the user didn't set it up above] # ################### if [ -z ${ORACLE_SID} ] then ORACLE_SID=`ps -ef|grep pmon|grep -v grep|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g"|tail -1` export ORACLE_SID fi ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable inside this script in order to get it run properly." echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" mail -s "goldengate_lag_mon script failed on Server [${SRV_NAME}] due to the failure of finding ORACLE_HOME, Please export ORACLE_HOME variable inside the script" ${MAIL_LIST} < /dev/null exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib echo LD_LIBRARY_PATH is: $LD_LIBRARY_PATH # ################################################ # Checking the LAG status from Goldengate Console: # ################################################ for GREP_SERVICE in EXTRACT REPLICAT do export GREP_SERVICE export LOG_DIR=${LOG_DIRECTORY} export LOG_FILE=${LOG_DIR}/${GREP_SERVICE}_lag_mon.log # Identify lagging operation name: case ${GREP_SERVICE} in "REPLICAT") LAST_COL_OPNAME="RECEIVING" export LAST_COL_OPNAME BFR_LAST_COL_OPNAME="APPLYING" export BFR_LAST_COL_OPNAME ;; "EXTRACT") LAST_COL_OPNAME="SENDING" export LAST_COL_OPNAME BFR_LAST_COL_OPNAME="EXTRACTING" export BFR_LAST_COL_OPNAME ;; esac $GG_HOME/ggsci << EOF |grep "${GREP_SERVICE}" > ${LOG_FILE} info all exit EOF # ################################ # Email Notification if LAG Found: # ################################ for i in `cat ${LOG_FILE}|egrep -v ${EXL_PROC_NAME}|awk '{print $NF}'|sed -e 's/://g'` do if [ $i -ge ${LAG} ] then mail -s "Goldengate LAG detected in ${LAST_COL_OPNAME} TRAIL FILES on Server [${SERVER_NAME}]" ${MAIL_LIST} < ${LOG_FILE} echo "Goldengate LAG detected in ${LAST_COL_OPNAME} TRAIL FILES on Server [${SERVER_NAME}]" fi done for i in `cat ${LOG_FILE}|egrep -v ${EXL_PROC_NAME}|awk '{print $(NF-1)}'|sed -e 's/://g'` do if [ $i -ge ${LAG} ] then mail -s "Goldengate LAG detected in ${BFR_LAST_COL_OPNAME} TRAIL FILES on Server [${SERVER_NAME}]" ${MAIL_LIST} < ${LOG_FILE} echo "Goldengate LAG detected in ${BFR_LAST_COL_OPNAME} TRAIL FILES on Server [${SERVER_NAME}]" fi done done # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/db_jobs.sh 0000740 0152073 0152061 00000030746 13775601357 014431 0 ustar oracle oinstall # ################################################# # Script to Check Scheduled Jobs. # # # # Author: Mahmmoud ADEL # # # # ### # Created: 02-02-10 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # 14-05-14 Add AUTOTASK MAINT WINDO # 29-11-15 Add Last Run Details # # ################################################# SCRIPT_NAME="db_jobs" # ########### # Description: # ########### echo echo "==============================================" echo "This script Checks ALL database Scheduled Jobs ..." echo "==============================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi # if [ -z "${REPLY##[0-9]*}" ] # then # export ORACLE_SID=$DB_ID # echo Selected Instance: # echo $DB_ID # break # else # export ORACLE_SID=${REPLY} # break # fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ############################### # SQLPLUS: Check Scheduled Jobs: # ############################### ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 200 set pages 1000 PROMPT DBMS_JOBS: PROMPT ----------- col LAST_RUN for a25 col NEXT_RUN for a25 select job,schema_user,failures,to_char(LAST_DATE,'DD-Mon-YYYY hh24:mi:ss')LAST_RUN,to_char(NEXT_DATE,'DD-Mon-YYYY hh24:mi:ss')NEXT_RUN from dba_jobs; PROMPT PROMPT DBMS_SCHEDULER: PROMPT ---------------- col "OWNER.JOB_NAME" for a39 col STATE for a9 col FAILURE_COUNT for 9999 heading 'Fail' col "DURATION(d:hh:mm:ss)" for a10 col REPEAT_INTERVAL for a41 col LAST_RUN for a20 col NEXT_RUN for a20 --col LAST_START_DATE for a40 --select JOB_NAME,OWNER,ENABLED,STATE,FAILURE_COUNT,to_char(LAST_START_DATE,'DD-Mon-YYYY hh24:mi:ss')LAST_RUN,to_char(NEXT_RUN_DATE,'DD-Mon-YYYY hh24:mi:ss')NEXT_RUN,REPEAT_INTERVAL, select OWNER||'.'||JOB_NAME "OWNER.JOB_NAME",ENABLED,STATE,FAILURE_COUNT,to_char(LAST_START_DATE,'DD-Mon-YYYY hh24:mi:ss TZR')LAST_RUN,to_char(NEXT_RUN_DATE,'DD-Mon-YYYY hh24:mi:ss TZR')NEXT_RUN,REPEAT_INTERVAL, extract(day from last_run_duration) ||':'|| lpad(extract(hour from last_run_duration),2,'0')||':'|| lpad(extract(minute from last_run_duration),2,'0')||':'|| lpad(round(extract(second from last_run_duration)),2,'0') "DURATION(d:hh:mm:ss)" from dba_scheduler_jobs order by ENABLED,STATE,"OWNER.JOB_NAME"; PROMPT PROMPT AUTOTASK INTERNAL MAINTENANCE WINDOWS: PROMPT --------------------------------------- col WINDOW_NAME for a17 col NEXT_RUN for a20 col ACTIVE for a6 col OPTIMIZER_STATS for a15 col SEGMENT_ADVISOR for a15 col SQL_TUNE_ADVISOR for a16 col HEALTH_MONITOR for a15 SELECT WINDOW_NAME,TO_CHAR(WINDOW_NEXT_TIME,'DD-MM-YYYY HH24:MI:SS') NEXT_RUN,AUTOTASK_STATUS STATUS,WINDOW_ACTIVE ACTIVE,OPTIMIZER_STATS,SEGMENT_ADVISOR,SQL_TUNE_ADVISOR FROM DBA_AUTOTASK_WINDOW_CLIENTS; PROMPT PROMPT FAILED JOBS IN THE LAST 24H: PROMPT ---------------------------- col LOG_DATE for a36 col OWNER for a15 col JOB_NAME for a35 col STATUS for a11 col RUN_DURATION for a20 select JOB_NAME,OWNER,LOG_DATE,STATUS,ERROR#,RUN_DURATION from DBA_SCHEDULER_JOB_RUN_DETAILS where STATUS='FAILED' and LOG_DATE > sysdate-1 order by JOB_NAME,LOG_DATE; PROMPT RUNNING JOBS DETAILS: PROMPT --------------------- col INS for 999 col "OWNER.JOB_NAME|OSPID|SID" for a45 col ELAPSED_TIME for a17 col CPU_USED for a17 col "WAIT_SEC" for 9999999999 col WAIT_CLASS for a15 col "BLKD_BY" for 9999999 col "WAITED|WCLASS|EVENT" for a45 select j.RUNNING_INSTANCE INS,j.OWNER||'.'||j.JOB_NAME ||' | '||SLAVE_OS_PROCESS_ID||'|'||j.SESSION_ID"OWNER.JOB_NAME|OSPID|SID" ,s.FINAL_BLOCKING_SESSION "BLKD_BY",ELAPSED_TIME,CPU_USED ,substr(s.SECONDS_IN_WAIT||'|'||s.WAIT_CLASS||'|'||s.EVENT,1,45) "WAITED|WCLASS|EVENT",S.SQL_ID from dba_scheduler_running_jobs j, gv\$session s where j.RUNNING_INSTANCE=S.INST_ID(+) and j.SESSION_ID=S.SID(+) order by "OWNER.JOB_NAME|OSPID|SID",ELAPSED_TIME; EOF echo "Enter the JOB_NAME/ID to get its details/DDL/Run History:" echo "=========================================================" read JOB_NAME # Exit if No Input: if [ -z "${JOB_NAME}" ] then # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi exit fi # Check if the variable is Number query DBMS_JOBS: if [ -z "${JOB_NAME##[0-9]*}" ] then ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF col what for a157 Select what from dba_jobs where job='$JOB_NAME'; EOF # If variable is Characters query dba_scheduler_jobs: else JOB_OWNER_TMP=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; col what for a157 prompt select * from (Select owner from dba_scheduler_jobs where job_name='${JOB_NAME}') where rownum=1; EOF ) JOB_OWNER=`echo ${JOB_OWNER_TMP}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` export JOB_OWNER ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 200 pages 1000 col OWNER for a10 col STATE for a11 col FAILURE_COUNT for 999 heading 'Fail' col "DURATION(d:hh:mm:ss)" for a22 col REPEAT_INTERVAL for a60 --col LAST_START_DATE for a40 col NEXT_RUN for a21 col "STICK|INST" for a10 select JOB_NAME,OWNER,ENABLED,STATE,FAILURE_COUNT,to_char(LAST_START_DATE,'DD-Mon-YYYY hh24:mi:ss')LAST_RUN,REPEAT_INTERVAL,to_char(NEXT_RUN_DATE,'DD-Mon-YYYY hh24:mi:ss')NEXT_RUN, extract(day from last_run_duration) ||':'|| lpad(extract(hour from last_run_duration),2,'0')||':'|| lpad(extract(minute from last_run_duration),2,'0')||':'|| lpad(round(extract(second from last_run_duration)),2,'0') "DURATION(d:hh:mm:ss)" ,INSTANCE_STICKINESS||'|'||INSTANCE_ID "STICK|INST" from dba_scheduler_jobs where JOB_NAME='$JOB_NAME'; prompt Last Run Details: prompt ----------------- col END_DATE for a20 col START_DATE for a20 col CPU_USED for a17 col OWNER for a15 col JOB_NAME for a40 col STATUS for a11 col RUN_DURATION for a20 select TO_CHAR(ACTUAL_START_DATE,'DD-MON-YY HH24:MI:SS') START_DATE,TO_CHAR(LOG_DATE,'DD-MON-YY HH24:MI:SS') END_DATE,RUN_DURATION,OWNER,JOB_NAME,STATUS,ERROR#,CPU_USED from DBA_SCHEDULER_JOB_RUN_DETAILS where JOB_NAME='$JOB_NAME' and LOG_DATE > sysdate-10 order by LOG_DATE; prompt prompt Job Action: prompt ----------- set long 9999999 col JOB_DDL for a200 col "EXECUTED_PROGRAM | JOB_ACTION" for a40 Select COMMENTS,PROGRAM_OWNER||'.'||PROGRAM_NAME||' | '||JOB_ACTION "EXECUTED_PROGRAM | JOB_ACTION" from dba_scheduler_jobs where JOB_NAME='$JOB_NAME'; select dbms_metadata.get_ddl('PROCOBJ', '${JOB_NAME}','${JOB_OWNER}') JOB_DDL from dual; EOF fi # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/import_data.sh 0000700 0152073 0152061 00000130230 14106473236 015303 0 ustar oracle oinstall # ############################################################################################################################### # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # THE AUTHOR WILL NOT BE HELD RESPONSIBLE TO ANY PERSON OR ENTITY WITH RESPECT TO ANY DATA LOSS OR DAMAGES CAUSED BY THIS SCRIPT. # # Ver: 1.1 # This script help with importing data using impdp. # # # # # # Author: Mahmmoud ADEL # # # # ### # # # # # # # Created: 22-12-2020 # Modified: 31-12-2020 Allow turning OFF the FLASHBACK mode during the import. # 31-12-2020 Delay the drop of the importer user DBA_BUNDLE7 for 5 sec as some slow workers may not yet cleaned up. # # # # ############################################################################################################################### # ########### # Description: # ########### export SRV_NAME="`uname -n`" echo echo "==================================================================" echo "THIS SCRIPT HELP WITH IMPORTING DATA ON DATABASE | SCHEMA | TABLE." echo "==================================================================" echo sleep 1 echo "" echo "DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED \"AS IS\"." echo "THE AUTHOR WILL NOT BE HELD RESPONSIBLE TO ANY PERSON OR ENTITY WITH RESPECT TO ANY DATA LOSS OR DAMAGES CAUSED BY THIS SCRIPT." echo "" echo "Do you agree to continue? [YES | NO]" echo "=========================" while read DISCLAIMER do case ${DISCLAIMER} in Y|y|yes|YES|Yes) echo; break;; N|n|no|NO|No|NE) echo; echo "Nothing wrong with being on the safe side :-)";echo "Please test this script on a test environment first to be more confident with it.";echo "SCRIPT TERMINATED! "; echo; exit;; *) echo "Please Enter a valid answer: [YES|NO]";; esac done echo "Provide the DIRECTORY FULL LOCATION PATH where the export file located: [e.g. /backup/export]" echo "=======================================================================" while read DUMPDIRPATH do case ${DUMPDIRPATH} in '') export DUMPDIRPATH=`pwd`; echo "DIRECTORY TRANSLATED TO: ${DUMPDIRPATH}";; '.') export DUMPDIRPATH=`pwd`; echo "DIRECTORY TRANSLATED TO: ${DUMPDIRPATH}";; '~') export DUMPDIRPATH=${HOME}; echo "DIRECTORY TRANSLATED TO: ${DUMPDIRPATH}";; esac if [[ -d "${DUMPDIRPATH}" ]] && [[ -r "${DUMPDIRPATH}" ]] && [[ -w "${DUMPDIRPATH}" ]] then export DUMPDIR="${DUMPDIRPATH}"; break else echo; printf "`echo "Please make sure that oracle user has"` `echo -e "\033[33;5mREAD/WRITE\033[0m"` `echo "permissions on the provided directory."`\n"; echo; echo "Enter the complete PATH where the dump file is located: [e.g. /backup/export]" fi done echo "" echo "Provide the EXPORT FILE name: [The dump file name to import from]" echo "=============================" echo "For multiple dump files separate them by comma: e.g. dump01.dmp,dump02.dmp" echo "For multiple dump files in sequence, replace the sequence number with *: e.g. dump*.dmp" echo while read DUMPFILE do case ${DUMPFILE} in "") echo "You MISSED to Enter the export file name!"; echo; echo "Provide the EXPORT FILE name: [e.g. dump01.dmp]";; */*) echo; echo "Enter the FILE NAME only NOT the full path!"; echo; echo "Provide the EXPORT FILE name: [e.g. dump01.dmp]";; *) export DUMPFILENAME="$(sed s/*/%U/g <<<${DUMPFILE})"; echo; echo "File Name is: ${DUMPFILE}"; break;; esac done #if [ -f ${DUMPFILE} ]; then #export VALID_DUMP=`strings {${DUMPFILEPATH}} | head -1 | grep 'EXPORT' | wc -l` #export LEGACY_MODE=`strings {${DUMPFILEPATH}} | head -1 | grep 'EXPORT:' | wc -l` #export TABLE_EXPORT_MODE=`strings {${DUMPFILEPATH}} | head -1 | grep TABLE | wc -l` #export DUMPDIR="${DUMPFILEPATH%/*}" #export DUMPFILENAME="${DUMPFILEPATH##*/}" # break;; #else # echo "File not found or not accessible!" # echo # echo "Please Enter a valid path, or make sure it's readable by Oracle user:" # echo "=====================================================================" # ;; #fi # Warning if the file is not a valid Import file: # if [ ${VALID_DUMP} -ne 1 ] # then # echo # echo "WARNING: The provided file doesn't sound like a valid EXPORT file! " # echo # fi # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Instances: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! echo Please start the database first. exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To IMPORT the data to: [Enter the number]" echo "---------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated! " exit fi # ######################## # Getting ORACLE_BASE: # ######################## # Get ORACLE_BASE from user's profile if not set: if [ -z "${ORACLE_BASE}" ] then ORACLE_BASE=`grep -h 'ORACLE_BASE=\/' ${USR_ORA_HOME}/.bash* ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi # ########################### # INSTANCE OPEN MODE CHECKING: # ########################### INSTANCE_STATUS_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT STATUS FROM V\$INSTANCE; EOF ) INSTANCE_STATUS=`echo ${INSTANCE_STATUS_RAW}| awk '{print $NF}'` case ${INSTANCE_STATUS} in "OPEN") echo ;; *) echo;echo "ERROR: INSTANCE [${ORACLE_SID}] IS IN STATUS: ${INSTANCE_STATUS} !" echo;echo "PLEASE FIRST OPEN INSTANCE [${ORACLE_SID}] THEN RE-RUN THIS SCRIPT.";echo; exit ;; esac # ################### # Checking DB Version: # ################### DB_VER_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${PARFILE} echo "directory=EXPORT_FILES_DBA_BUNDLE" >> ${PARFILE} echo "dumpfile=${DUMPFILENAME}" >> ${PARFILE} echo "logfile=import_${IMPORT_MODE}_on_${ORACLE_SID}_${DUMPDATE}.log" >> ${PARFILE} if [ "${TABLE_IMPORT_MODE}" -eq 1 ] then # ENTER TABLE IMPORT MODE: echo "Enter the TABLE NAMES you want to IMPORT: [Leave it BLANK and hit ENTER to import ALL TABLES in the Export file]" echo "========================================" echo "i.e. SCOTT.EMP,HR.DEPARTMENTS" echo "" while read LISTOFTABLESVAR do case ${LISTOFTABLESVAR} in "") echo; export LISTOFTABLES=""; break ;; *) echo; export LISTOFTABLES="TABLES=${LISTOFTABLESVAR}"; echo ${LISTOFTABLES} >> ${PARFILE}; break ;; esac done if [ -z ${LISTOFTABLESVAR} ] then echo "Enter the TABLE NAMES you want to EXCLUDE from this import job: [Leave it BLANK and hit ENTER to import ALL TABLES]" echo "==============================================================" echo "i.e. SCOTT.EMP,HR.DEPARTMENTS" echo "" while read EXCLUDETABLEVAR do case ${EXCLUDETABLEVAR} in "") echo; export EXCLUDETABLE=""; break ;; *) echo; export EXCLUDETABLE="EXCLUDE=TABLE:\"IN('$(sed s/,/\',\'/g <<<${EXCLUDETABLEVAR}| tr '[:lower:]' '[:upper:]')')\"" echo ${EXCLUDETABLE} >> ${PARFILE}; break ;; esac done fi else echo "Enter the SCHEMA NAMES you want to IMPORT: [Leave it BLANK and hit ENTER to import FULL DATABASE or ALL SCHEMAS in the Export file]" echo "=========================================" echo "i.e. SCOTT,HR" echo "" while read LISTOFSCHEMASVAR do case ${LISTOFSCHEMASVAR} in "") echo; export LISTOFSCHEMAS=""; break ;; *) echo; export LISTOFSCHEMAS="SCHEMAS=${LISTOFSCHEMASVAR}"; echo ${LISTOFSCHEMAS} >> ${PARFILE}; break ;; esac done if [ -z ${LISTOFSCHEMASVAR} ] then echo "Enter the SCHEMA NAMES you want to EXCLUDE from this import job: [Leave it BLANK and hit ENTER to import ALL SCHEMAS]" echo "===============================================================" echo "i.e. ANONYMOUS,APPQOSSYS,AUDSYS,BI,CTXSYS,DBSNMP,DIP,DMSYS,DVF,DVSYS,EXDSYS,EXFSYS,GSMADMIN_INTERNAL,GSMCATUSER,GSMUSER,LBACSYS,MDSYS,MGMT_VIEW,MDDATA,MTSSYS,ODM,ODM_MTR,OJVMSYS,OLAPSYS,ORACLE_OCM,ORDDATA,ORDPLUGINS,ORDSYS,OUTLN,SI_INFORMTN_SCHEMA,SPATIAL_CSW_ADMIN,SPATIAL_CSW_ADMIN_USR,SPATIAL_WFS_ADMIN,SPATIAL_WFS_ADMIN_USR,SYS,SYSBACKUP,SYSDG,SYSKM,SYSMAN,SYSTEM,TSMSYS,WKPROXY,WKSYS,WK_TEST,WMSYS,XDB,XTISYS,DSSYS,PERFSTAT,REPADMIN,OEM_ADVISOR,OEM_MONITOR,OLAP_DBA,OLAP_USER,OWBSYS,OWBSYS_AUDIT,APEX_030200" echo "" while read EXCLUDESCHEMAVAR do case ${EXCLUDESCHEMAVAR} in "") echo; export EXCLUDESCHEMA=""; break ;; *) echo; export EXCLUDESCHEMA="EXCLUDE=SCHEMA:\"IN('$(sed s/,/\',\'/g <<<${EXCLUDESCHEMAVAR}| tr '[:lower:]' '[:upper:]')')\"" echo ${EXCLUDESCHEMA} >> ${PARFILE}; break ;; esac done fi # Enter TABLE MODE if the user specifies no SCHEMA: if [ -z ${LISTOFSCHEMASVAR} ] && [ -z ${EXCLUDESCHEMAVAR} ] then echo "Enter the TABLE NAMES you want to IMPORT: [Leave it BLANK and hit ENTER to import ALL TABLES in the Export file]" echo "========================================" echo "i.e. SCOTT.EMP,HR.DEPARTMENTS" echo "" while read LISTOFTABLESVAR do case ${LISTOFTABLESVAR} in "") echo; export LISTOFTABLES=""; break ;; *) echo; export LISTOFTABLES="TABLES=${LISTOFTABLESVAR}"; echo ${LISTOFTABLES} >> ${PARFILE}; break ;; esac done if [ -z ${LISTOFTABLESVAR} ] then echo "Enter the TABLE NAMES you want to EXCLUDE from this import: [Leave it BLANK and hit ENTER to import ALL TABLES]" echo "==========================================================" echo "i.e. SCOTT.EMP,HR.DEPARTMENTS" echo "" while read EXCLUDETABLEVAR do case ${EXCLUDETABLEVAR} in "") echo; export EXCLUDETABLE=""; break ;; *) echo; export EXCLUDETABLE="EXCLUDE=TABLE:\"IN('$(sed s/,/\',\'/g <<<${EXCLUDETABLEVAR}| tr '[:lower:]' '[:upper:]')')\"" echo ${EXCLUDETABLE} >> ${PARFILE}; break ;; esac done fi fi fi # REMAP SCHEMA section: echo "REMAP SCHEMAS or TABLES OWNER: [Leave it BLANK to keep SCHEMA NAMES | TABLES OWNER same as source]" echo "=============================" echo "SOURCE_SCHEMA:TARGET_SCHEMA i.e. If you want to import objects owned by HR to BLAKE schema:" echo "HR:BLAKE" echo "" while read REMAPSCHEMAVAR do case ${REMAPSCHEMAVAR} in "") echo; export REMAPSCHEMA=""; break ;; *:*) echo; export REMAPSCHEMA="REMAP_SCHEMA=${REMAPSCHEMAVAR}";echo ${REMAPSCHEMA} >> ${PARFILE}; break ;; *) echo; echo "Please REMAP the SCHEMA in a right format: i.e. SOURCE_SCHEMA_NAME:TARGET_SCHEMA_NAME";; esac done # REMAP TABLE section: echo "REMAP TABLE NAMES: [Leave it BLANK to keep TABLE NAMES same as source]" echo "=================" echo "OWNER.SOURCE_TABLE:TARGET_TABLE i.e. If you want to import table HR.EMPLOYEES as EMPX then enter it as follows:" echo "HR.EMPLOYEES:EMPX" echo "" while read REMAPTABLEVAR do case ${REMAPTABLEVAR} in "") echo; export REMAPTABLE=""; break ;; *:*) echo; export REMAPTABLE="REMAP_TABLE=${REMAPTABLEVAR}"; echo ${REMAPTABLE} >> ${PARFILE}; break ;; *) echo; echo "Please REMAP the TABLE in a right format: i.e. SOURCE_TABLE:TARGET_TABLE";; esac done # REMAP TABLESPACE section: echo "REMAP TABLESPACE: [Leave it BLANK to import the objects on same TABLESPACE NAME as source]" echo "=================" echo "SOURCE_TABLESPACE:TARGET_TABLESPACE" echo "i.e. If you want the imported objects to be created on EXAMPLE tablespace instead of USERS tablespace, then enter it as follows:" echo "USERS:EXAMPLE" echo "" while read REMAPTABLESPACEVAR do case ${REMAPTABLESPACEVAR} in "") echo; export REMAPTABLESPACE=""; break ;; *:*) echo; export REMAPTABLESPACE="REMAP_TABLESPACE=${REMAPTABLESPACEVAR}"; echo ${REMAPTABLESPACE} >> ${PARFILE}; break ;; *) echo; echo "Please REMAP the TABLESPACE in a right format: i.e. SOURCE_TABLESPACE:TARGET_TABLESPACE";; esac done # TABLE_EXISTS_ACTION SECTION: echo "TABLE_EXISTS_ACTION: Specify an action to be taken if the table is ALREADY EXIST: [[SKIP] | APPEND | REPLACE | TRUNCATE]" echo "================================================================================" echo "1. SKIP [IF TABLE IS ALREADY EXIST, SKIP ITS IMPORT AND LEAVE IT INTACT [DEFAULT]]" echo "2. APPEND [IF TABLE IS ALREADY EXIST, APPEND THE IMPORTED DATA TO THE TABLE AND LEAVE THE CURRENT DATA INTACT]" echo "3. REPLACE [IF TABLE IS ALREADY EXIST, DROP, RE-CREATE IT AND IMPORT NEW DATA, WHICH WILL DESTROY ITS CURRENT EXISTING DATA]" echo "4. TRUNCATE [IF TABLE IS ALREADY EXIST, TRUNCATE IT AND IMPORT NEW DATA, WHICH WILL DESTROY ITS CURRENT EXISTING DATA]" echo "" while read TABLEEXISTSACTIONVAR do case ${TABLEEXISTSACTIONVAR} in ""|1|SKIP|skip|Skip) export TABLEEXISTSACTION="TABLE_EXISTS_ACTION=SKIP"; echo ${TABLEEXISTSACTION} >> ${PARFILE} echo "SKIP MODE SELECTED | EXISTING DATA ON 'TABLES TO BE IMPORTED' WILL BE [PRESERVED]"; echo; break;; 2|APPEND|append|Append) export TABLEEXISTSACTION="TABLE_EXISTS_ACTION=APPEND"; echo ${TABLEEXISTSACTION} >> ${PARFILE} echo "APPEND MODE SELECTED | EXISTING DATA ON 'TABLES TO BE IMPORTED' WILL BE [PRESERVED]"; echo; break;; 3|REPLACE|replace|Replace) export TABLEEXISTSACTION="TABLE_EXISTS_ACTION=REPLACE"; echo ${TABLEEXISTSACTION} >> ${PARFILE} printf "`echo "REPLACE MODE SELECTED | EXISTING DATA ON 'TABLES TO BE IMPORTED' WILL BE ["` `echo -e "\033[33;5mDESTROYED\033[0m"` `echo "]"`\n"; echo; break;; 4|TRUNCATE|truncate|Truncate) echo; export TABLEEXISTSACTION="TABLE_EXISTS_ACTION=TRUNCATE"; echo ${TABLEEXISTSACTION} >> ${PARFILE} printf "`echo "TRUNCATE MODE SELECTED | EXISTING DATA ON 'TABLES TO BE IMPORTED' WILL BE ["` `echo -e "\033[33;5mDESTROYED\033[0m"` `echo "]"`\n"; echo; break;; *) echo; echo "Please Enter a valid NUMBER between 1 to 4";; esac done # CONTENT SECTION: echo "Specify if you want to import DATA or METADATA(DDLs) or both: [[DATA+METADATA] | METADATA_ONLY | DATA_ONLY]" echo "============================================================" echo "1. DATA+METADATA (ALL) [DEFAULT]" echo "2. METADATA_ONLY" echo "3. DATA_ONLY" echo "" while read CONTENTVAR do case ${CONTENTVAR} in ""|1|DATA+METADATA|data+metadata|DATAMETADATA|all|ALL) export CONTENT="CONTENT=ALL"; echo ${CONTENT} >> ${PARFILE}; echo ${CONTENT}; echo; break;; 2|METADATA|METADATA_ONLY|metadata|metadata_only) export CONTENT="CONTENT=METADATA_ONLY"; echo ${CONTENT} >> ${PARFILE}; echo ${CONTENT}; echo; break;; 3|DATA|data|DATA_ONLY|data_only|dataonly|DATAONLY) export CONTENT="CONTENT=DATA_ONLY"; echo ${CONTENT} >> ${PARFILE}; echo ${CONTENT}; echo; break;; *) echo; echo "Please Enter a valid NUMBER between 1 to 3";; esac done # INCLUDE ONLY SPECIFIC OBJECTS AND DENY THE OTHERS: echo "Specify if you want to import ONLY specific objects and IGNORE the rest in the dump file: [Leave it BLANK to include all objects in the dump file]" echo "========================================================================================" echo "Note: TABLE option is valid ONLY in FULL & SCHEMA import modes." echo "e.g. To import ONLY specific object types, separate them by comma: TABLE,INDEX,CONSTRAINT,REF_CONSTRAINT,TRIGGER,PROCEDURE,PACKAGE,FUNCTION,..." echo "e.g. You can IMPORT ONLY the INDEXES starting with name PROD by typing: INDEX:\"LIKE 'PROD%'\"" echo "" while read INCLUDEOBJECTSVAR do case ${INCLUDEOBJECTSVAR} in "") echo; export INCLUDEOBJECTS=""; break;; *) echo; export INCLUDEOBJECTS="INCLUDE=${INCLUDEOBJECTSVAR}"; echo ${INCLUDEOBJECTS} >> ${PARFILE}; echo; echo "EXCLUDE option will not be shown because INCLUDE option is used, whereas both options are mutually exclusive.";echo;break;; esac done # Hide the following EXCLUDE options if INCLUDE is used, because INCLUDE & EXCLUDE are mutually exclusive: if [ -z "${INCLUDEOBJECTSVAR}" ] then # EXCLUDE OTHER OBJECT TYPES: echo "Specify if you want to EXCLUDE specific object types from this import: [Leave it BLANK to include all objects in the dump file]" echo "=====================================================================" echo "Note: TABLE option is valid ONLY in FULL & SCHEMA import modes." echo "e.g. you can exclude one or more object type separating with comma: TABLE,INDEX,CONSTRAINT,REF_CONSTRAINT,TRIGGER,PROCEDURE,PACKAGE,FUNCTION,..." echo "e.g. you can exclude all tables start with name TEMP: TABLE:\"LIKE 'TEMP%'\"" echo "" while read EXCLUDEOTHEROBJECTSVAR do case ${EXCLUDEOTHEROBJECTSVAR} in "") echo; export EXCLUDEOTHEROBJECTS=""; break;; *) echo; export EXCLUDEOTHEROBJECTS="EXCLUDE=${EXCLUDEOTHEROBJECTSVAR}"; echo ${EXCLUDEOTHEROBJECTS} >> ${PARFILE}; break;; esac done # EXCLUDE GRANTS SECTION: echo "Do you want to import the OBJECT PRIVILEGES? [[YES] | NO]" echo "============================================" echo "" while read GRANTSVAR do case ${GRANTSVAR} in ""|YES|Yes|yes|y|Y) echo; export GRANTS=""; break;; NO|No|no|n|N) echo; export GRANTS="EXCLUDE=OBJECT_GRANT"; echo ${GRANTS} >> ${PARFILE}; break;; *) echo; echo "Please Enter a valid ANSWER YES or NO:";; esac done # EXCLUDE STATISTICS SECTION: echo "Do you want to import the STATISTICS? [[YES] | NO]" echo "=====================================" echo "" while read STATISTICSVAR do case ${STATISTICSVAR} in ""|YES|Yes|yes|Y|y) echo; export STATISTICS=""; break;; NO|No|no|N|n) echo; export STATISTICS="EXCLUDE=STATISTICS"; echo ${STATISTICS} >> ${PARFILE}; break;; *) echo; echo "Please Enter a valid ANSWER YES or NO:";; esac done fi echo -e "\033[33;5m[IMPDP PERFORMANCE SETTINGS]\033[0m";echo # PARALLEL SECTION: # If database edition support the PARALLEL option: if [ "${CHK_PARALLELISM_OPTION}" -eq 1 ] then # Get the CPU Count on the machine: case `uname` in Linux ) export CPUCOUNT=`cat /proc/cpuinfo| grep processor|wc -l`;; AIX ) export CPUCOUNT=`lsdev -C|grep Process|wc -l`;; SunOS ) export CPUCOUNT=`kstat cpu_info|grep core_id|sort -u|wc -l`;; HP-UX) export CPUCOUNT=`lsdev -C|grep Process|wc -l`;; esac echo "Enter the PARALLELISM DEGREE if you want to run the import in PARALLEL: [Leave it BLANK for NO PARALLEL | CPU COUNT is: ${CPUCOUNT}]" echo "======================================================================" echo "" while read PARALLELDEGREEVAR do case ${PARALLELDEGREEVAR} in "") echo; export PARALLELDEGREE=""; break;; *[!0-9]*) echo "Please enter a valid NUMBER:";; *) echo; export PARALLELDEGREE="PARALLEL=${PARALLELDEGREEVAR}"; echo ${PARALLELDEGREE} >> ${PARFILE}; break;; esac done fi # CLUSTER SECTION: # If cluster detected and other instances are open: if [ "${RAC_ACTIVE}" -eq 1 ] then echo "Do you want to BALANCE the import load between RAC nodes? [YES | [NO]] [Note: The dumpfile should be located on a SHARED location]" echo "=========================================================" echo "" while read CLUSTERVAR do case ${CLUSTERVAR} in ""|N|n|NO|no) echo; export CLUSTER=""; break;; Y|y|YES|yes) echo; export CLUSTER="CLUSTER=YES"; echo ${CLUSTER} >> ${PARFILE}; break;; *) echo "Please enter a valid answer: [YES|NO]";; esac done fi # If DB Version is 12c+: if [ ${DB_VER} -gt 11 ] then # Disable ARCHIVE LOGGING for the import: echo "Perform the import in NOLOGGING mode? [[YES] | NO] [NOT RECOMMENDED to use NOLOGGING if this DB is DataGuarded by a STANDBY DB]" echo "=====================================" echo "Note: Only the import operation will run in NOLOGGING mode by setting TRANSFORM=DISABLE_ARCHIVE_LOGGING:Y" echo "" while read ARCHIVELOGGINGVAR do case ${ARCHIVELOGGINGVAR} in N|n|NO|no) echo; export ARCHIVELOGGING=""; break;; ""|Y|y|YES|yes) export ARCHIVELOGGING="TRANSFORM=DISABLE_ARCHIVE_LOGGING:Y"; echo ${ARCHIVELOGGING} >> ${PARFILE};echo "TRANSFORM=DISABLE_ARCHIVE_LOGGING mode activated.";echo; break;; *) echo "Please enter a valid answer: [YES|NO]";; esac done # Enable ADDITIONAL PARAMETERS for 12c+: # Enable LOGTIME: [Timed Log Records] echo "LOGTIME=all" >> ${PARFILE} # Enable METRICS: [Detailed log] echo "METRICS=YES" >> ${PARFILE} # Enable STATUS update every 30sec: #echo "STATUS=30" >> ${PARFILE} fi echo -e "\033[33;5m[DATABASE PERFORMANCE SETTINGS]\033[0m";echo # Disable FORCE LOGGING mode: # If FORCE LOGGING is ENABLED: if [ "${FORCE_LOGGING}" -eq 1 ] then echo "FORCE LOGGING mode is ENABLED | Do you want to DISABLE it during the import? [YES | [NO]] [NOT RECOMMENDED to disable if this DB is DataGuarded by a STANDBY DB]" echo "============================================================================" echo "NOTE: If you choose to disable it, the script will automatically reset it to its original setting and enable it back after the import." echo "" while read FORCELOGGINGVAR do case ${FORCELOGGINGVAR} in ""|N|n|NO|no) echo; export FORCELOGGING=""; break;; Y|y|YES|yes) export FORCELOGGING="ALTER DATABASE NO FORCE LOGGING;";PRESERVEFORCELOGGING="ALTER DATABASE FORCE LOGGING;"; echo "FORCE LOGGING mode will be disabled during the import and will be enabled back after the import."; echo; break;; *) echo "Please enter a valid answer: [YES|NO]";; esac done fi # Disable FLASHBACK mode: # If FLASHBACK mode is ENABLED: if [ "${FLASHBACK_ACTIVE}" -eq 1 ] then echo "FLASHBACK mode is ENABLED | Do you want to DISABLE it during the import? [[YES] | NO]" echo "========================================================================" echo "NOTE: If you choose to disable it, the script will automatically reset it to its original setting and enable it back after the import." echo "" while read FLASHBACKVAR do case ${FLASHBACKVAR} in N|n|NO|no) echo; export FLASHBACK=""; break;; ""|Y|y|YES|yes) export FLASHBACK="ALTER DATABASE FLASHBACK OFF;";PRESERVEFLASHBACK="ALTER DATABASE FLASHBACK ON;"; echo "FLASHBACK mode will be disabled during the import and will be enabled back after the import."; echo; break;; *) echo "Please enter a valid answer: [YES|NO]";; esac done fi # Disable of DB_BLOCK_CHECKING: # IF DB_BLOCK_CHECKING_VAL=TRUE if [ "${DB_BLOCK_CHECKING_VAL}" = "TRUE" ] then echo "DB_BLOCK_CHECKING is set to TRUE, Do you want to DISABLE it to speed up the import? [[YES] | NO]" echo "===================================================================================" echo "NOTE: If you choose to disable it, the script will automatically reset it to its original setting and enable it back after the import." echo "" while read DBBLOCKCHECKINGVAR do case ${DBBLOCKCHECKINGVAR} in N|n|NO|no) echo; export DBBLOCKCHECKING=""; break;; ""|Y|y|YES|yes) export DBBLOCKCHECKING="ALTER SYSTEM SET db_block_checking=FALSE SCOPE=MEMORY;"; export PRESERVEDBBLOCKCHECKING="ALTER SYSTEM SET db_block_checking=TRUE;";echo "DB_BLOCK_CHECKING will be disabled during the import and will be enabled back after the import."; echo; break;; *) echo "Please enter a valid answer: [YES|NO]";; esac done fi # Disable of DB_BLOCK_CHECKSUM: # IF DB_BLOCK_CHECKSUM_VAL=TRUE if [ "${DB_BLOCK_CHECKSUM_VAL}" = "TYPICAL" ] || [ "${DB_BLOCK_CHECKSUM_VAL}" = "FULL" ] then echo "DB_BLOCK_CHECKSUM is set to TRUE, Do you want to DISABLE it to speed up the import? [[YES] | NO]" echo "===================================================================================" echo "NOTE: If you choose to disable it, the script will automatically reset it to its original setting and enable it back after the import." echo "" while read DBBLOCKCHECKSUMVAR do case ${DBBLOCKCHECKSUMVAR} in N|n|NO|no) echo; export DBBLOCKCHECKSUM=""; break;; ""|Y|y|YES|yes) export DBBLOCKCHECKSUM="ALTER SYSTEM SET db_block_checksum=OFF SCOPE=MEMORY;"; export PRESERVEDBBLOCKCHECKSUM="ALTER SYSTEM SET db_block_checksum=${DB_BLOCK_CHECKSUM_VAL};";echo "DB_BLOCK_CHECKSUM will be disabled during the import and will be enabled back after the import."; echo; break;; *) echo "Please enter a valid answer: [YES|NO]";; esac done fi echo echo "You are almost done!"; echo echo "Hint: Make sure that TEMPORARY & UNDO Tablespaces along with UNDO_RETENTION Parameter are big enough to support this import operation." echo "" sleep 1 echo "Please verify the import settings summary:" echo "------------------------------------------" cat ${PARFILE} echo sleep 2 echo "Shall we start the IMPORT now? [[YES] | NO]" echo "==============================" while read STARTNOW do case ${STARTNOW} in N|n|NO|no) echo; echo "SCRIPT TERMINATED! "; echo; exit;; ""|Y|y|YES|yes) echo; echo "STARTING THE IMPORT ..."; echo; break;; *) echo "Please enter a valid answer: [YES|NO]";; esac done VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SPOOL ${STGDIR}/user_creation.log PROMPT CREATE USER DBA_BUNDLEEXP7 [IMPORTER USER] (WILL BE DROPPED AFTER THE IMPORT) ... CREATE USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; ALTER USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; GRANT CREATE SESSION TO DBA_BUNDLEEXP7; GRANT DBA TO DBA_BUNDLEEXP7; -- The following privileges to workaround Bug 6392040: GRANT EXECUTE ON SYS.DBMS_DEFER_IMPORT_INTERNAL TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_EXPORT_EXTENSION TO DBA_BUNDLEEXP7; PROMPT PROMPT CREATING DIRECTORY EXPORT_FILES_DBA_BUNDLE POINTING TO ${DUMPDIR} ... CREATE OR REPLACE DIRECTORY EXPORT_FILES_DBA_BUNDLE AS '${DUMPDIR}'; PROMPT PROMPT DISABLING DB FEATURES TO SPEED UP THE IMPORT: [will be enabled back after the import] ${FORCELOGGING} ${FLASHBACK} ${DBBLOCKCHECKING} ${DBBLOCKCHECKSUM} PROMPT SPOOL OFF EOF ) echo # Creation of the Import Script: export LOGFILE="${STGDIR}/IMPORT_${IMPORT_MODE}_on_${ORACLE_SID}_${DUMPDATE}.log" export IMPORTSCRIPT=${STGDIR}/IMPORTSCRIPT.sh export IMPORTSCRIPTRUNNER=${STGDIR}/IMPORTSCRIPTRUNNER.sh echo "# IMPORT Script: [Created By DBA_BUNDLE]" > ${IMPORTSCRIPT} echo "echo ''" >>${IMPORTSCRIPT} echo "echo \"While the Import job is running, you can check the STATUS using:\"" >>${IMPORTSCRIPT} echo "echo \"--------------------------------------------------------------- \"" >>${IMPORTSCRIPT} echo "echo \"SELECT job_name, operation, job_mode, DEGREE, state FROM dba_datapump_jobs where OPERATION='IMPORT' and state='EXECUTING' and owner_name='DBA_BUNDLEEXP7';\"" >>${IMPORTSCRIPT} echo "echo ''" >>${IMPORTSCRIPT} echo "echo \"Then you can ATTACH to the import job and control it using:\"" >>${IMPORTSCRIPT} echo "echo \"---------------------------------------------------------- \"" >>${IMPORTSCRIPT} echo "echo \"impdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=\"" >>${IMPORTSCRIPT} echo "echo \"i.e.\"" >>${IMPORTSCRIPT} echo "echo \"impdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=SYS_IMPORT_${IMPORT_MODE}_01\"" >>${IMPORTSCRIPT} echo "echo \"To Show the STATUS:....... STATUS\"" >>${IMPORTSCRIPT} echo "echo \"To KILL the import:....... KILL_JOB\"" >>${IMPORTSCRIPT} echo "echo \"To PAUSE the import:...... STOP_JOB\"" >>${IMPORTSCRIPT} echo "echo \"To RESUME a paused import: START_JOB\"" >>${IMPORTSCRIPT} echo "export ORACLE_SID=${ORACLE_SID}" >>${IMPORTSCRIPT} echo "echo ''" >>${IMPORTSCRIPT} echo "echo 'Running The IMPORT Job Now ...'" >>${IMPORTSCRIPT} echo "${ORACLE_HOME}/bin/impdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" PARFILE=${PARFILE}" >>${IMPORTSCRIPT} echo "echo ''" >>${IMPORTSCRIPT} echo "echo 'Running Post IMPORT Steps ...'" >>${IMPORTSCRIPT} echo "echo ''" >>${IMPORTSCRIPT} echo "sleep 5" >>${IMPORTSCRIPT} echo "${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF" >>${IMPORTSCRIPT} echo "PROMPT" >>${IMPORTSCRIPT} echo "PROMPT DROPPING THE IMPORTER USER DBA_BUNDLEEXP7 (SAFELY) ..." >>${IMPORTSCRIPT} echo "DROP USER DBA_BUNDLEEXP7;" >>${IMPORTSCRIPT} echo "PROMPT PRESERVE ORIGINAL DB SETTINGS ..." >>${IMPORTSCRIPT} echo "${PRESERVEFORCELOGGING}" >>${IMPORTSCRIPT} echo "${PRESERVEFLASHBACK}" >>${IMPORTSCRIPT} echo "${PRESERVEDBBLOCKCHECKING}" >>${IMPORTSCRIPT} echo "${PRESERVEDBBLOCKCHECKSUM}" >>${IMPORTSCRIPT} echo "EOF" >>${IMPORTSCRIPT} echo "export JOBSTATUS=\`grep \"successfully\\|stopped\\|completed\" ${LOGFILE}|tail -1\`" >>${IMPORTSCRIPT} echo "export LOGFILE=${LOGFILE}" >>${IMPORTSCRIPT} echo "export EMAILID=\"${EMAILANS}\"" >>${IMPORTSCRIPT} echo "${SENDEMAIL}" >>${IMPORTSCRIPT} echo "echo; echo -e '\033[32;5mIMPORT IS DONE.\033[0m'" >>${IMPORTSCRIPT} echo "echo" >>${IMPORTSCRIPT} chmod 740 ${IMPORTSCRIPT} echo echo "#!/bin/bash" > ${IMPORTSCRIPTRUNNER} echo "nohup sh ${IMPORTSCRIPT}| tee ${LOGFILE} 2>&1 &" >>${IMPORTSCRIPTRUNNER} chmod 740 ${IMPORTSCRIPTRUNNER} echo -e "\033[32;5mFeel free to EXIT from this session as the IMPORT SCRIPT is running in the BACKGROUND.\033[0m";echo source ${IMPORTSCRIPTRUNNER} # ############# # END OF SCRIPT # ############# # Your feedback is most welcome, e-mail me at: mahmmoudadel@hotmail.com # Every month a new release of DBA BUNDLE will get published, make sure to download it from: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/Archives_Delete.sh 0000740 0152073 0152061 00000020603 13775602255 016042 0 ustar oracle oinstall # ################################################# # This script Deletes the ARCHIVELOGS of a database # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-09-11 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # Added FORCE keyword to DELETE command # # # # ################################################# echo echo "=============================================================" echo "This script Deletes the ARCHIVELOGS of a database using RMAN." echo "=============================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi if [ -f ${USR_ORA_HOME}/login.sql ] then mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ############################### # RMAN: Script Execution: # ############################### # Variables echo echo Delete the ARCHIVES OLDER than the following NUMBER of days: [5] echo "===========================================================" while read NUM_DAYS do case $NUM_DAYS in # NO VALUE PROVIDED: 0) echo "WARNING: ALL ARCHIVELOGS WILL BE DELETED ... [Ctrl+c to Cancel]";echo ".";sleep 2;echo "..";sleep 2,sleep 3;break ;; "") NUM_DAYS=5;echo "DELETING Archivelogs OLDER than $NUM_DAYS days ... [Ctrl+c to Cancel]";sleep 6;break ;; # A NON NUMERIC VALUE PROVIDED: *[!0-9]*) echo "Please enter a Valid NUMERIC Value:" ;; *) echo;echo "DELETING Archivelogs OLDER than [$NUM_DAYS] days ... [Ctrl+c to Cancel]";sleep 6;break ;; esac done # EXECUTE THE RMAN ARCHIVE DELETION COMMAND: ${ORACLE_HOME}/bin/rman target / <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/biggest_100_objects.sh 0000740 0152073 0152061 00000015426 13775063565 016545 0 ustar oracle oinstall # ################################################# # Script to shows the biggest 100 objects on the DB # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-08-11 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # # # # ################################################# # ########### # Description: # ########### echo echo "===================================================" echo "This script shows the biggest 100 objects on the DB." echo "===================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ###################################### # SQLPLUS: Retreiving Biggest 100 Object: # ###################################### ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/all_users_ddl.sh 0000740 0152073 0152061 00000022716 13775064163 015637 0 ustar oracle oinstall # ##################################################################### # This script generate DDL for ALL USERS [Creation & Privileges] # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 30-04-2017 # # # # # # Modified: # # # ##################################################################### SCRIPT_NAME="all_users_ddl" # ############ # Description: # ############ echo echo "===========================================================" echo "This script generates the CREATION STATEMENT for ALL USERS." echo "===========================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################ # Listing Available Databases: # ############################ # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################### # Getting DB_NAME: # ######################### DB_NAME_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${SPOOL_FILE} echo "ALL DB USERS DLL:" >> ${SPOOL_FILE} echo "*****************" >> ${SPOOL_FILE} echo "" >> ${SPOOL_FILE} #fi # Perpare the List of user to loop on: ${ORACLE_HOME}/bin/sqlplus -S '/ as sysdba' << EOF PROMPT spool ${SPOOLLOF} set pages 0 set echo off heading off feedback off select username from dba_users where username not in ('SYS','SYSTEM','DBSNMP','EXFSYS','MDSYS','ORDDATA') order by 1; spool off EOF # Loop on each user with generating its DDL: for USERNAME in `cat ${SPOOLLOF}` do export USERNAME ${ORACLE_HOME}/bin/sqlplus -S '/ as sysdba' << EOF spool ${SPOOL_FILE} APPEND set termout off set linesize 190 set pages 50000 set feedback off set trim on set echo off col USERNAME for a30 col account_status for a23 PROMPT PROMPT ====================================== PROMPT USER [$USERNAME] PROMPT ====================================== select a.username,a.account_status,a.profile,q.tablespace_name,q.bytes/1024/104 USED_MB, q.max_bytes "MAX_QUOTA_Bytes" from dba_users a, dba_ts_quotas q where a.username=q.username and a.username='$USERNAME'; set pages 0 set echo off heading off feedback off -- Generate Creation Statement: SELECT 'CREATE USER ' || u.username ||' IDENTIFIED ' ||' BY VALUES ''' || c.password || ''' DEFAULT TABLESPACE ' || u.default_tablespace ||' TEMPORARY TABLESPACE ' || u.temporary_tablespace ||' PROFILE ' || u.profile || case when account_status= 'OPEN' then ';' else ' Account LOCK;' end "--Creation Statement" FROM dba_users u,user$ c where u.username=c.name and u.username=upper('$USERNAME') UNION -- Generate Granted Roles: select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted Roles" from dba_role_privs where grantee= upper('$USERNAME') UNION -- Generate System Privileges: select 'GRANT '||PRIVILEGE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted System Privileges" from dba_sys_privs where grantee= upper('$USERNAME') UNION -- Generate Object Privileges: select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where GRANTEE=upper('$USERNAME'); spool off EOF done echo "" echo "[ALL USERS DDL SAVED TO: ${SPOOL_FILE}]" echo "" # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/audit_records.sh 0000740 0152073 0152061 00000020403 13775602144 015636 0 ustar oracle oinstall ################################################### # This script shows AUDIT records for a user. # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 25-04-2013 # # # # # # ################################################### ############################# # Listing Available Instances: ############################# echo echo "==================================================================" echo "This Script Retreives AUDIT data for a user if auditing is enabled." echo "==================================================================" echo sleep 1 # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Run this script Against:[Enter the Number]" echo "-------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib ########################################## # Exit if the user is not the Oracle Owner: ########################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi ########################### # SQLPLUS Section: ########################### # PROMPT FOR VARIABLES: ###################### echo echo "Enter The DB USERNAME:" echo "=====================" while read DB_USERNAME do case $DB_USERNAME in # NO VALUE PROVIDED: "") USERNAME_COND=$DB_USERNAME;echo "RETREIVING ALL USERS AUDIT DATA";break ;; *) USERNAME_COND="USERNAME=upper('$DB_USERNAME') and";break ;; esac done echo echo "How [MANY DAYS BACK] you want to retrieve AUDIT data? [Default 1]" echo "=====================================================" echo "OR: If you want to retrieve AUDIT data on a [SPECIFIC DATE] Enter the DATE in this FORMAT [DD-MM-YYYY] e.g. 25-01-2011" echo "== ==================================================================================================" while read NUM_DAYS do case $NUM_DAYS in # User PROVIDED a NON NUMERIC value: *[!0-9]*) echo;echo "Retreiving AUDIT data for User [${DB_USERNAME}] on [${NUM_DAYS}] ..." ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < SYSDATE-$NUM_DAYS order by EXTENDED_TIMESTAMP; EOF ############### # END OF SCRIPT ############### # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # Please visit my blog: http://dba-tips.blogspot.com DBA_BUNDLE6/export_data.sh 0000700 0152073 0152061 00000237555 14106473143 015331 0 ustar oracle oinstall # ############################################################################################################################ # Ver: 3.0 # EXPORT DATABASE | SCHEMA | TABLE. # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # # # # # # # Created: 03-02-2014 # Modified: 26-05-2014 Hashed METADATA export lines to clear the confusion. # 21-08-2014 Added DEGREE OF PARALLELISM calculation. # 22-01-2020 Passing the export DataPump parameters to a Par file. # 22-01-2020 Convert the execution of the export in the background NOHUP mode. # 23-01-2020 Added the option of providing multiple schemas to export. # 23-01-2020 Added the option of providing multiple tables to export. # 23-01-2020 Added the option of excluding specific schemas and tables from the Full DB export mode. # 23-01-2020 Added the option of excluding specific tables from the SCHEMA mode export. # 28-01-2020 Added the option of COMPRESSING the legacy dump file on the fly for all LEGACY export modes. # 29-01-2020 Redesigned the parallelism option section to pop-up only when database edition support parallelism. # 02-02-2020 Added Email Notification option. # 17-08-2020 Fix a directory creation bug. # 03-01-2020 Translation of user input . & ~ # ############################################################################################################################ # ########### # Description: # ########### export SRV_NAME="`uname -n`" echo echo "==============================================" echo "This script EXPORTS DATABASE | SCHEMA | TABLE." echo "==============================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Instances: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Run this Script Against:[Enter the number]" echo "-------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ######################## # Getting ORACLE_BASE: # ######################## # Get ORACLE_BASE from user's profile if not set: if [ -z "${ORACLE_BASE}" ] then ORACLE_BASE=`grep -h 'ORACLE_BASE=\/' ${USR_ORA_HOME}/.bash* ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi # ######################### # EXPORT Section: # ######################### # VARIABLES: # ######### # Date Stamp: DUMPDATE=`date +%d-%b-%Y` #PASSHALF=`echo $((RANDOM % 999+7000))` PASSHALF=`date '+%s'` # If expdp version is 10g don't use REUSE_DUMPFILES parameter in the script: VERSION=`strings ${ORACLE_HOME}/bin/expdp|grep Release|awk '{print $3}'` case ${VERSION} in 10g) REUSE_DUMP='';; *) REUSE_DUMP='REUSE_DUMPFILES=Y';; # *) REUSE_DUMP='REUSE_DUMPFILES=Y COMPRESSION=ALL';; esac # Capturing the CURRENT_SCN to use it for a consistent DATA PUMP export: CURRENT_SCN_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 lines 1000 feedback off; col current_scn for 99999999999999999999999999999999999 select current_scn from v\$database; EOF ) CURRENT_SCN=`echo ${CURRENT_SCN_RAW}| awk '{print $NF}'` case ${CURRENT_SCN} in *[0-9]*) export EXPORTSCN="FLASHBACK_SCN=${CURRENT_SCN}";; *) export EXPORTSCN="";; esac VAL33=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT STATUS FROM V\$INSTANCE; EOF ) VAL44=`echo ${VAL33}| awk '{print $NF}'` case ${VAL44} in "OPEN") echo ;; *) echo;echo "ERROR: INSTANCE [${ORACLE_SID}] IS IN STATUS: ${VAL44} !" echo; echo "PLEASE OPEN INSTANCE [${ORACLE_SID}] AND RE-RUN THIS SCRIPT.";echo; exit ;; esac # ############################################ # Checking if PARALLELISM option is available: # ############################################ # Computing the default PARALLEL DEGREE based on CPU count: case `uname` in Linux ) export PARALLEL_DEGREE=`cat /proc/cpuinfo| grep processor|wc -l`;; AIX ) export PARALLEL_DEGREE=`lsdev -C|grep Process|wc -l`;; SunOS ) export PARALLEL_DEGREE=`kstat cpu_info|grep core_id|sort -u|wc -l`;; HP-UX) export PARALLEL_DEGREE=`lsdev -C|grep Process|wc -l`;; esac if [ ! -z "${PARALLEL_DEGREE##[0-9]*}" ] then export PARALLEL_DEGREE=1 fi CHK_PARALLELISM_OPTION_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off echo off; SELECT count(*) from v\$option where parameter='Parallel execution' and value='TRUE'; exit; EOF ) export CHK_PARALLELISM_OPTION=`echo ${CHK_PARALLELISM_OPTION_RAW} | awk '{print $NF}'` # ############################## # Prompt for EMAIL Confirmation: # ############################## echo "Enter your EMAIL to receive a notification upon the completion of the Export job: [Leave it BLANK or Enter N to Skip the notification]" echo "=================================================================================" while read EMAILANS do case ${EMAILANS} in ""|"N"|"n"|"NO"|"No"|"no")export EMAILANS=""; export SENDEMAIL=""; echo; break;; *@*.*) export SENDEMAIL="mail -s \"\${JOBSTATUS} on Server ${SRV_NAME}\" \${EMAILID} < \${LOGFILE}"; echo; break;; *)echo "" echo -e "\033[32;5mThis doesn't sound like a valid Email? ${EMAILANS}\033[0m" echo "" echo "Please Enter your Email: [Leave it BLANK or Enter N to Skip this!]" echo "------------------------" echo "i.e. john.smith@xyzcompany.com" echo "";; esac done echo "Enter the FULL LOCATION PATH where the EXPORT FILE will be saved under: [e.g. /backup/export]" echo "======================================================================" while read LOC1 do case ${LOC1} in '') export LOC1=`pwd`; echo "DIRECTORY TRANSLATED TO: ${LOC1}";; '.') export LOC1=`pwd`; echo "DIRECTORY TRANSLATED TO: ${LOC1}";; '~') export LOC1=${HOME}; echo "DIRECTORY TRANSLATED TO: ${LOC1}";; esac if [[ -d "${LOC1}" ]] && [[ -r "${LOC1}" ]] && [[ -w "${LOC1}" ]] then echo "Export File will be saved under: ${LOC1}"; break else echo; printf "`echo "Please make sure that oracle user has"` `echo -e "\033[33;5mREAD/WRITE\033[0m"` `echo "permissions on the provided directory."`\n"; echo; echo "Enter the complete PATH where the dump file will be saved: [e.g. /backup/export]" fi done # ###################### # Export Options: # ###################### echo echo "Please Select the EXPORT MODE: [Enter a number]" echo "==============================" echo "1. EXPORT FULL DATABASE" echo "2. EXPORT SCHEMAS" echo "3. EXPORT TABLES" echo "[Enter a number from 1 to 3]" echo "" while read ANS do case $ANS in 1|"EXPORT FULL DATABASE"|"database"|"DATABASE"|"full"|"FULL")echo;echo "Entering EXPORT FULL DATABASE MODE ...";sleep 1 # ####################### # EXPORT DATABASE SECTION: # ####################### echo echo "WHICH EXPORT UTILITY YOU WANT TO USE: [DEFAULT IS DATAPUMP EXPDP]" echo "====================================" echo "1) DATAPUMP [EXPDP] |Pros: Faster when import, Cloud/PARALLELISM compatible, can Exclude schema/tables |Cons: COMPRESSION requires license" echo "2) LEGACY EXPORT [EXP] |Pros: COMPRESSION can happen on the fly without license |Cons: Slower when import, No Cloud/PARALLELISM compatibility" while read EXP_TOOL do case $EXP_TOOL in ""|"1"|"DATAPUMP"|"datapump"|"DATAPUMP [EXPDP]"|"[EXPDP]"|"EXPDP"|"expdp") # Prompt the user the PARALLELISM option only if it's available in the DB Edition: export INT='^[0-9]+$' if [[ ${CHK_PARALLELISM_OPTION} =~ ${INT} ]] then if [ ${CHK_PARALLELISM_OPTION} -eq 1 ] then echo echo "Enter the PARALLEL DEGREE you want to perform the export with PARALLELISM? [If used, The final dump file will be divided into multiple files!]" echo "=========================================================================" echo "[Current CPU Count on this Server is: ${PARALLEL_DEGREE}]" echo "Enter a number bigger than 1 to utilize PARALLELISM or enter 0 to disable PARALLELISM" echo "" while read PARALLEL_ANS do # Check if the input is an integer: if [[ ${PARALLEL_ANS} =~ ${INT} ]] then # Check if the input is greater than 1: if [ ${PARALLEL_ANS} -gt 1 ] then export PARALLEL="PARALLEL=${PARALLEL_ANS}" export PARA="_%u" echo -e "\033[32;5mPARALLELISM ENABLED | The final dump file will be divided into multiple files based on the degree of parallelism you used.\033[0m" else echo "PARALLELISM DISABLED." fi break fi done else echo;echo -e "\033[32;5mPARALLELISM option is not available in the current Database Edition.\033[0m" fi fi # PARAMETER FILE CREATION: export DUMPFILENAME="EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}${PARA}.dmp" export LOGFILE="${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.log" PARFILE=${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}.par echo "# FULL DATABASE EXPORT PARAMETER FILE CREATED BY export_data.sh SCRIPT on [${DUMPDATE}]:" > ${PARFILE} echo "FULL=Y" >> ${PARFILE} echo "DIRECTORY=EXPORT_FILES_DBA_BUNDLE" >> ${PARFILE} echo "DUMPFILE=${DUMPFILENAME}" >> ${PARFILE} echo "LOGFILE=EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.log" >> ${PARFILE} echo "${EXPORTSCN}" >> ${PARFILE} echo "${REUSE_DUMP}" >> ${PARFILE} echo "${PARALLEL}" >> ${PARFILE} echo "Do you want to enable the COMPRESSION [Y|N] [N] [Do NOT answer with YES unless you already have the Advanced Compression License]" echo "=====================================" while read COMP_ANS do case $COMP_ANS in y|Y|yes|YES|Yes) echo;echo "COMPRESSION=ALL" >> ${PARFILE};echo -e "\033[32;5mCompression Enabled.\033[0m";echo; break ;; ""|n|N|no|NO|No) echo; break ;; *) echo;echo "Please Enter a Valid Answer [Y|N]" echo "---------------------------------";; esac done echo echo "Enter the SCHEMAS you want to EXCLUDE from the export, separating them by comma:" echo "===============================================================================" echo "i.e. ANONYMOUS,APPQOSSYS,AUDSYS,BI,CTXSYS,DBSNMP,DIP,DMSYS,DVF,DVSYS,EXDSYS,EXFSYS,GSMADMIN_INTERNAL,GSMCATUSER,GSMUSER,LBACSYS,MDSYS,MGMT_VIEW,MDDATA,MTSSYS,ODM,ODM_MTR,OJVMSYS,OLAPSYS,ORACLE_OCM,ORDDATA,ORDPLUGINS,ORDSYS,OUTLN,SI_INFORMTN_SCHEMA,SPATIAL_CSW_ADMIN,SPATIAL_CSW_ADMIN_USR,SPATIAL_WFS_ADMIN,SPATIAL_WFS_ADMIN_USR,SYS,SYSBACKUP,SYSDG,SYSKM,SYSMAN,SYSTEM,TSMSYS,WKPROXY,WKSYS,WK_TEST,WMSYS,XDB,XTISYS,DSSYS,PERFSTAT,REPADMIN,OEM_ADVISOR,OEM_MONITOR,OLAP_DBA,OLAP_USER,OWBSYS,OWBSYS_AUDIT,APEX_030200" echo "[Leave it BLANK and hit Enter if you do NOT want to exclude any SCHEMAS]" echo "" while read EXCLUDESCHEMAVAR do case ${EXCLUDESCHEMAVAR} in "") echo; export EXCLUDESCHEMA=""; break ;; *) echo; export EXCLUDESCHEMA="EXCLUDE=SCHEMA:\"IN('$(sed s/,/\',\'/g <<<${EXCLUDESCHEMAVAR}| tr '[:lower:]' '[:upper:]')')\"" echo ${EXCLUDESCHEMA} >> ${PARFILE}; break ;; esac done echo echo "Enter the TABLES you want to EXCLUDE from the export, separating them by comma:" echo "==============================================================================" echo "i.e. EMP,DEPT" echo "[Leave it BLANK and hit Enter if you do NOT want to exclude any TABLES]" echo "" while read EXCLUDETABLEVAR do case ${EXCLUDETABLEVAR} in "") echo; export EXCLUDETABLE=""; break ;; *) echo; export EXCLUDETABLE="EXCLUDE=TABLE:\"IN('$(sed s/,/\',\'/g <<<${EXCLUDETABLEVAR}| tr '[:lower:]' '[:upper:]')')\"" echo ${EXCLUDETABLE} >> ${PARFILE}; break ;; esac done cd ${LOC1} SPOOLFILE2=${LOC1}/AFTER_IMPORT_DATABASE_${ORACLE_SID}_${DUMPDATE}.sql echo "Creating the Exporter User DBA_BUNDLEEXP7 ..." echo "Preparing the BEFORE and AFTER import script which will help you import the dump file later ..." VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT CREATE USER DBA_BUNDLEEXP7 [EXPORTER USER] (WILL BE DROPPED AFTER THE EXPORT) ... CREATE USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; ALTER USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; GRANT CREATE SESSION TO DBA_BUNDLEEXP7; GRANT DBA TO DBA_BUNDLEEXP7; -- The following privileges to workaround Bug 6392040: GRANT EXECUTE ON SYS.DBMS_DEFER_IMPORT_INTERNAL TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_EXPORT_EXTENSION TO DBA_BUNDLEEXP7; PROMPT PROMPT CREATING DIRECTORY EXPORT_FILES_DBA_BUNDLE POINTING TO ${LOC1} ... CREATE OR REPLACE DIRECTORY EXPORT_FILES_DBA_BUNDLE AS '${LOC1}'; PROMPT PROMPT CREATING AFTER DATABASE IMPORT SCRIPT ... PROMPT SET PAGES 0 TERMOUT OFF LINESIZE 157 ECHO OFF FEEDBACK OFF SPOOL ${SPOOLFILE2} SELECT 'PROMPT ' FROM DUAL; SELECT 'PROMPT COMPILING DATABASE INVALID OBJECTS ...' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT 'PROMPT ' FROM DUAL; SELECT 'PROMPT THE FOLLOWING TRIGGERS ARE OWNED BY SYS SCHEMA AND MAY NOT BE EXIST AFTER THE IMPORT' FROM DUAL; SELECT 'PROMPT YOU MAY CONSIDER CREATING THE NON EXIST TRIGGERS IF YOU NEED SO:' FROM DUAL; SELECT 'PROMPT ***************************************************************' FROM DUAL; SELECT 'PROMPT '||TRIGGER_TYPE||' TRIGGER: '||TRIGGER_NAME FROM DBA_TRIGGERS WHERE OWNER=UPPER('SYS') ORDER BY 1; SELECT 'PROMPT ' FROM DUAL; SELECT 'PROMPT CHECK IF THESE DIRECTORIES ARE POINTING TO THE RIGHT PATHS? ' FROM DUAL; SELECT 'PROMPT *********************************************************** ' FROM DUAL; COL DIRECTORY FOR A50 COL DIRECTORY_PATH FOR A100 SELECT 'PROMPT '||OWNER||'.'||DIRECTORY_NAME||': '||DIRECTORY_PATH FROM DBA_DIRECTORIES; SELECT 'PROMPT ' FROM DUAL; SPOOL OFF EOF ) echo # Creation of the Export Script: export EXPORTSCRIPT=${LOC1}/EXPORTSCRIPT.sh export EXPORTSCRIPTRUNNER=${LOC1}/EXPORTSCRIPTRUNNER.sh echo "# Export Script: [Created By DBA_BUNDLE]" > ${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"While the Export job is running, you can check the STATUS using:\"" >>${EXPORTSCRIPT} echo "echo \"--------------------------------------------------------------- \"" >>${EXPORTSCRIPT} echo "echo \"SELECT job_name, operation, job_mode, DEGREE, state FROM dba_datapump_jobs where OPERATION='EXPORT' and state='EXECUTING' and owner_name='DBA_BUNDLEEXP7';\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"Then you can ATTACH to the export job and control it using:\"" >>${EXPORTSCRIPT} echo "echo \"---------------------------------------------------------- \"" >>${EXPORTSCRIPT} echo "echo \"expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=\"" >>${EXPORTSCRIPT} echo "echo \"i.e.\"" >>${EXPORTSCRIPT} echo "echo \"expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=SYS_EXPORT_FULL_01\"" >>${EXPORTSCRIPT} echo "echo \"To Show the STATUS:....... STATUS\"" >>${EXPORTSCRIPT} echo "echo \"To KILL the export:....... KILL_JOB\"" >>${EXPORTSCRIPT} echo "echo \"To PAUSE the export:...... STOP_JOB\"" >>${EXPORTSCRIPT} echo "echo \"To RESUME a paused export: START_JOB\"" >>${EXPORTSCRIPT} echo "export ORACLE_SID=${ORACLE_SID}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running The Export Job Now ...'" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" PARFILE=${PARFILE}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running Post Export Steps ...'" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF" >>${EXPORTSCRIPT} echo "PROMPT" >>${EXPORTSCRIPT} echo "PROMPT DROPPING THE EXPORTER USER DBA_BUNDLEEXP7 (SAFELY) ..." >>${EXPORTSCRIPT} echo "DROP USER DBA_BUNDLEEXP7;" >>${EXPORTSCRIPT} echo "EOF" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"IMPORT GUIDELINES:\"" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"FLASHBACK SCN used for this export is: ${CURRENT_SCN}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"Later, AFTER IMPORTING THE DUMPFILE, RUN THIS SQL SCRIPT: ${SPOOLFILE2}\"" >>${EXPORTSCRIPT} echo "echo \" => IT INCLUDES (HINT FOR TRIGGERS OWNED BY SYS) WHICH WILL NOT BE CREATED BY THE IMPORT PROCESS + COMPILING INVALID OBJECTS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"*************************\"" >>${EXPORTSCRIPT} echo "echo \"EXPORT DUMP FILE LOCATION: ${LOC1}/${DUMPFILENAME}\"" >>${EXPORTSCRIPT} echo "echo \"*************************\"" >>${EXPORTSCRIPT} echo "export JOBSTATUS=\`grep \"successfully\\|stopped\\|completed\" ${LOGFILE}|tail -1\`" >>${EXPORTSCRIPT} echo "export LOGFILE=${LOGFILE}" >>${EXPORTSCRIPT} echo "export EMAILID=\"${EMAILANS}\"" >>${EXPORTSCRIPT} echo "${SENDEMAIL}" >>${EXPORTSCRIPT} chmod 740 ${EXPORTSCRIPT} echo echo "#!/bin/bash" > ${EXPORTSCRIPTRUNNER} echo "nohup sh ${EXPORTSCRIPT}| tee ${LOGFILE} 2>&1 &" >>${EXPORTSCRIPTRUNNER} chmod 740 ${EXPORTSCRIPTRUNNER} echo -e "\033[32;5mFeel free to EXIT from this session as the EXPORT SCRIPT is running in the BACKGROUND.\033[0m" source ${EXPORTSCRIPTRUNNER} ## Export METADATA ONLY: #echo;echo "CREATING A FILE CONTAINS ALL CREATION [DDL] STATEMENT OF ALL USERS|OBJECTS ...";sleep 1 #${ORACLE_HOME}/bin/exp DBA_BUNDLEEXP7/"BUNdle_#-^${PASSHALF}" FULL=y ROWS=N STATISTICS=NONE FILE=${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.dmp log=${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.log ## Getting READABLE export script: [DUMP REFINING] #/usr/bin/strings ${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.dmp > ${LOC1}/${ORACLE_SID}_METADATA_REFINED_${DUMPDATE}.trc echo; exit ;; # In case the user will export the FULL database using EXP legacy tool: "2"|"LEGACY EXPORT"|"LEGACY"|"EXPORT"|"LEGACY EXPORT [EXP]"|"EXP"|"[EXP]"|"exp"|"legacy export"|"legacy"|"export") echo echo "Do you want to enable the COMPRESSION [Y|N] [N] [COMPRESSION will happen on the fly using mknod | No License required]" echo "=====================================" while read COMP_ANS do case $COMP_ANS in y|Y|yes|YES|Yes) echo;export EXPORTDUMP="${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}_pipe.dmp" export MKNOD="rm -f ${EXPORTDUMP}; mknod ${EXPORTDUMP} p" export ZIP="nohup bzip2 -fz < ${EXPORTDUMP} > ${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.dmp.bz2 &" export EXPORTDUMPOUTPUT="${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.dmp.bz2" export REMOVEMKDON="rm -f ${EXPORTDUMP}" export UNZIPMESSAGE="First DE-COMPRESS the file using this command: bunzip2 -f ${EXPORTDUMPOUTPUT}" echo -e "\033[32;5mCompression Enabled.\033[0m";echo; break ;; ""|n|N|no|NO|No) echo;export MKNOD="" export ZIP="" export EXPORTDUMP="${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.dmp" export EXPORTDUMPOUTPUT="${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.dmp";break ;; *) echo;echo "Please Enter a Valid Answer [Y|N]" echo "---------------------------------";; esac done echo echo "EXPORTING DATABASE $ORACLE_SID [USING LEGACY EXP] ..." sleep 1 cd ${LOC1} SPOOLFILE2=${LOC1}/AFTER_IMPORT_DATABASE_${ORACLE_SID}_${DUMPDATE}.sql echo "Creating the Exporter User DBA_BUNDLEEXP7 ..." echo "Preparing the BEFORE and AFTER import script which will help you import the dump file later ..." VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT CREATE USER DBA_BUNDLEEXP7 [EXPORTER USER] (WILL BE DROPPED AFTER THE EXPORT) ... CREATE USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; ALTER USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; GRANT CREATE SESSION TO DBA_BUNDLEEXP7; GRANT EXP_FULL_DATABASE TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_FLASHBACK TO DBA_BUNDLEEXP7; -- The following privileges to workaround Bug 6392040: GRANT EXECUTE ON SYS.DBMS_DEFER_IMPORT_INTERNAL TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_EXPORT_EXTENSION TO DBA_BUNDLEEXP7; PROMPT PROMPT CREATING DIRECTORY EXPORT_FILES_DBA_BUNDLE POINTING TO ${LOC1} ... CREATE OR REPLACE DIRECTORY EXPORT_FILES_DBA_BUNDLE AS '${LOC1}'; PROMPT PROMPT CREATING AFTER DATABASE IMPORT SCRIPT ... PROMPT SET PAGES 0 TERMOUT OFF LINESIZE 157 ECHO OFF FEEDBACK OFF SPOOL ${SPOOLFILE2} SELECT 'PROMPT COMPILING DATABASE INVALID OBJECTS ...' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT 'PROMPT ' FROM DUAL; SELECT 'PROMPT THE FOLLOWING TRIGGERS ARE OWNED BY SYS SCHEMA AND MAY NOT BE EXIST AFTER THE IMPORT' FROM DUAL; SELECT 'PROMPT YOU MAY CONSIDER CREATING THE NON EXIST TRIGGERS IF YOU NEED SO:' FROM DUAL; SELECT 'PROMPT ***************************************************************' FROM DUAL; SELECT 'PROMPT '||TRIGGER_TYPE||' TRIGGER: '||TRIGGER_NAME FROM DBA_TRIGGERS WHERE OWNER=UPPER('SYS') ORDER BY 1; SELECT 'PROMPT ARE THESE DIRECTORIES POINTING TO THE RIGHT PATHS? ' FROM DUAL; COL DIRECTORY FOR A50 COL DIRECTORY_PATH FOR A100 SELECT 'PROMPT '||OWNER||'.'||DIRECTORY_NAME||': '||DIRECTORY_PATH FROM DBA_DIRECTORIES; SPOOL OFF EOF ) # Creation of the Post Export Script: export DUMPFILENAME="EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}${PARA}.dmp" export LOGFILE="${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.log" export EXPORTSCRIPT=${LOC1}/EXPORTSCRIPT.sh export EXPORTSCRIPTRUNNER=${LOC1}/EXPORTSCRIPTRUNNER.sh echo "# Export Script: [Created By DBA_BUNDLE]" > ${EXPORTSCRIPT} echo "export ORACLE_SID=${ORACLE_SID}" >>${EXPORTSCRIPT} echo "echo 'Running The Export Job Now ...'" >>${EXPORTSCRIPT} echo "${MKNOD}" >>${EXPORTSCRIPT} echo "sleep 1" >>${EXPORTSCRIPT} echo "${ZIP}" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/exp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" FULL=y DIRECT=y CONSISTENT=y STATISTICS=NONE FEEDBACK=100000 ${EXPORTSCN} RESUMABLE=y RESUMABLE_NAME=DBA_BUNDLE_EXPORT RESUMABLE_TIMEOUT=86400 FILE=${EXPORTDUMP} log=${LOC1}/EXPORT_FULL_DB_${ORACLE_SID}_${DUMPDATE}.log" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running Post Export Steps ...'" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF" >>${EXPORTSCRIPT} echo "PROMPT" >>${EXPORTSCRIPT} echo "PROMPT DROPPING THE EXPORTER USER DBA_BUNDLEEXP7 (SAFELY) ..." >>${EXPORTSCRIPT} echo "DROP USER DBA_BUNDLEEXP7;" >>${EXPORTSCRIPT} echo "EOF" >>${EXPORTSCRIPT} echo "sleep 3" >>${EXPORTSCRIPT} echo "${REMOVEMKDON}" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"IMPORT GUIDELINES:\"" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"FLASHBACK SCN used for this export is: ${CURRENT_SCN}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"${UNZIPMESSAGE}\"" >>${EXPORTSCRIPT} echo "echo \"Later, AFTER IMPORTING THE DUMPFILE, RUN THIS SQL SCRIPT: ${SPOOLFILE2}\"" >>${EXPORTSCRIPT} echo "echo \" => IT INCLUDES (HINT FOR TRIGGERS OWNED BY SYS) WHICH WILL NOT BE CREATED BY THE IMPORT PROCESS + COMPILING INVALID OBJECTS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "echo \"EXPORT DUMP FILE LOCATION: ${EXPORTDUMPOUTPUT}\"" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "export JOBSTATUS=\`grep \"successfully\\|stopped\\|completed\" ${LOGFILE}|tail -1\`" >>${EXPORTSCRIPT} echo "export LOGFILE=${LOGFILE}" >>${EXPORTSCRIPT} echo "export EMAILID=\"${EMAILANS}\"" >>${EXPORTSCRIPT} echo "${SENDEMAIL}" >>${EXPORTSCRIPT} chmod 740 ${EXPORTSCRIPT} echo echo "#!/bin/bash" > ${EXPORTSCRIPTRUNNER} echo "nohup sh ${EXPORTSCRIPT}| tee ${LOGFILE} 2>&1 &" >>${EXPORTSCRIPTRUNNER} chmod 740 ${EXPORTSCRIPTRUNNER} echo -e "\033[32;5mFeel free to EXIT from this session as the EXPORT SCRIPT is running in the BACKGROUND.\033[0m" source ${EXPORTSCRIPTRUNNER} ## Export METADATA ONLY: #echo #echo "CREATING A FILE CONTAINS ALL CREATION [DDL] STATEMENT OF ALL USERS|OBJECTS ..." #sleep 1 #${ORACLE_HOME}/bin/exp DBA_BUNDLEEXP7/"BUNdle_#-^${PASSHALF}" FULL=y ROWS=N STATISTICS=NONE FILE=${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.dmp log=${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.log ## Removing Extra Bad characters: [DUMP REFINING] #/usr/bin/strings ${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.dmp > ${LOC1}/${ORACLE_SID}_METADATA_REFINED_${DUMPDATE}.trc #echo #echo "EXTRA FILES:" #echo "-----------" #echo "METADATA ONLY DUMP FILE : ${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.dmp" #echo "DDL Script FILE : ${LOC1}/${ORACLE_SID}_METADATA_REFINED_${DUMPDATE}.trc" #echo "*****************************************************************" echo; exit ;; *) echo "Enter a valid number:" echo "=====================" echo "i.e." echo "1 for expdp tool" echo "2 for exp tool" echo ;; esac done break;; 2|"EXPORT SCHEMAS"|"database"|"DATABASE"|"schema"|"schemas"|"SCHEMA"|"SCHEMAS") echo echo "Entering EXPORT SCHEMA MODE ..." sleep 1 # ###################### # EXPORT SCHEMA SECTION: # ###################### echo echo "WHICH EXPORT UTILITY YOU WANT TO USE: [1) DATAPUMP [EXPDP]]" echo "====================================" echo "1) DATAPUMP [EXPDP] |Pros: Faster when import, Cloud/PARALLELISM compatible, can Exclude schema/tables |Cons: COMPRESSION requires license" echo "2) LEGACY EXPORT [EXP] |Pros: COMPRESSION can happen on the fly without license |Cons: Slower when import, No Cloud/PARALLELISM compatibility" while read EXP_TOOL do case $EXP_TOOL in ""|"1"|"DATAPUMP"|"datapump"|"DATAPUMP [EXPDP]"|"[EXPDP]"|"EXPDP"|"expdp") if [[ ${CHK_PARALLELISM_OPTION} =~ ${INT} ]] then if [ ${CHK_PARALLELISM_OPTION} -eq 1 ] then echo echo "Enter the PARALLEL DEGREE you want to perform the export with PARALLELISM? [If used, The final dump file will be divided into multiple files!]" echo "=========================================================================" echo "[Current CPU Count on this Server is: ${PARALLEL_DEGREE}]" echo "Enter a number bigger than 1 to utilize PARALLELISM or enter 0 to disable PARALLELISM" echo "" while read PARALLEL_ANS do # Check if the input is an integer: if [ -z ${PARALLEL_ANS} ]; then export PARALLEL_ANS=0 fi if [[ ${PARALLEL_ANS} =~ ${INT} ]] then # Check if the input is greater than 1: if [ "${PARALLEL_ANS}" -gt 1 ] then export PARALLEL="PARALLEL=${PARALLEL_ANS}" export PARA="_%u" echo -e "\033[32;5mPARALLELISM ENABLED | The final dump file will be divided into multiple files based on the degree of parallelism you used.\033[0m" else echo "PARALLELISM DISABLED." fi break fi done else echo;echo -e "\033[32;5mPARALLELISM option is not available in the current Database Edition.\033[0m" fi fi # PARAMETER FILE CREATION: export DUMPFILENAME="EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}${PARA}.dmp" export LOGFILE="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.log" # PARAMETER FILE CREATION: PARFILE=${LOC1}/EXPORT_SCHEMA_DB_${ORACLE_SID}.par echo "# SCHEMA EXPORT PARAMETER FILE CREATED BY export_data.sh SCRIPT on [${DUMPDATE}]:" > ${PARFILE} echo "DIRECTORY=EXPORT_FILES_DBA_BUNDLE" >> ${PARFILE} echo "DUMPFILE=${DUMPFILENAME}" >> ${PARFILE} echo "LOGFILE=EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.log" >> ${PARFILE} echo "${EXPORTSCN}" >> ${PARFILE} echo "${REUSE_DUMP}" >> ${PARFILE} echo "${PARALLEL}" >> ${PARFILE} echo echo "Enter the SCHEMAS you want to export, separating them by comma:" echo "==============================================================" echo "i.e. HR,SCOTT,OE" echo "" while read SCHEMASVAR do case ${SCHEMASVAR} in "") echo; echo "Please Enter the Schema Name you want to export:" echo "-----------------------------------------------" echo "i.e. SCOTT,HR,OE" echo "";; *) echo # Convert User's input into UPPERCASE: export SCHEMASVAR="$(echo ${SCHEMASVAR}| tr [:lower:] [:upper:])" export SCHEMA="SCHEMAS=${SCHEMASVAR}" echo ${SCHEMA} >> ${PARFILE} export SCHEMALIST="'$(sed s/,/\',\'/g <<<${SCHEMASVAR}| tr '[:lower:]' '[:upper:]')'"; break ;; esac done echo echo "Enter the TABLES you want to EXCLUDE from the export, separating them by comma:" echo "===============================================================================" echo "i.e. EMP,DEPT" echo "[Leave it BLANK and hit Enter if you do NOT want to exclude any TABLES]" echo "" while read EXCLUDETABLEVAR do case ${EXCLUDETABLEVAR} in "") echo; export EXCLUDETABLE=""; break ;; *) echo; export EXCLUDETABLE="EXCLUDE=TABLE:\"IN('$(sed s/,/\',\'/g <<<${EXCLUDETABLEVAR}| tr '[:lower:]' '[:upper:]')')\"" echo ${EXCLUDETABLE} >> ${PARFILE}; break ;; esac done echo echo "Do you want to enable the COMPRESSION [Y|N] [N] [Do NOT answer with YES unless you already have the Advanced Compression License]" echo "=====================================" while read COMP_ANS do case $COMP_ANS in y|Y|yes|YES|Yes) echo;echo "COMPRESSION=ALL" >> ${PARFILE};echo -e "\033[32;5mCompression Enabled.\033[0m";echo; break ;; ""|n|N|no|NO|No) echo; break ;; *) echo;echo "Please Enter a Valid Answer: [Y|N]" echo "----------------------------";; esac done cd ${LOC1} SPOOLFILE1=${LOC1}/BEFORE_IMPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.sql SPOOLFILE2=${LOC1}/AFTER_IMPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.sql echo "Creating the Exporter User DBA_BUNDLEEXP7 ..." echo "Preparing the BEFORE and AFTER import script which will help you import the dump file later ..." VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT CREATE USER DBA_BUNDLEEXP7 [EXPORTER USER] (WILL BE DROPPED AFTER THE EXPORT) ... CREATE USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; ALTER USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; GRANT CREATE SESSION TO DBA_BUNDLEEXP7; GRANT DBA TO DBA_BUNDLEEXP7; -- The following privileges to workaround Bug 6392040: GRANT EXECUTE ON SYS.DBMS_DEFER_IMPORT_INTERNAL TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_EXPORT_EXTENSION TO DBA_BUNDLEEXP7; PROMPT PROMPT CREATING DIRECTORY EXPORT_FILES_DBA_BUNDLE POINTING TO ${LOC1} ... CREATE OR REPLACE DIRECTORY EXPORT_FILES_DBA_BUNDLE AS '${LOC1}'; PROMPT PROMPT CREATING BEFORE SCHEMA IMPORT SCRIPT ... PROMPT SET PAGES 0 TERMOUT OFF LINESIZE 157 ECHO OFF FEEDBACK OFF SPOOL ${SPOOLFILE1} SELECT 'CREATE USER ' || u.username ||' IDENTIFIED ' ||' BY VALUES ''' || c.password || ''' DEFAULT TABLESPACE ' || u.default_tablespace ||' TEMPORARY TABLESPACE ' || u.temporary_tablespace ||' PROFILE ' || u.profile || case when account_status= 'OPEN' then ';' else ' Account LOCK;' end "--Creation Statement" FROM dba_users u,user$ c where u.username=c.name and u.username in (${SCHEMALIST}) UNION SELECT 'CREATE ROLE '||GRANTED_ROLE||';' FROM DBA_ROLE_PRIVS WHERE GRANTEE in (${SCHEMALIST}) UNION select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted Roles" from dba_role_privs where grantee in (${SCHEMALIST}) UNION select 'GRANT '||PRIVILEGE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted System Privileges" from dba_sys_privs where grantee in (${SCHEMALIST}) UNION select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where GRANTEE in (${SCHEMALIST}); SPOOL OFF PROMPT CREATING AFTER SCHEMA IMPORT SCRIPT ... PROMPT SPOOL ${SPOOLFILE2} select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where OWNER in (${SCHEMALIST}) UNION SELECT 'CREATE PUBLIC SYNONYM '||SYNONYM_NAME||' FOR '||TABLE_OWNER||'.'||TABLE_NAME||';' FROM DBA_SYNONYMS WHERE TABLE_OWNER in (${SCHEMALIST}) AND OWNER=UPPER('PUBLIC'); PROMPT SELECT 'PROMPT COMPILING DATABASE INVALID OBJECTS ...' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT 'PROMPT ' FROM DUAL; SELECT 'PROMPT THE FOLLOWING TRIGGERS ARE OWNED BY OTHER USERS BUT ARE DEPENDANT ON THE EXPORTED SCHEMAS OBJECTS' FROM DUAL; SELECT 'PROMPT YOU MAY CONSIDER TO CREATE THEM AFTER THE SCHEMA IMPORT IF YOU NEED SO:' FROM DUAL; SELECT 'PROMPT **********************************************************************' FROM DUAL; SELECT 'PROMPT '||TRIGGER_TYPE||' TRIGGER: '||OWNER||'.'||TRIGGER_NAME||' =>ON TABLE: '||TABLE_OWNER||'.'||TABLE_NAME FROM DBA_TRIGGERS WHERE TABLE_OWNER IN (${SCHEMALIST}) AND OWNER NOT IN (${SCHEMALIST}) ORDER BY 1; SPOOL OFF EOF ) echo # Creation of the Export Script: export EXPORTSCRIPT=${LOC1}/EXPORTSCRIPT.sh export EXPORTSCRIPTRUNNER=${LOC1}/EXPORTSCRIPTRUNNER.sh echo "# Export Script: [Created By DBA_BUNDLE]" > ${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"While the Export job is running, you can check the STATUS using:\"" >>${EXPORTSCRIPT} echo "echo \"--------------------------------------------------------------- \"" >>${EXPORTSCRIPT} echo "echo \"SELECT job_name, operation, job_mode, DEGREE, state FROM dba_datapump_jobs where OPERATION='EXPORT' and state='EXECUTING' and owner_name='DBA_BUNDLEEXP7';\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"Then you can ATTACH to the export job and control it using:\"" >>${EXPORTSCRIPT} echo "echo \"---------------------------------------------------------- \"" >>${EXPORTSCRIPT} echo "echo \"expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=\"" >>${EXPORTSCRIPT} echo "echo \"i.e.\"" >>${EXPORTSCRIPT} echo "echo \"expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=SYS_EXPORT_SCHEMA_01\"" >>${EXPORTSCRIPT} echo "echo \"To Show the STATUS:....... STATUS\"" >>${EXPORTSCRIPT} echo "echo \"To KILL the export:....... KILL_JOB\"" >>${EXPORTSCRIPT} echo "echo \"To PAUSE the export:...... STOP_JOB\"" >>${EXPORTSCRIPT} echo "echo \"To RESUME a paused export: START_JOB\"" >>${EXPORTSCRIPT} echo "export ORACLE_SID=${ORACLE_SID}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running The Export Job Now ...'" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" PARFILE=${PARFILE}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running Post Export Steps ...'" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF" >>${EXPORTSCRIPT} echo "PROMPT" >>${EXPORTSCRIPT} echo "PROMPT DROPPING THE EXPORTER USER DBA_BUNDLEEXP7 (SAFELY) ..." >>${EXPORTSCRIPT} echo "DROP USER DBA_BUNDLEEXP7;" >>${EXPORTSCRIPT} echo "EOF" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"IMPORT GUIDELINES:\"" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"FLASHBACK SCN used for this export is: ${CURRENT_SCN}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"BEFORE IMPORTING THE DUMPFILE IT'S RECOMMENDED TO RUN THIS SQL SCRIPT: ${SPOOLFILE1}\"" >>${EXPORTSCRIPT} echo "echo \"It includes (USER|ROLES|GRANTED PRIVILEGES CREATION STATEMENTS), WHICH WILL NOT BE CREATED DURING THE IMPORT PROCESS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"AFTER IMPORTING THE DUMPFILE, RUN THIS SQL SCRIPT: ${SPOOLFILE2}\"" >>${EXPORTSCRIPT} echo "echo \"It includes (Public Synonyms DDLs, Privileges granted to others, Hints for Triggers owned by others but depending on the exported schemas objects) + COMPILING INVALID OBJECTS, SUCH STUFF WILL NOT BE CARRIED OUT BY THE IMPORT PROCESS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "echo \"EXPORT DUMP FILE LOCATION: ${LOC1}/${DUMPFILENAME}\"" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "export JOBSTATUS=\`grep \"successfully\\|stopped\\|completed\" ${LOGFILE}|tail -1\`" >>${EXPORTSCRIPT} echo "export LOGFILE=${LOGFILE}" >>${EXPORTSCRIPT} echo "export EMAILID=\"${EMAILANS}\"" >>${EXPORTSCRIPT} echo "${SENDEMAIL}" >>${EXPORTSCRIPT} chmod 740 ${EXPORTSCRIPT} echo echo "#!/bin/bash" > ${EXPORTSCRIPTRUNNER} echo "nohup sh ${EXPORTSCRIPT}| tee ${LOGFILE} 2>&1 &" >>${EXPORTSCRIPTRUNNER} chmod 740 ${EXPORTSCRIPTRUNNER} echo -e "\033[32;5mFeel free to EXIT from this session as the EXPORT SCRIPT is running in the BACKGROUND.\033[0m" source ${EXPORTSCRIPTRUNNER} ## Export METADATA ONLY: #echo;echo "CREATING A FILE CONTAINS ALL CREATION [DDL] STATEMENT OF ALL USERS|OBJECTS ...";sleep 1 #${ORACLE_HOME}/bin/exp DBA_BUNDLEEXP7/"BUNdle_#-^${PASSHALF}" FULL=y ROWS=N STATISTICS=NONE FILE=${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.dmp log=${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.log ## Getting READABLE export script: [DUMP REFINING] #/usr/bin/strings ${LOC1}/${ORACLE_SID}_METADATA_${DUMPDATE}.dmp > ${LOC1}/${ORACLE_SID}_METADATA_REFINED_${DUMPDATE}.trc echo; exit ;; "2"|"LEGACY EXPORT"|"LEGACY"|"EXPORT"|"LEGACY EXPORT [EXP]"|"EXP"|"[EXP]"|"exp"|"legacy export"|"legacy"|"export") DUMPFILE="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.dmp" LOGFILE="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.log" echo echo "Enter the SCHEMAS you want to export, separating them by comma:" echo "==============================================================" echo "i.e. HR,SCOTT,OE" echo "" while read SCHEMASVAR do case ${SCHEMASVAR} in "") echo; echo "Please Enter the Schema Name you want to export: [i.e. SCOTT,HR,OE]" echo "-----------------------------------------------";; *) echo # Convert User's input into UPPERCASE: export SCHEMASVAR="$(echo ${SCHEMASVAR}| tr [:lower:] [:upper:])" export SCHEMALIST="'$(sed s/,/\',\'/g <<<${SCHEMASVAR}| tr '[:lower:]' '[:upper:]')'"; break ;; esac done export EXPORTDUMP="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.dmp" export LOGFILE="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.log" echo echo "Do you want to enable the COMPRESSION [Y|N] [N] [COMPRESSION will happen on the fly using mknod | No License required]" echo "=====================================" while read COMP_ANS do case $COMP_ANS in y|Y|yes|YES|Yes) echo;export EXPORTDUMP="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}_pipe.dmp" export MKNOD="rm -f ${EXPORTDUMP}; mknod ${EXPORTDUMP} p" export ZIP="nohup bzip2 -fz < ${EXPORTDUMP} > ${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.dmp.bz2 &" export EXPORTDUMPOUTPUT="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.dmp.bz2" export REMOVEMKDON="rm -f ${EXPORTDUMP}" export UNZIPMESSAGE="First DE-COMPRESS the file using this command: bunzip2 -f ${EXPORTDUMPOUTPUT}" echo -e "\033[32;5mCompression Enabled.\033[0m";echo; break ;; ""|n|N|no|NO|No) echo;export MKNOD="" export ZIP="" export EXPORTDUMP="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.dmp" export EXPORTDUMPOUTPUT="${LOC1}/EXPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.dmp";break ;; *) echo;echo "Please Enter a Valid Answer [Y|N]" echo "---------------------------------";; esac done cd ${LOC1} SPOOLFILE1=${LOC1}/BEFORE_IMPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.sql SPOOLFILE2=${LOC1}/AFTER_IMPORT_SCHEMA_${ORACLE_SID}_${DUMPDATE}.sql echo "Creating the Exporter User DBA_BUNDLEEXP7 ..." echo "Preparing the BEFORE and AFTER import script which will help you import the dump file later ..." VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT CREATE USER DBA_BUNDLEEXP7 [EXPORTER USER] (WILL BE DROPPED AFTER THE EXPORT) ... CREATE USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; ALTER USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; GRANT CREATE SESSION TO DBA_BUNDLEEXP7; GRANT DBA TO DBA_BUNDLEEXP7; -- The following privileges to workaround Bug 6392040: GRANT EXECUTE ON SYS.DBMS_DEFER_IMPORT_INTERNAL TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_EXPORT_EXTENSION TO DBA_BUNDLEEXP7; PROMPT PROMPT CREATING DIRECTORY EXPORT_FILES_DBA_BUNDLE POINTING TO ${LOC1} ... CREATE OR REPLACE DIRECTORY EXPORT_FILES_DBA_BUNDLE AS '${LOC1}'; PROMPT PROMPT CREATING BEFORE SCHEMA IMPORT SCRIPT ... PROMPT SET PAGES 0 TERMOUT OFF LINESIZE 157 ECHO OFF FEEDBACK OFF SPOOL ${SPOOLFILE1} SELECT 'CREATE USER ' || u.username ||' IDENTIFIED ' ||' BY VALUES ''' || c.password || ''' DEFAULT TABLESPACE ' || u.default_tablespace ||' TEMPORARY TABLESPACE ' || u.temporary_tablespace ||' PROFILE ' || u.profile || case when account_status= 'OPEN' then ';' else ' Account LOCK;' end "--Creation Statement" FROM dba_users u,user$ c where u.username=c.name and u.username in (${SCHEMALIST}) UNION SELECT 'CREATE ROLE '||GRANTED_ROLE||';' FROM DBA_ROLE_PRIVS WHERE GRANTEE in (${SCHEMALIST}) UNION select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted Roles" from dba_role_privs where grantee in (${SCHEMALIST}) UNION select 'GRANT '||PRIVILEGE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted System Privileges" from dba_sys_privs where grantee in (${SCHEMALIST}) UNION select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where GRANTEE in (${SCHEMALIST}); SPOOL OFF PROMPT CREATING AFTER SCHEMA IMPORT SCRIPT ... PROMPT SPOOL ${SPOOLFILE2} select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where OWNER in (${SCHEMALIST}) UNION SELECT 'CREATE PUBLIC SYNONYM '||SYNONYM_NAME||' FOR '||TABLE_OWNER||'.'||TABLE_NAME||';' FROM DBA_SYNONYMS WHERE TABLE_OWNER in (${SCHEMALIST}) AND OWNER=UPPER('PUBLIC'); PROMPT SELECT 'PROMPT COMPILING DATABASE INVALID OBJECTS ...' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT '@?/rdbms/admin/utlrp' FROM DUAL; SELECT 'PROMPT ' FROM DUAL; SELECT 'PROMPT THE FOLLOWING TRIGGERS ARE OWNED BY OTHER USERS BUT ARE DEPENDANT ON THE EXPORTED SCHEMA OBJECTS' FROM DUAL; SELECT 'PROMPT YOU MAY CONSIDER TO CREATE THEM AFTER THE SCHEMA IMPORT IF YOU NEED SO:' FROM DUAL; SELECT 'PROMPT **********************************************************************' FROM DUAL; SELECT 'PROMPT '||TRIGGER_TYPE||' TRIGGER: '||OWNER||'.'||TRIGGER_NAME||' =>ON TABLE: '||TABLE_OWNER||'.'||TABLE_NAME FROM DBA_TRIGGERS WHERE TABLE_OWNER in (${SCHEMALIST}) AND OWNER not in (${SCHEMALIST}) ORDER BY 1; SPOOL OFF EOF ) # Creation of the Post Export Script: export EXPORTSCRIPT=${LOC1}/EXPORTSCRIPT.sh export EXPORTSCRIPTRUNNER=${LOC1}/EXPORTSCRIPTRUNNER.sh echo "# Export Script: [Created By DBA_BUNDLE]" > ${EXPORTSCRIPT} echo "export ORACLE_SID=${ORACLE_SID}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running The Export Job Now ...'" >>${EXPORTSCRIPT} echo "${MKNOD}" >>${EXPORTSCRIPT} echo "sleep 1" >>${EXPORTSCRIPT} echo "${ZIP}" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/exp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" OWNER=${SCHEMASVAR} DIRECT=y CONSISTENT=y STATISTICS=NONE FEEDBACK=100000 ${EXPORTSCN} RESUMABLE=y RESUMABLE_NAME=DBA_BUNDLE_EXPORT RESUMABLE_TIMEOUT=86400 FILE=${EXPORTDUMP} log=${LOGFILE}">>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running Post Export Steps ...'" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF" >>${EXPORTSCRIPT} echo "PROMPT" >>${EXPORTSCRIPT} echo "PROMPT DROPPING THE EXPORTER USER DBA_BUNDLEEXP7 (SAFELY) ..." >>${EXPORTSCRIPT} echo "DROP USER DBA_BUNDLEEXP7;" >>${EXPORTSCRIPT} echo "EOF" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "sleep 3" >>${EXPORTSCRIPT} echo "${REMOVEMKDON}" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"IMPORT GUIDELINES:\"" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"FLASHBACK SCN used for this export is: ${CURRENT_SCN}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"${UNZIPMESSAGE}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"BEFORE IMPORTING THE DUMPFILE IT'S RECOMMENDED TO RUN THIS SQL SCRIPT: ${SPOOLFILE1}\"" >>${EXPORTSCRIPT} echo "echo \"It includes (USER|ROLES|GRANTED PRIVILEGES CREATION STATEMENTS), WHICH WILL NOT BE CREATED DURING THE IMPORT PROCESS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"AFTER IMPORTING THE DUMPFILE, RUN THIS SQL SCRIPT: ${SPOOLFILE2}\"" >>${EXPORTSCRIPT} echo "echo \"It includes (Public Synonyms DDLs, Privileges granted to others, Hints for Triggers owned by others but depending on the exported schemas objects) + COMPILING INVALID OBJECTS, SUCH STUFF WILL NOT BE CARRIED OUT BY THE IMPORT PROCESS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "echo \"EXPORT DUMP FILE LOCATION: ${EXPORTDUMPOUTPUT}\"" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "export JOBSTATUS=\`grep \"successfully\\|stopped\\|completed\" ${LOGFILE}|tail -1\`" >>${EXPORTSCRIPT} echo "export LOGFILE=${LOGFILE}" >>${EXPORTSCRIPT} echo "export EMAILID=\"${EMAILANS}\"" >>${EXPORTSCRIPT} echo "${SENDEMAIL}" >>${EXPORTSCRIPT} chmod 740 ${EXPORTSCRIPT} echo echo "#!/bin/bash" > ${EXPORTSCRIPTRUNNER} echo "nohup sh ${EXPORTSCRIPT}| tee ${LOGFILE} 2>&1 &" >>${EXPORTSCRIPTRUNNER} chmod 740 ${EXPORTSCRIPTRUNNER} echo -e "\033[32;5mFeel free to EXIT from this session as the EXPORT SCRIPT is running in the BACKGROUND.\033[0m" source ${EXPORTSCRIPTRUNNER} ## Export METADATA ONLY: #echo #echo "CREATING A FILE CONTAINS ALL CREATION [DDL] STATEMENT OF ALL USERS|OBJECTS ..." #sleep 1 #${ORACLE_HOME}/bin/exp DBA_BUNDLEEXP7/"BUNdle_#-^${PASSHALF}" OWNER=${SCHEMA_NAME} ROWS=N STATISTICS=NONE FILE=${LOC1}/${SCHEMA_NAME}_${ORACLE_SID}_METADATA_${DUMPDATE}.dmp log=${LOC1}/${SCHEMA_NAME}_${ORACLE_SID}_METADATA_${DUMPDATE}.log ## Removing Extra Bad characters: [DUMP REFINING] #/usr/bin/strings ${LOC1}/${SCHEMA_NAME}_${ORACLE_SID}_METADATA_${DUMPDATE}.dmp > ${LOC1}/${SCHEMA_NAME}_${ORACLE_SID}_METADATA_REFINED_${DUMPDATE}.trc echo; exit ;; *) echo "Enter a valid number:" echo "=====================" echo "i.e." echo "1 for expdp tool" echo "2 for exp tool" echo ;; esac done break;; 3|"EXPORT TABLES"|"TABLES"|"tables"|"table") echo; echo "Entering EXPORT TABLE MODE ...";echo;sleep 1 # ##################### # EXPORT TABLE SECTION: # ##################### echo echo "Enter the TABLES you want to export, separating them by comma:" echo "==============================================================" echo "i.e. HR.EMPLOYEES,HR.DEPARTMENTS,SCOTT.BONUS" echo "" while read TABLESVAR do case ${TABLESVAR} in "") echo; echo "Please mention the tables you want to export:" echo "--------------------------------------------" echo "i.e. HR.EMPLOYEES,HR.DEPARTMENTS,SCOTT.BONUS" echo "";; *) echo # Convert User's input into UPPERCASE: export TABLESVAR="$(echo ${TABLESVAR}| tr [:lower:] [:upper:])" export TABLELIST="'$(sed s/,/\',\'/g <<<${TABLESVAR}| tr '[:lower:]' '[:upper:]')'"; break ;; esac done echo "WHICH EXPORT UTILITY YOU WANT TO USE: [1) DATAPUMP [EXPDP]]" echo "====================================" echo "1) DATAPUMP [EXPDP] |Pros: Faster when import, Cloud/PARALLELISM compatible, can Exclude schema/tables |Cons: COMPRESSION requires license" echo "2) LEGACY EXPORT [EXP] |Pros: COMPRESSION can happen on the fly without license |Cons: Slower when import, No Cloud/PARALLELISM compatibility" while read EXP_TOOL do case $EXP_TOOL in ""|"1"|"DATAPUMP"|"datapump"|"DATAPUMP [EXPDP]"|"[EXPDP]"|"EXPDP"|"expdp") if [[ ${CHK_PARALLELISM_OPTION} =~ ${INT} ]] then if [ ${CHK_PARALLELISM_OPTION} -eq 1 ] then echo echo "Enter the PARALLEL DEGREE you want to perform the export with PARALLELISM? [If used, The final dump file will be divided into multiple files!]" echo "=========================================================================" echo "[Current CPU Count on this Server is: ${PARALLEL_DEGREE}]" echo "Enter a number bigger than 1 to utilize PARALLELISM or enter 0 to disable PARALLELISM" echo "" while read PARALLEL_ANS do # Check if the input is an integer: if [[ ${PARALLEL_ANS} =~ ${INT} ]] then # Check if the input is greater than 1: if [ ${PARALLEL_ANS} -gt 1 ] then export PARALLEL="PARALLEL=${PARALLEL_ANS}" export PARA="_%u" echo -e "\033[32;5mPARALLELISM ENABLED | The final dump file will be divided into multiple files based on the degree of parallelism you used.\033[0m" else echo "PARALLELISM DISABLED." fi break fi done else echo;echo -e "\033[32;5mPARALLELISM option is not available in the current Database Edition.\033[0m" fi fi # PARAMETER FILE CREATION: export DUMPFILENAME="EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}${PARA}.dmp" export LOGFILE="${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.log" # PARAMETER FILE CREATION: PARFILE=${LOC1}/EXPORT_TABLE_DB_${ORACLE_SID}.par echo "# TABLE EXPORT PARAMETER FILE CREATED BY export_data.sh SCRIPT on [${DUMPDATE}]:" > ${PARFILE} echo "DIRECTORY=EXPORT_FILES_DBA_BUNDLE" >> ${PARFILE} echo "DUMPFILE=${DUMPFILENAME}" >> ${PARFILE} echo "LOGFILE=EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.log" >> ${PARFILE} echo "${EXPORTSCN}" >> ${PARFILE} echo "${REUSE_DUMP}" >> ${PARFILE} echo "TABLES=${TABLESVAR}" >> ${PARFILE} echo "${PARALLEL}" >> ${PARFILE} echo echo "Do you want to enable the COMPRESSION [Y|N] [N] [Do NOT answer with YES unless you already have the Advanced Compression License]" echo "=====================================" while read COMP_ANS do case $COMP_ANS in y|Y|yes|YES|Yes) echo;echo "COMPRESSION=ALL" >> ${PARFILE};echo -e "\033[32;5mCompression Enabled.\033[0m";echo; break ;; ""|n|N|no|NO|No) echo; break ;; *) echo;echo "Please Enter a Valid Answer: [Y|N]" echo "----------------------------";; esac done echo "Creating the Exporter User DBA_BUNDLEEXP7 ..." echo "Preparing the BEFORE and AFTER import script which will help you import the dump file later ..." SPOOLFILE2=${LOC1}/AFTER_IMPORT_TABLE_${DUMPDATE}.sql VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT CREATE USER DBA_BUNDLEEXP7 [EXPORTER USER] (WILL BE DROPPED AFTER THE EXPORT) ... CREATE USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; ALTER USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; GRANT CREATE SESSION TO DBA_BUNDLEEXP7; GRANT DBA TO DBA_BUNDLEEXP7; -- The following privileges to workaround Bug 6392040: GRANT EXECUTE ON SYS.DBMS_DEFER_IMPORT_INTERNAL TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_EXPORT_EXTENSION TO DBA_BUNDLEEXP7; PROMPT CREATING DIRECTORY EXPORT_FILES_DBA_BUNDLE POINTING TO ${LOC1} ... CREATE OR REPLACE DIRECTORY EXPORT_FILES_DBA_BUNDLE AS '${LOC1}'; PROMPT PROMPT CREATING AFTER TABLE IMPORT SCRIPT ... PROMPT SET PAGES 0 TERMOUT OFF LINESIZE 157 ECHO OFF FEEDBACK OFF SPOOL ${SPOOLFILE2} SELECT 'CREATE SYNONYM '||OWNER||'.'||SYNONYM_NAME||' FOR '||TABLE_OWNER||'.'||TABLE_NAME||';' FROM DBA_SYNONYMS WHERE TABLE_OWNER||'.'||TABLE_NAME in (${TABLELIST}) AND OWNER <> UPPER('PUBLIC') UNION SELECT 'CREATE PUBLIC SYNONYM '||SYNONYM_NAME||' FOR '||TABLE_OWNER||'.'||TABLE_NAME||';' FROM DBA_SYNONYMS WHERE TABLE_OWNER||'.'||TABLE_NAME in (${TABLELIST}) AND OWNER=UPPER('PUBLIC'); SPOOL OFF EOF ) # Creation of the Export Script: export EXPORTSCRIPT=${LOC1}/EXPORTSCRIPT.sh export EXPORTSCRIPTRUNNER=${LOC1}/EXPORTSCRIPTRUNNER.sh echo "# Export Script: [Created By DBA_BUNDLE]" > ${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"While the Export job is running, you can check the STATUS using:\"" >>${EXPORTSCRIPT} echo "echo \"--------------------------------------------------------------- \"" >>${EXPORTSCRIPT} echo "echo \"SELECT job_name, operation, job_mode, DEGREE, state FROM dba_datapump_jobs where OPERATION='EXPORT' and state='EXECUTING' and owner_name='DBA_BUNDLEEXP7';\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"Then you can ATTACH to the export job and control it using:\"" >>${EXPORTSCRIPT} echo "echo \"---------------------------------------------------------- \"" >>${EXPORTSCRIPT} echo "echo \"expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=\"" >>${EXPORTSCRIPT} echo "echo \"i.e.\"" >>${EXPORTSCRIPT} echo "echo \"expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" ATTACH=SYS_EXPORT_TABLE_01\"" >>${EXPORTSCRIPT} echo "echo \"To Show the STATUS:....... STATUS\"" >>${EXPORTSCRIPT} echo "echo \"To KILL the export:....... KILL_JOB\"" >>${EXPORTSCRIPT} echo "echo \"To PAUSE the export:...... STOP_JOB\"" >>${EXPORTSCRIPT} echo "echo \"To RESUME a paused export: START_JOB\"" >>${EXPORTSCRIPT} echo "export ORACLE_SID=${ORACLE_SID}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running The Export Job Now ...'" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/expdp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" PARFILE=${PARFILE}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running Post Export Steps ...'" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF" >>${EXPORTSCRIPT} echo "PROMPT" >>${EXPORTSCRIPT} echo "PROMPT DROPPING THE EXPORTER USER DBA_BUNDLEEXP7 (SAFELY) ..." >>${EXPORTSCRIPT} echo "DROP USER DBA_BUNDLEEXP7;" >>${EXPORTSCRIPT} echo "EOF" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"IMPORT GUIDELINES:\"" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"FLASHBACK SCN used for this export is: ${CURRENT_SCN}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"AFTER IMPORTING THE DUMPFILE, RUN THIS SQL SCRIPT: ${SPOOLFILE2}\"" >>${EXPORTSCRIPT} echo "echo \"IT INCLUDES (PRIVATE & PUBLIC SYNONYMS DDLS) WHICH WILL NOT BE HANDELED BY THE IMPORT PROCESS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "echo \"EXPORT DUMP FILE LOCATION: ${LOC1}/${DUMPFILENAME}\"" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "export JOBSTATUS=\`grep \"successfully\\|stopped\\|completed\" ${LOGFILE}|tail -1\`" >>${EXPORTSCRIPT} echo "export LOGFILE=${LOGFILE}" >>${EXPORTSCRIPT} echo "export EMAILID=\"${EMAILANS}\"" >>${EXPORTSCRIPT} echo "${SENDEMAIL}" >>${EXPORTSCRIPT} chmod 740 ${EXPORTSCRIPT} echo echo "#!/bin/bash" > ${EXPORTSCRIPTRUNNER} echo "nohup sh ${EXPORTSCRIPT}| tee ${LOGFILE} 2>&1 &" >>${EXPORTSCRIPTRUNNER} chmod 740 ${EXPORTSCRIPTRUNNER} echo -e "\033[32;5mFeel free to EXIT from this session as the EXPORT SCRIPT is running in the BACKGROUND.\033[0m" source ${EXPORTSCRIPTRUNNER} echo; exit ;; "2"|"LEGACY EXPORT"|"LEGACY"|"EXPORT"|"LEGACY EXPORT [EXP]"|"EXP"|"[EXP]"|"exp"|"legacy export"|"legacy"|"export") export EXPORTDUMP="${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.dmp" export LOGFILE="${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.log" echo echo "Do you want to enable the COMPRESSION [Y|N] [N] [COMPRESSION will happen on the fly using mknod | No License required]" echo "=====================================" while read COMP_ANS do case $COMP_ANS in y|Y|yes|YES|Yes) echo;export EXPORTDUMP="${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}_pipe.dmp" export MKNOD="rm -f ${EXPORTDUMP}; mknod ${EXPORTDUMP} p" export ZIP="nohup bzip2 -fz < ${EXPORTDUMP} > ${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.dmp.bz2 &" export EXPORTDUMPOUTPUT="${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.dmp.bz2" export REMOVEMKDON="rm -f ${EXPORTDUMP}" export UNZIPMESSAGE="First DE-COMPRESS the file using this command: bunzip2 -f ${EXPORTDUMPOUTPUT}" echo -e "\033[32;5mCompression Enabled.\033[0m";echo; break ;; ""|n|N|no|NO|No) echo;export MKNOD="" export ZIP="" export EXPORTDUMP="${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.dmp" export EXPORTDUMPOUTPUT="${LOC1}/EXPORT_TABLE_${ORACLE_SID}_${DUMPDATE}.dmp";break ;; *) echo;echo "Please Enter a Valid Answer [Y|N]" echo "---------------------------------";; esac done SPOOLFILE2=${LOC1}/AFTER_IMPORT_TABLE_DB_${ORACLE_SID}_${DUMPDATE}.sql echo "Creating the Exporter User DBA_BUNDLEEXP7 ..." echo "Preparing the BEFORE and AFTER import script which will help you import the dump file later ..." VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT CREATE USER DBA_BUNDLEEXP7 [EXPORTER USER] (WILL BE DROPPED AFTER THE EXPORT) ... CREATE USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; ALTER USER DBA_BUNDLEEXP7 IDENTIFIED BY "BUNdle_#-^${PASSHALF}"; GRANT CREATE SESSION TO DBA_BUNDLEEXP7; GRANT DBA TO DBA_BUNDLEEXP7; -- The following privileges to workaround Bug 6392040: GRANT EXECUTE ON SYS.DBMS_DEFER_IMPORT_INTERNAL TO DBA_BUNDLEEXP7; GRANT EXECUTE ON SYS.DBMS_EXPORT_EXTENSION TO DBA_BUNDLEEXP7; PROMPT CREATING DIRECTORY EXPORT_FILES_DBA_BUNDLE POINTING TO ${LOC1} ... CREATE OR REPLACE DIRECTORY EXPORT_FILES_DBA_BUNDLE AS '${LOC1}'; PROMPT PROMPT CREATING AFTER TABLE IMPORT SCRIPT ... PROMPT SET PAGES 0 TERMOUT OFF LINESIZE 157 ECHO OFF FEEDBACK OFF SPOOL ${SPOOLFILE2} SELECT 'CREATE SYNONYM '||OWNER||'.'||SYNONYM_NAME||' FOR '||TABLE_OWNER||'.'||TABLE_NAME||';' FROM DBA_SYNONYMS WHERE TABLE_OWNER||'.'||TABLE_NAME in (${TABLELIST}) AND OWNER <> UPPER('PUBLIC') UNION SELECT 'CREATE PUBLIC SYNONYM '||SYNONYM_NAME||' FOR '||TABLE_OWNER||'.'||TABLE_NAME||';' FROM DBA_SYNONYMS WHERE TABLE_OWNER||'.'||TABLE_NAME in (${TABLELIST}) AND OWNER=UPPER('PUBLIC'); SPOOL OFF EOF ) # Creation of the Post Export Script: export EXPORTSCRIPT=${LOC1}/EXPORTSCRIPT.sh export EXPORTSCRIPTRUNNER=${LOC1}/EXPORTSCRIPTRUNNER.sh echo "# Export Script: [Created By DBA_BUNDLE]" > ${EXPORTSCRIPT} echo "export ORACLE_SID=${ORACLE_SID}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running The Export Job Now ...'" >>${EXPORTSCRIPT} echo "${MKNOD}" >>${EXPORTSCRIPT} echo "sleep 1" >>${EXPORTSCRIPT} echo "${ZIP}" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/exp DBA_BUNDLEEXP7/\"BUNdle_#-^${PASSHALF}\" TABLES=${TABLESVAR} DIRECT=y CONSISTENT=y STATISTICS=NONE FEEDBACK=100000 ${EXPORTSCN} RESUMABLE=y RESUMABLE_NAME=DBA_BUNDLE_EXPORT RESUMABLE_TIMEOUT=86400 FILE=${EXPORTDUMP} log=${LOGFILE}" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo 'Running Post Export Steps ...'" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF" >>${EXPORTSCRIPT} echo "PROMPT" >>${EXPORTSCRIPT} echo "PROMPT DROPPING THE EXPORTER USER DBA_BUNDLEEXP7 (SAFELY) ..." >>${EXPORTSCRIPT} echo "DROP USER DBA_BUNDLEEXP7;" >>${EXPORTSCRIPT} echo "EOF" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "sleep 3" >>${EXPORTSCRIPT} echo "${REMOVEMKDON}" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"IMPORT GUIDELINES:\"" >>${EXPORTSCRIPT} echo "echo \"*****************\"" >>${EXPORTSCRIPT} echo "echo \"FLASHBACK SCN used for this export is: ${CURRENT_SCN}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"${UNZIPMESSAGE}\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"AFTER IMPORTING THE DUMPFILE, RUN THIS SQL SCRIPT: ${SPOOLFILE2}\"" >>${EXPORTSCRIPT} echo "echo \"IT INCLUDES (PRIVATE & PUBLIC SYNONYMS DDLS) WHICH WILL NOT BE HANDELED BY THE IMPORT PROCESS.\"" >>${EXPORTSCRIPT} echo "echo ''" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "echo \"EXPORT DUMP FILE LOCATION: ${EXPORTDUMPOUTPUT}\"" >>${EXPORTSCRIPT} echo "echo \"**************************\"" >>${EXPORTSCRIPT} echo "export JOBSTATUS=\`grep \"successfully\\|stopped\\|completed\" ${LOGFILE}|tail -1\`" >>${EXPORTSCRIPT} echo "export LOGFILE=${LOGFILE}" >>${EXPORTSCRIPT} echo "export EMAILID=\"${EMAILANS}\"" >>${EXPORTSCRIPT} echo "${SENDEMAIL}" >>${EXPORTSCRIPT} chmod 740 ${EXPORTSCRIPT} echo echo "#!/bin/bash" > ${EXPORTSCRIPTRUNNER} echo "nohup sh ${EXPORTSCRIPT}| tee ${LOGFILE} 2>&1 &" >>${EXPORTSCRIPTRUNNER} chmod 740 ${EXPORTSCRIPTRUNNER} echo -e "\033[32;5mFeel free to EXIT from this session as the EXPORT SCRIPT is running in the BACKGROUND.\033[0m" source ${EXPORTSCRIPTRUNNER} echo; exit ;; *) echo "Enter a valid number:" echo "=====================" echo "i.e." echo "1 for expdp tool" echo "2 for exp tool" echo ;; esac done break;; *) echo "Enter a NUMBER between 1 to 3 boss:" echo "==================================" ;; esac done # ############# # END OF SCRIPT # ############# # Your feedback is highly appreciated, you can Email it to: mahmmoudadel@hotmail.com # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # Every month there is a new version of DBA BUNDLE is getting released, you can download it from this link: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/aliases_DBA_BUNDLE.sh 0000740 0152073 0152061 00000145377 14071551775 016154 0 ustar oracle oinstall # ############################################################################################################################################# # DBA BUNDLE Main Script For Setting the Environment Variables and Command Aliases. # Ver 5.9 # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 02-01-14 # # # # # # Modified: 13-01-14 # Force using "." command # 01-10-16 Added more aliases # 27-12-17 Added more aliases for new scripts for V[4.0] # 14-02-18 SQLPLUS to use login.sql.sav under bundle directory # 20-03-18 Added raclog/asmalert aliases for clusterware and ASM instance. # 30-10-18 Enhance the way of locating raclog. # 31-10-18 Added crss/clusterstatus alias, to display cluster services status. # 20-01-19 Enhanced the logic of locating ASMALERT, GRID_HOME, GRID_BASE, GRID ALERTLOG and ORACLE_HOME. # 18-11-19 Made GRID_HOME variable permanent to avoid the need of exporting it before running crss command. # 11-06-20 Enhance the bdump location fetch. # 21-06-20 Reformatting crss command output to be compatible with 12c+ # 15-07-20 Fixing the looping of PATH values in .DBA_BUNDLE_profile # 15-07-20 Disable the display of aliases hints if the user provide any extra argument while executing the script. i.e. bundle 1 # 23-09-20 Removed the constraint of extractng the bundle under ORACLE user home dir. # 12-10-20 Add sqltune alias for sql_tune.sh script # ############################################################################################################################################# export SCRIPT_NAME="aliases_DBA_BUNDLE" export BUNDLE_NAME="DBA_BUNDLE6" export SRV_NAME=`uname -n` # ########################### # BUNDLE LOCATION: # ########################### export BUNDLE_LOC=${PWD} USEDCOMM=`history|tail -1|awk '{print $2}'|egrep '(bundle|source|\.)'|grep -v '\.\/'` if [ -z "${USEDCOMM}" ] then echo "" echo "Please Use \".\" command to run this script." echo "e.g." echo ". ${BUNDLE_LOC}/aliases_DBA_BUNDLE.sh" echo "" exit 1 return fi # ########################### # Extract The Bundle: [The user should do it manually to avoid mistakes] # ########################### # Check the existence of the TAR file: # if [ -f ./${BUNDLE_NAME}.tar ] # then # echo "Extracting The DBA_BUNDLE..." # tar xvf ./DBA_BUNDLE.tar # else # echo "The TAR file DBA_BUNDLE.tar is not exist under the current working directory !" # echo "Please copy the TAR file DBA_BUNDLE.tar to the current working directory and re-run the script." # exit # fi # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo "No Database is Running !" echo return fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo "---------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[0-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] || [ ${REPLY} -eq 0 ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi echo "Setting ORACLE_HOME ..." # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################## # Getting ORACLE_BASE: # ######################## echo "Setting ORACLE_BASE ..." # Get ORACLE_BASE from user's profile if it EMPTY: if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`cat ${ORACLE_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export ORACLE_BASE fi if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`grep -h 'ORACLE_BASE=\/' ${USR_ORA_HOME}/.bash* ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi # ######################### # Getting DB_NAME: # ######################### echo "Getting DB NAME ..." DB_NAME_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${USRPROF}.tmp && mv ${USRPROF}.tmp ${USRPROF} echo "# The Following Entry For DBA_BUNDLE Aliases" >> ${USRPROF} echo ". ${PROFILE}" >> ${USRPROF} fi if [ -f ${USR_ORA_HOME}/.profile ] then USRPROF=${USR_ORA_HOME}/.profile sed '/DBA_BUNDLE/d' ${USRPROF} > ${USRPROF}.tmp && mv ${USRPROF}.tmp ${USRPROF} echo "# The Following Entry For DBA_BUNDLE Aliases" >> ${USRPROF} echo ". ${PROFILE}" >> ${USRPROF} fi if [ -f ${USR_ORA_HOME}/.bash_profile ] then USRPROF=${USR_ORA_HOME}/.bash_profile sed '/DBA_BUNDLE/d' ${USRPROF} > ${USRPROF}.tmp && mv ${USRPROF}.tmp ${USRPROF} echo "# The Following Entry For DBA_BUNDLE Aliases" >> ${USRPROF} echo ". ${PROFILE}" >> ${USRPROF} fi # ######################## # Getting GRID_HOME: # ######################## CHECK_OCSSD=`ps -ef|grep 'ocssd.bin'|grep -v grep|wc -l` CHECK_CRSD=`ps -ef|grep 'crsd.bin'|grep -v grep|wc -l` if [ ${CHECK_OCSSD} -gt 0 ] then echo "Setting GRID_HOME ..." GRID_HOME=`ps -ef|grep 'ocssd.bin'|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v sed|grep -v "//g"|tail -1` export GRID_HOME if [ ! -d ${GRID_HOME} ] then ASM_INSTANCE_NAME=`ps -ef|grep pmon|grep -v grep|grep asm_pmon_|awk '{print $NF}'|sed -e 's/asm_pmon_//g'|grep -v sed|grep -v "s///g"|tail -1` GRID_HOME=`dbhome ${ASM_INSTANCE_NAME}` export GRID_HOME fi # Locating GRID_BASE: echo "Setting GRID_BASE ..." GRID_BASE=`cat ${GRID_HOME}/crs/install/crsconfig_params|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/crs/utl/appvipcfg|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi fi # ############################# # Getting hostname in lowercase: # ############################# HOSTNAMELOWER=$( echo "`hostname --short`"| tr '[A-Z]' '[a-z]' ) export HOSTNAMELOWER # ############################## # Locate ASM instance alert log: # ############################## ASMCOUNT=`ps -ef|grep -v grep|grep asm_pmon_|wc -l` if [ ${ASMCOUNT} -gt 0 ] then echo "[ASM Instance Found] Locating ASM Instance ALERTLOG ..." # Fetching ASM Instance name: ASM_INSTANCE_NAME=`ps -ef|grep pmon|grep -v grep|grep asm_pmon_|awk '{print $NF}'|sed -e 's/asm_pmon_//g'|grep -v sed|grep -v "s///g"|tail -1` export ASM_INSTANCE_NAME # Locating GRID_HOME: GRID_HOME=`ps -ef|grep ocssd|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v "ocssd.bin"|tail -1` export GRID_HOME if [ ! -d ${GRID_HOME} ] then GRID_HOME=`dbhome ${ASM_INSTANCE_NAME}` export GRID_HOME fi # Locating GRID_BASE: GRID_BASE=`cat $GRID_HOME/crs/install/crsconfig_params|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat $GRID_HOME/crs/utl/appvipcfg|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat $GRID_HOME/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi # Locating ASM ALERTLOG: ASMALERT=`ls -rtl ${GRID_BASE}/diag/asm/+asm/${ASM_INSTANCE_NAME}/trace/alert_+ASM*.log|tail -1|awk '{print $NF}'` export ASMALERT if [ ! -f ${ASMALERT} ] then if [ -x /usr/bin/locate ] then ASMALERT=`ls -rtl \`/usr/bin/locate alert_+ASM\`|tail -1|awk '{print $NF}'` export ASMALERT fi fi # Only UN-HASH when ASMALERT is set manually: # if [ ! -d ${GRID_BASE} ] # then # if [ -f ${ASMALERT} ] # then #GRID_BASE=`grep 'ORACLE_BASE from environment' ${ASMALERT} | awk '{print $(5)}'|tail -1` #export GRID_BASE # fi # fi fi # #################################### # Locate GRID INFRASTRUCTURE ALERTLOG: # #################################### # Locate ADR BASE: VAL_ADR_BASE=$(${ORACLE_HOME}/bin/adrci < ${CLUSTERWARE_STATUS_SCRIPT} #echo "awk 'BEGIN {printf \"%-50s %-10s %-18s\n\", \"HA Resource\", \"Target\", \"State\";printf \"%-50s %-10s %-18s\n\", \"-----------\", \"------\", \"-----\";}'; ${GRID_HOME}/bin/crsctl status resource | awk 'BEGIN { FS=\"=\"; state = 0; } \$1~/NAME/ && \$2~/'\$1'/ {appname = \$2; state=1};state == 0 {next;} \$1~/TARGET/ && state == 1 {apptarget = \$2; state=2;} \$1~/STATE/ && state == 2 {appstate = \$2; state=3;} state == 3 {printf \"%-50s %-10s %-18s\n\", appname, apptarget, appstate; state=0;}'|egrep -v 'ora.diskmon'" > ${CLUSTERWARE_STATUS_SCRIPT} EXCLUDED_SERVICES="ora.proxy_advm|ora.asmgroup|ora.diskmon|ora.ons" echo "${GRID_HOME}/bin/crsctl status res |grep -v \"^\$\"|awk -F \"=\" 'BEGIN {print \" \"} {printf(\"%s\",NR%4 ? \$2\"|\" : \$2\"\n\")}'|sed -e 's/ *, /,/g' -e 's/, /,/g'|awk -F \"|\" 'BEGIN { printf \"%-50s%-50s\n\",\"Resource Name\",\"STATUS\";printf \"%-50s%-50s\n\", \"-------------------------------------\",\"----------------------\"; }{ split (\$3,trg,\",\") split (\$4,st,\",\")}{for (i in trg) {printf \"%-50s%-50s\n\",\$1,st[i]}}'|egrep -v \"${EXCLUDED_SERVICES}\"" > ${CLUSTERWARE_STATUS_SCRIPT} if [ -f ${CLUSTERWARE_STATUS_SCRIPT} ] then chmod 740 ${CLUSTERWARE_STATUS_SCRIPT} fi fi # ########################################## # Setting the Environment & Commands Aliases # ########################################## echo "Lastly, Setting up the Environment Variables and Command Aliases ..." if [ -f ${BUNDLE_LOC}/aliases_DBA_BUNDLE.sh ] then PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/sbin:/usr/sbin:${ORACLE_HOME}/bin export PATH TNS_ADMIN=${ORACLE_HOME}/network/admin export TNS_ADMIN LD_LIBRARY_PATH=${ORACLE_HOME}/lib export LD_LIBRARY_PATH export PS1='[\u@\h \t \W]\$ ' #sed -i '/${BUNDLE_NAME}/d' ${PROFILE} if [ -f ${PROFILE} ]; then sed '/DBA_BUNDLE/d' ${PROFILE} > ${PROFILE}.tmp && mv ${PROFILE}.tmp ${PROFILE} fi echo "# ${BUNDLE_NAME} =====================================================================================" >> ${PROFILE} echo "# ${BUNDLE_NAME} The Following ALIASES Are Added By aliases_DBA_BUNDLE.sh Script [Part of ${BUNDLE_NAME}]" >> ${PROFILE} echo "# ${BUNDLE_NAME} =====================================================================================" >> ${PROFILE} echo "export ORACLE_SID=\"${ORACLE_SID}\" #${BUNDLE_NAME}" >> ${PROFILE} echo "export ORACLE_HOME=\"${ORACLE_HOME}\" #${BUNDLE_NAME}" >> ${PROFILE} echo "export LD_LIBRARY_PATH=\"${ORACLE_HOME}/lib\" #${BUNDLE_NAME}" >> ${PROFILE} echo "export TNS_ADMIN=\"${ORACLE_HOME}/network/admin\" #${BUNDLE_NAME}" >> ${PROFILE} echo "export PATH=\"/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/sbin:/usr/sbin:\${ORACLE_HOME}/bin:\${ORACLE_HOME}/OPatch\" #${BUNDLE_NAME}" >> ${PROFILE} echo "EDITOR=vi #${BUNDLE_NAME}" >> ${PROFILE} echo "export EDITOR #${BUNDLE_NAME}" >> ${PROFILE} echo "alias l='ls' #${BUNDLE_NAME}" >> ${PROFILE} echo "alias d='date' #${BUNDLE_NAME} >> Display the date." >> ${PROFILE} echo "alias df='df -hTP' #${BUNDLE_NAME}" >> ${PROFILE} echo "alias top='top -c' #${BUNDLE_NAME}" >> ${PROFILE} echo "alias ll='ls -rtlh' #${BUNDLE_NAME}" >> ${PROFILE} echo "alias lla='ls -rtlha' #${BUNDLE_NAME}" >> ${PROFILE} echo "alias cron='crontab -e' #${BUNDLE_NAME} >> Open the crontab for editing." >> ${PROFILE} echo "alias crol='crontab -l' #${BUNDLE_NAME} >> Display the crontab." >> ${PROFILE} echo "alias profile='. ${PROFILE}' #${BUNDLE_NAME} >> Call the user's profile to reload Environment Variables." >> ${PROFILE} echo "alias viprofile='view ${PROFILE}' #${BUNDLE_NAME} >> View the user's profile." >> ${PROFILE} echo "alias catprofile='cat ${PROFILE}' #${BUNDLE_NAME} >> Display the user's profile." >> ${PROFILE} echo "alias alert='tail -100f ${ALERTDB}' #${BUNDLE_NAME} >> Tail the default instance ALERTLOG file." >> ${PROFILE} echo "alias dbalert='tail -100f ${ALERTDB}' #${BUNDLE_NAME} >> Tail the default instance ALERTLOG file." >> ${PROFILE} echo "alias vialert='view ${ALERTDB}' #${BUNDLE_NAME} >> View the default instance ALERTLOG file." >> ${PROFILE} echo "alias asmalert='tail -100f ${ASMALERT}' #${BUNDLE_NAME} >> Tail the ASM instance ALERTLOG file." >> ${PROFILE} echo "alias alertasm='tail -100f ${ASMALERT}' #${BUNDLE_NAME} >> Tail the ASM instance ALERTLOG file." >> ${PROFILE} echo "alias viasmalert='view ${ASMALERT}' #${BUNDLE_NAME} >> View the ASM instance ALERTLOG file.">> ${PROFILE} echo "alias vialertasm='view ${ASMALERT}' #${BUNDLE_NAME} >> View the ASM instance ALERTLOG file.">> ${PROFILE} echo "alias sql='sqlplus "/ as sysdba" @${BUNDLE_LOC}/login.sql.bundle' #${BUNDLE_NAME} >> Open SQLPLUS console." >> ${PROFILE} echo "alias grid='cd ${GRID_HOME}; ls; pwd' #${BUNDLE_NAME} >> Step under GRID_HOME if installed." >> ${PROFILE} echo "alias gh='cd ${GRID_HOME};ls;pwd' #${BUNDLE_NAME} >> Step under GRID_HOME." >> ${PROFILE} echo "alias oh='cd ${ORACLE_HOME};ls;pwd' #${BUNDLE_NAME} >> Step under ORACLE_HOME." >> ${PROFILE} echo "alias bb=' cd ${BUNDLE_LOC};. aliases_DBA_BUNDLE.sh;cd -' #${BUNDLE_NAME} >> Set the default Instance for BUNDLE Commands." >> ${PROFILE} echo "alias bundle='. ${BUNDLE_LOC}/aliases_DBA_BUNDLE.sh' #${BUNDLE_NAME} >> Set the default Instance for BUNDLE Commands." >> ${PROFILE} echo "alias bundledir=' cd ${BUNDLE_LOC};pwd' #${BUNDLE_NAME} >> Step under Bundle directory." >> ${PROFILE} echo "alias bundle='cd ${BUNDLE_LOC};. aliases_DBA_BUNDLE.sh; cd -' #${BUNDLE_NAME} >> Set the default Instance for BUNDLE Commands." >> ${PROFILE} echo "alias p='ps -ef|grep pmon|grep -v grep' #${BUNDLE_NAME} >> List current RUNNING Instances." >> ${PROFILE} echo "alias lsn='ps -ef|grep tnslsnr|grep -v grep' #${BUNDLE_NAME} >> List current RUNNING Listeners." >> ${PROFILE} echo "alias bdump='cd ${BDUMP};ls -lrth|tail -10;pwd' #${BUNDLE_NAME} >> Step under bdump directory." >> ${PROFILE} echo "alias dbs='cd ${ORACLE_HOME}/dbs;ls -rtlh;pwd' #${BUNDLE_NAME} >> Step you under ORACLE_HOME/dbs directory." >> ${PROFILE} echo "alias rman='${ORACLE_HOME}/bin/rman target /' #${BUNDLE_NAME} >> Open the RMAN console." >> ${PROFILE} echo "alias lis='view ${ORACLE_HOME}/network/admin/listener.ora' #${BUNDLE_NAME} >> View listener.ora file." >> ${PROFILE} echo "alias tns='view ${ORACLE_HOME}/network/admin/tnsnames.ora' #${BUNDLE_NAME} >> View tnsnames.ora file." >> ${PROFILE} echo "alias sqlnet='view ${ORACLE_HOME}/network/admin/sqlnet.ora' #${BUNDLE_NAME} >> View sqlnet.ora file." >> ${PROFILE} echo "alias pfile='view ${ORACLE_HOME}/dbs/init${ORACLE_SID}.ora' #${BUNDLE_NAME} >> View the pfile." >> ${PROFILE} echo "alias aud='cd ${ORACLE_HOME}/rdbms/audit;ls -rtlh|tail -200' #${BUNDLE_NAME} >> Step under the audit logs directory." >> ${PROFILE} echo "alias network='cd ${ORACLE_HOME}/network/admin;ls -rtlh;pwd' #${BUNDLE_NAME} >> Step under Oracle Network files directory." >> ${PROFILE} echo "alias spfile='view ${ORACLE_HOME}/dbs/spfile${ORACLE_SID}.ora' #${BUNDLE_NAME} >> View the SPFILE." >> ${PROFILE} echo "alias raclog='tail -100f ${RACLOGFILE}' #${BUNDLE_NAME} >> tail the Clusterware ALERTLOG." >> ${PROFILE} echo "alias viraclog='view ${RACLOGFILE}' #${BUNDLE_NAME} >> view the Clusterware ALERTLOG." >> ${PROFILE} echo "alias clusterwarelog='tail -100f ${RACLOGFILE}' #${BUNDLE_NAME} >> Monitor Clusterware ALERTLOG on the fly." >> ${PROFILE} echo "alias crss='sh ${CLUSTERWARE_STATUS_SCRIPT}' #${BUNDLE_NAME} >> Check High Availability Resources Status." >> ${PROFILE} echo "alias clusterstatus='sh ${CLUSTERWARE_STATUS_SCRIPT}' #${BUNDLE_NAME} >> Check High Availability Resources Status." >> ${PROFILE} echo "alias removebundle='sh ${BUNDLE_LOC}/bundle_remove.sh' #${BUNDLE_NAME} >> Remove All Modifications done by aliases script." >> ${PROFILE} echo "alias dfs='sh ${BUNDLE_LOC}/datafiles.sh' #${BUNDLE_NAME} >> List All DATAFILES on the database." >> ${PROFILE} echo "alias datafiles='sh ${BUNDLE_LOC}/datafiles.sh' #${BUNDLE_NAME} >> List All DATAFILES on the database." >> ${PROFILE} echo "alias invalid='sh ${BUNDLE_LOC}/invalid_objects.sh' #${BUNDLE_NAME} >> List All Invalid Objects." >> ${PROFILE} echo "alias objects='sh ${BUNDLE_LOC}/biggest_100_objects.sh' #${BUNDLE_NAME} >> List Biggest 100 Object on the database." >> ${PROFILE} echo "alias lockuser='sh ${BUNDLE_LOC}/lock_user.sh' #${BUNDLE_NAME} >> lock a specific DB User Account." >> ${PROFILE} echo "alias lock='sh ${BUNDLE_LOC}/lock_user.sh' #${BUNDLE_NAME} >> lock a specific DB User Account." >> ${PROFILE} echo "alias userlock='sh ${BUNDLE_LOC}/lock_user.sh' #${BUNDLE_NAME} >> lock a specific DB User Account." >> ${PROFILE} echo "alias unlockuser='sh ${BUNDLE_LOC}/unlock_user.sh' #${BUNDLE_NAME} >> Unlock a specific DB User Account." >> ${PROFILE} echo "alias userunlock='sh ${BUNDLE_LOC}/unlock_user.sh' #${BUNDLE_NAME} >> Unlock a specific DB User Account." >> ${PROFILE} echo "alias unlock='sh ${BUNDLE_LOC}/unlock_user.sh' #${BUNDLE_NAME} >> Unlock a specific DB User Account." >> ${PROFILE} echo "alias sessions='sh ${BUNDLE_LOC}/all_sessions_info.sh' #${BUNDLE_NAME} >> List All current sessions on the DB." >> ${PROFILE} echo "alias session='sh ${BUNDLE_LOC}/session_details.sh' #${BUNDLE_NAME} >> List Details of a current session." >> ${PROFILE} echo "alias activesessions='sh ${BUNDLE_LOC}/active_sessions.sh' #${BUNDLE_NAME} >> List ALL ACTIVE Sessions." >> ${PROFILE} echo "alias active='sh ${BUNDLE_LOC}/active_sessions.sh' #${BUNDLE_NAME} >> List ALL ACTIVE Sessions." >> ${PROFILE} #echo "alias sess='sh /home/oracle/${BUNDLE_NAME}/all_sessions_info.sh|grep -v INACTIVE|grep -v Streams|grep -v \"Net message from client\"|grep -v \"class slave wait\"' #${BUNDLE_NAME} >> List Details of ACTIVE session." >> ${PROFILE} echo "alias sid='sh ${BUNDLE_LOC}/session_details.sh' #${BUNDLE_NAME} >> List Details of a current session." >> ${PROFILE} echo "alias locks='sh ${BUNDLE_LOC}/db_locks.sh' #${BUNDLE_NAME} >> Show Blocking LOCKS on the database" >> ${PROFILE} echo "alias sqlid='sh ${BUNDLE_LOC}/sql_tune.sh' #${BUNDLE_NAME} >> Tune a SQL Statmnt details." >> ${PROFILE} echo "alias sqltune='sh ${BUNDLE_LOC}/sql_tune.sh' #${BUNDLE_NAME} >> Tune a SQL Statmnt details." >> ${PROFILE} echo "alias parm='sh ${BUNDLE_LOC}/parameter_val.sh' #${BUNDLE_NAME} >> Show the value of a Visible/Hidden DB Parameter." >> ${PROFILE} echo "alias jobs='sh ${BUNDLE_LOC}/db_jobs.sh' #${BUNDLE_NAME} >> List All database Jobs." >> ${PROFILE} echo "alias spid='sh ${BUNDLE_LOC}/process_info.sh' #${BUNDLE_NAME} >> Show Session details providing its Unix PID." >> ${PROFILE} echo "alias tbs='sh ${BUNDLE_LOC}/tablespaces.sh' #${BUNDLE_NAME} >> List All TABLESPACES on the database." >> ${PROFILE} echo "alias tablespaces='sh ${BUNDLE_LOC}/tablespaces.sh' #${BUNDLE_NAME} >> List All TABLESPACES on the database." >> ${PROFILE} echo "alias cleanup='sh ${BUNDLE_LOC}/oracle_cleanup.sh' #${BUNDLE_NAME} >> Backup & Clean up All DB & its Listeners LOGs." >> ${PROFILE} echo "alias starttrace='sh ${BUNDLE_LOC}/start_tracing.sh' #${BUNDLE_NAME} >> Start TRACING an Oracle Session." >> ${PROFILE} echo "alias stoptrace='sh ${BUNDLE_LOC}/stop_tracing.sh' #${BUNDLE_NAME} >> Stop TRACING a traced Oracle Session." >> ${PROFILE} echo "alias objectddl='sh ${BUNDLE_LOC}/object_ddl.sh' #${BUNDLE_NAME} >> Generate the Creation DDL Statement for an OBJECT." >> ${PROFILE} echo "alias objectsize='sh ${BUNDLE_LOC}/object_size.sh' #${BUNDLE_NAME} >> Show the size of an OBJECT." >> ${PROFILE} echo "alias tablesize='sh ${BUNDLE_LOC}/object_size.sh' #${BUNDLE_NAME} >> Show the size of an OBJECT." >> ${PROFILE} echo "alias objectlocks='sh ${BUNDLE_LOC}/object_locks.sh' #${BUNDLE_NAME} >> Show all locks on an OBJECT." >> ${PROFILE} echo "alias oradebug='sh ${BUNDLE_LOC}/oradebug.sh' #${BUNDLE_NAME} >> Run ORADEBUG utility for hang analysis report." >> ${PROFILE} echo "alias userddl='sh ${BUNDLE_LOC}/user_ddl.sh' #${BUNDLE_NAME} >> Generate Full SQL Creation script for DB USER." >> ${PROFILE} echo "alias userdetail='sh ${BUNDLE_LOC}/user_details.sh' #${BUNDLE_NAME} >> Generate USER DDL plus Schema information." >> ${PROFILE} echo "alias schemadetails='sh ${BUNDLE_LOC}/user_details.sh' #${BUNDLE_NAME} >> Generate USER DDL plus Schema information." >> ${PROFILE} echo "alias roleddl='sh ${BUNDLE_LOC}/role_ddl.sh' #${BUNDLE_NAME} >> Generate Full SQL Creation script for DB ROLE." >> ${PROFILE} echo "alias roledetail='sh ${BUNDLE_LOC}/role_ddl.sh' #${BUNDLE_NAME} >> Generate Full SQL Creation script for DB ROLE." >> ${PROFILE} echo "alias lastlogin='sh ${BUNDLE_LOC}/last_logon_report.sh' #${BUNDLE_NAME} >> Report the last login date for ALL users on DB." >> ${PROFILE} echo "alias failedlogin='sh ${BUNDLE_LOC}/failed_logins.sh' #${BUNDLE_NAME} >> Report the last failed login attempts on the DB." >> ${PROFILE} echo "alias archivedel='sh ${BUNDLE_LOC}/Archives_Delete.sh' #${BUNDLE_NAME} >> Delete Archivelogs older than n number of days through RMAN." >> ${PROFILE} echo "alias analyze='sh ${BUNDLE_LOC}/analyze_tables.sh' #${BUNDLE_NAME} >> Analyze All Tables in a Schema." >> ${PROFILE} echo "alias audit='sh ${BUNDLE_LOC}/zAngA_zAngA.sh' #${BUNDLE_NAME} >> Retrieve AUDIT data for a DB user on a SPECIFIC DATE." >> ${PROFILE} echo "alias zanga='sh ${BUNDLE_LOC}/zAngA_zAngA.sh' #${BUNDLE_NAME} >> Retrieve AUDIT data for a DB user on a SPECIFIC DATE." >> ${PROFILE} echo "alias gather='sh ${BUNDLE_LOC}/gather_stats.sh' #${BUNDLE_NAME} >> Backup & Gather Statistics for a SPECIFIC SCHEMA|TABLE." >> ${PROFILE} echo "alias gatherstats='sh ${BUNDLE_LOC}/gather_stats.sh' #${BUNDLE_NAME} >> Backup & Gather Statistics for a SPECIFIC SCHEMA|TABLE." >> ${PROFILE} echo "alias gatherstatistics='sh ${BUNDLE_LOC}/gather_stats.sh' #${BUNDLE_NAME} >> Backup & Gather Statistics for a SPECIFIC SCHEMA|TABLE." >> ${PROFILE} echo "alias exportdata='sh ${BUNDLE_LOC}/export_data.sh' #${BUNDLE_NAME} >> Export Database | SCHEMA | Table data with EXP or EXPDP." >> ${PROFILE} echo "alias dataexport='sh ${BUNDLE_LOC}/export_data.sh' #${BUNDLE_NAME} >> Export Database | SCHEMA | Table data with EXP or EXPDP." >> ${PROFILE} echo "alias importdata='sh ${BUNDLE_LOC}/import_data.sh' #${BUNDLE_NAME} >> Import Database | SCHEMA | Table data with IMPDP." >> ${PROFILE} echo "alias dataimport='sh ${BUNDLE_LOC}/import_data.sh' #${BUNDLE_NAME} >> Import Database | SCHEMA | Table data with IMPDP." >> ${PROFILE} echo "alias rmanfull='sh ${BUNDLE_LOC}/RMAN_full.sh' #${BUNDLE_NAME} >> Takes an RMAN FULL DATABASE BACKUP." >> ${PROFILE} echo "alias tableinfo='sh ${BUNDLE_LOC}/table_info.sh' #${BUNDLE_NAME} >> Show ALL Important Information about specific TABLE." >> ${PROFILE} echo "alias tablerebuild='sh ${BUNDLE_LOC}/rebuild_table.sh' #${BUNDLE_NAME} >> REBUILD a TABLE and its related INDEXES." >> ${PROFILE} echo "alias rebuildtable='sh ${BUNDLE_LOC}/rebuild_table.sh' #${BUNDLE_NAME} >> REBUILD a TABLE and its related INDEXES." >> ${PROFILE} echo "alias allusersddl='sh ${BUNDLE_LOC}/all_users_ddl.sh' #${BUNDLE_NAME} >> Generate DDL Statement for all DB users." >> ${PROFILE} echo "alias asmdisks='sh ${BUNDLE_LOC}/asmdisks.sh' #${BUNDLE_NAME} >> Show ASM Disks info, its mount points and Labels." >> ${PROFILE} source ${PROFILE} # If the user provided any argument while executing the script, don't display the Aliases list: case $1 in '') echo "" echo "*******************" echo "LIST OF ALL ALIASES:" echo "*******************" echo echo " ===============================================================" echo "|Alias |Usage |" echo "|===============|===============================================|" echo "|bundle |Setup Aliases/Env Vars for a specific instance |" echo "|---------------|-----------------------------------------------|" echo "|removebundle |Remove bundle Aliases/Variables from the System|" echo "|---------------|-----------------------------------------------|" echo "|alert |tail -f the Database Instance Alertlog |" echo "|---------------|-----------------------------------------------|" echo "|asmalert |tail -f the ASM instance Alertlog |" echo "|---------------|-----------------------------------------------|" echo "|vialert |Open the Database Alertlog with vi editor |" echo "|---------------|-----------------------------------------------|" echo "|raclog |Open the Clusterware Alertlog [If found] |" echo "|---------------|-----------------------------------------------|" echo "|crss |Show Clusterware Services Status [If found] |" echo "|---------------|-----------------------------------------------|" echo "|lis |Open listener.ora file under ORACLE_HOME |" echo "|---------------|-----------------------------------------------|" echo "|tns |Open tnsnames.ora file under ORACLE_HOME |" echo "|---------------|-----------------------------------------------|" echo "|sqlnet |Open sqlnet.ora file under ORACLE_HOME |" echo "|---------------|-----------------------------------------------|" echo "|pfile |Open the PFILE under ORACLE_HOME/dbs |" echo "|---------------|-----------------------------------------------|" echo "|spfile |Open the SPFILE under ORACLE_HOME/dbs |" echo "|---------------|-----------------------------------------------|" echo "|oh |Go to ORACLE_HOME Dir |" echo "|---------------|-----------------------------------------------|" echo "|gh |Go to GRID_HOME Dir |" echo "|---------------|-----------------------------------------------|" echo "|dbs |Go to ORACLE_HOME/dbs |" echo "|---------------|-----------------------------------------------|" echo "|aud |Go to ORACLE_HOME/rdbms/audit |" echo "|---------------|-----------------------------------------------|" echo "|bdump |Go to BACKGROUND_DUMP_DEST |" echo "|---------------|-----------------------------------------------|" echo "|network |Go to ORACLE_HOME/network/admin |" echo "|---------------|-----------------------------------------------|" echo "|p |List the Current Running Instances |" echo "|---------------|-----------------------------------------------|" echo "|lsn |List the Current Running Listeners |" echo "|---------------|-----------------------------------------------|" echo "|dfs / datafiles|List All DATAFILES on a database |" echo "|---------------|-----------------------------------------------|" echo "|tbs/tablespaces|List All TABLESPACES on a database |" echo "|---------------|-----------------------------------------------|" echo "|invalid |List All Invalid Objects + Compile statements |" echo "|---------------|-----------------------------------------------|" echo "|objects |List the Biggest 100 Objects in the database |" echo "|---------------|-----------------------------------------------|" echo "|session / sid |List Details of a current oracle session |" echo "|---------------|-----------------------------------------------|" echo "|sessions |List All current sessions details on RAC DB |" echo "|---------------|-----------------------------------------------|" echo "|active |List ACTIVE SESSIONS/Other Activities on the DB|" echo "|---------------|-----------------------------------------------|" echo "|spid |Show DB Session details Based on its Unix PID |" echo "|---------------|-----------------------------------------------|" echo "|sqltune / sqlid|Show/Tune SQL Statement Based on its SQL_ID |" echo "|---------------|-----------------------------------------------|" echo "|locks |Show Blocking LOCKS on the database |" echo "|---------------|-----------------------------------------------|" echo "|lockuser |Lock a specific DB User Account |" echo "|---------------|-----------------------------------------------|" echo "|unlockuser |Unlock a specific DB User Account |" echo "|---------------|-----------------------------------------------|" echo "|parm |Show a Visible/Hidden DB Parameter Value |" echo "|---------------|-----------------------------------------------|" echo "|cleanup |Backup & Clean up DBs & their Listener LOGs |" echo "|---------------|-----------------------------------------------|" echo "|lastlogin |Shows the last login date for ALL users on DB |" echo "|---------------|-----------------------------------------------|" echo "|starttrace |Start TRACING an Oracle Session |" echo "|---------------|-----------------------------------------------|" echo "|stoptrace |Stop TRACING a current Traced Oracle Session |" echo "|---------------|-----------------------------------------------|" echo "|userddl |Generate Full SQL Creation script for a DB User|" echo "|---------------|-----------------------------------------------|" echo "|schemadetails |Generate USER DDL + Schema Information |" echo "|---------------|-----------------------------------------------|" echo "|roleddl |Generate Full SQL Creation script for a DB ROLE|" echo "|---------------|-----------------------------------------------|" echo "|objectddl |Generate Full SQL Creation script for an Object|" echo "|---------------|-----------------------------------------------|" echo "|objectsize |Show the size of an Object and its indexes |" echo "|---------------|-----------------------------------------------|" echo "|objectlocks |Show all locks on an object |" echo "|---------------|-----------------------------------------------|" echo "|failedlogin |Show Failed Login Attempts in the last n days |" echo "|---------------|-----------------------------------------------|" echo "|archivedel |Delete Archivelogs older than n number of days |" echo "|---------------|-----------------------------------------------|" echo "|analyze |Analyze All tables in a specific SCHEMA |" echo "|---------------|-----------------------------------------------|" echo "|audit / zanga |Retrieve AUDIT data for DB users |" echo "|---------------|-----------------------------------------------|" echo "|oradebug |Run ORADEBUG utility for hang analysis report |" echo "|---------------|-----------------------------------------------|" echo "|gather |Gather STATISTICS on a SCHEMA or TABLE |" echo "|---------------|-----------------------------------------------|" echo "|rmanfull |Take RMAN FULL BACKUP for a database |" echo "|---------------|-----------------------------------------------|" echo "|exportdata |Export DB|SCHEMA|TABLE data using EXP or EXPDP |" echo "|---------------|-----------------------------------------------|" echo "|importdata |Import DB|SCHEMA|TABLE data using IMPDP |" echo "|---------------|-----------------------------------------------|" echo "|tableinfo |Show Important Information for a specific TABLE|" echo "|---------------|-----------------------------------------------|" echo "|tablerebuild |REBUILD A TABLE and its related INDEXES |" echo "|---------------|-----------------------------------------------|" echo "|allusersddl |Generate DDL[Creation & Privs] for ALL DB Users|" echo "|---------------|-----------------------------------------------|" echo "|asmdisks |Show ASM Disks info, Mount Points and Labels |" echo " ===============================================================" echo "" echo "The Following Scripts are WITHOUT Aliases:" echo "******************************************" echo " --------------------------------------------------------------------------------------------------- " echo "|dbalarm.sh |Monitors All Databases & Listeners ALERTLOGs for errors and locks along with |" echo "| |monitoring the Tablespaces/ASM Diskgroups/CPU/Filesystems utilization. |" echo "| |you have to Change this template to your real E-mail |" echo "| |Schedule this script in the crontab to run [every 5 minutes]. |" echo "| |For More Details: |" echo "| |http://dba-tips.blogspot.com/2014/02/database-monitoring-script-for-ora-and.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|dbdailychk.sh |Perform Database Health Check and send the report by Email you need to replace |" echo "| | template with your E-MAIL: |" echo "| |Health Checks include but not limited to: |" echo "| |CHECK ALL DBs/Listeners ALERTLOGS FOR ERRORS |" echo "| |CHECK Filesystem/CPU/Tablespaces utilization |" echo "| |CHECK Unusable Indexes/Invalid Objects/Corrupted Blocks/Failed Jobs |" echo "| |/Failed Logins/Active Incidents/DB Growth/Resource Limits/Restore Points/Advisors/ |" echo "| |Monitored Indexes/Redolog Switches/Modified Parameters/RMAN Backups/RAC Services/ |" echo "| |New Created Objects/Long Running Jobs/Audit Records |" echo "| |For More Details: |" echo "| |http://dba-tips.blogspot.com/2015/05/oracle-database-health-check-script.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|SHUTDOWN_All.sh|SHUTDOWN ALL running Databases and Listeners on The server |" echo "| |I didn't alias it, to avoid having it run accidentally!. |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|COLD_BACKUP.sh |-Take a COLD BACKUP for any database. |" echo "| |-Create a Restore Script to help you restore that Cold Backup later. |" echo "| |For More Details: |" echo "| |http://dba-tips.blogspot.com/2014/02/cold-backup-script.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|schedule_rman_f|Can be scheduled in the crontab to take an RMAN Full backup for a specific database|" echo "|ull_bkp.sh |You MUST modify the variables/channels/maintenance section to match your env. |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|schedule_rman_i|Can be scheduled in the crontab to take an RMAN Image/Copy for a specific database |" echo "|mage_copy_bkp.s|You MUST modify the variables/channels/maintenance sections to match your env. |" echo "|h |Why to consider an RMAN image backups in your backup strategy, check this link: |" echo "| |http://dba-tips.blogspot.com/2011/11/switch-database-to-rman-copy-backup-and.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|configuration_ |Collect configuration baseline data for OS and all running DATABASES. |" echo "|baseline.sh |help you to track/rollback the changes in your environment. |" echo "| |It's recommended to execute it once a month. For More Details: |" echo "| |http://dba-tips.blogspot.com/2016/12/configuration-baseline-script-for-linux.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|delete_applied_|Deletes the applied archivelogs on the standby DB |" echo "|archives_on_sta|For More Details: |" echo "|ndby.sh |http://dba-tips.blogspot.com/2017/01/script-to-delete-applied-archivelogs-on.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|backup_ctrl_spf|Backup Controlfile as a (Trace/RMAN BKP), Backup SPFILE and Generate AWR [optional]|" echo "|_AWR.sh |This script can be scheduled in the crontab to run once a day. Script options/ |" echo "| |variables must be modified to match your environment. |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|kill_long_runni|Kill all queries running longer than 2.5 Hours by specific modules. |" echo "|ng_queries.sh |Time and Module Names Must be adjusted to match the killing criteria you want to |" echo "| |setup. This script can be scheduled in the crontab. |" echo "| |For More Details: |" echo "| |http://dba-tips.blogspot.com/2018/04/automatic-kill-of-long-running-sessions.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|report_long_run|Report long running queries that run for more than specific time. |" echo "|ing_queries.sh |For More Details: |" echo "| |http://dba-tips.blogspot.com/2018/04/report-long-running-queries-long-active.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|check_standby_l|If you have a standby DB then you can use this script on Primary DB site to report |" echo "|ag.sh |the LAG between primary and standby DB. |" echo "| |The variables section at the top of the script must be populated by you to match |" echo "| |your environment. It can be scheduled in the crontab to run every 5 minutes. |" echo "| |For more details on how to use this script: |" echo "| |http://dba-tips.blogspot.ae/2017/11/shell-script-to-check-lag-sync-status.html |" echo "|---------------|-----------------------------------------------------------------------------------|" echo "|goldengate_lag_|Monitors GoldenGate LAG and notify the user by E-mail |" echo "|mon.sh |For more details on functionality and How to Use: |" echo "| |http://dba-tips.blogspot.ae/2018/05/linux-shell-script-to-monitor-and.html |" echo " --------------------------------------------------------------------------------------------------- " echo "" echo "***************************************" echo "Thanks for using DBA BUNDLE V6.3," echo "Mahmmoud ADEL | Oracle DBA" echo -e "\033[32;5mdba-tips.blogspot.com\033[0m" echo "***************************************" ;; esac echo "" else echo "The Bundle directory ${BUNDLE_LOC} is not exist!" # echo -e "\033[32;5mThe DBA_BUNDLE Tar File MUST be extracted under the Oracle Owner Home Directory: ${USR_ORA_HOME}\033[0m" echo "" fi # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # Do not live under a rock :-) Every month a new version of DBA_BUNDLE get released, download it by visiting: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # REPORT BUGS to: mahmmoudadel@hotmail.com DBA_BUNDLE6/user_ddl.sh 0000740 0152073 0152061 00000030033 13775601565 014616 0 ustar oracle oinstall # #################################################################################################### # This script shows the creation statement of a DB user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-09-11 # # # # # # Modified: 31-12-13 Customized the script to run on various environments. # 15-09-14 Add Search Feature. # 20-09-20 Using dbms_metadata.get_ddl for 12c+ versions. # # #################################################################################################### # ############ # Description: # ############ echo echo "========================================================" echo "This script generates the CREATION STATEMENT for a USER." echo "========================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ################### # Checking DB Version: # ################### DB_VER_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/monitor_audit_records.sh 0000740 0152073 0152061 00000051217 13737542130 017410 0 ustar oracle oinstall # ##################################################################################################################################################### # Monitor audit records [Failed login attempts & MAJOR AUDIT RECRODS] on audit trail table VER="[1.0]" SCRIPT_NAME="monitor_audit_records" # ##################################################################################################################################################### # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 28-09-20 # # # # # # Modified: 04-10-20 Added the awarness of machine TIMEZONE to avoid wrong data fetch when timezone is UTC. # # # # # ###################################################################################################################################################### EMAIL="youremail@yourcompany.com" # ######################### # THRESHOLDS: # ######################### # Modify the THRESHOLDS to the value you prefer: HTMLENABLE=Y # Enable HTML Email Format [Default Enabled]. MINUTES=10 # Check audit records in the last N number of minutes [Default 5 minutes]. RECORDSNUM=1 # Send an Email if the number of audit records exceed the threshold [Default 1 record]. REPORT_FAILED_LOGINS=Y # Enable the reporting of failled logins [Default Enabled]. REPORT_AUDIT_RECORDS=Y # Enable the reporting of audit records [Default Enabled]. EXCLUDE_DBUSERS="'dba_bundleexp7'" # Exclude DB user from reporting their activities [In lowercase]. e.g. EXCLUDE_DBUSERS="'sys','scott'" EXCLUDE_OSUSERS="'user1'" # Exclude OS user from reporting their activities [In lowercase]. e.g. EXCLUDE_OSUSERS="'oracle','grid'" EXCLUDE_ACTIONS="'SELECT','SET ROLE','LOGON','LOGOFF','LOGOFF BY CLEANUP','EXPLAIN','PL/SQL EXECUTE','SYSTEM AUDIT'" # Exclude AUDIT EVENTS from reporting # e.g. To exclude all previous Audit Events along with DMLs (inserts, updates, deletes): # EXCLUDE_ACTIONS="'SELECT','SET ROLE','LOGON','LOGOFF','LOGOFF BY CLEANUP','EXPLAIN','PL/SQL EXECUTE','SYSTEM AUDIT','SESSION REC'" # To explore all the current available events in your DB run: # SQL> select distinct action_name from dba_audit_trail; SQLLINESIZE=200 # The LINE SIZE for SQLPLUS outputs. OSLINESIZE=300 # The LINE SIZE for OS Commands outputs. [Default is 167] SENDER="AUDITRECORDS" # Change the Email sender name. e.g. EXCLUDE_DBUSERS="AUDITRECORDS" # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will not run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM and APX instances: EXL_DB="\-MGMTDB|ASM|APX" # ####################################### # Verify Variables: # ####################################### export HTMLENABLE export MINUTES export RECORDSNUM export REPORT_FAILED_LOGINS export REPORT_AUDIT_RECORDS export EXCLUDE_DBUSERS export EXCLUDE_OSUSERS export EXCLUDE_ACTIONS export SQLLINESIZE export OSLINESIZE export EXL_DB case ${EXCLUDE_DBUSERS} in "") export HASHDBUSERNAME="--";; *) export HASHDBUSERNAME="";; esac case ${EXCLUDE_OSUSERS} in "") export HASHOSUSERNAME="--";; *) export HASHOSUSERNAME="";; esac case ${EXCLUDE_ACTIONS} in "") export HASHACTIONNAME="--";; *) export HASHACTIONNAME="";; esac export SRV_NAME="`uname -n`" # Check if MAIL_LIST parameter is not set notify the user and exit: case ${EMAIL} in "youremail@yourcompany.com") echo echo "******************************************************************" echo "Buddy! You forgot to edit line# 50 in ${SCRIPT_NAME}.sh script." echo "Please replace youremail@yourcompany.com with your E-mail address." echo "******************************************************************" echo echo "Script Terminated !" echo exit;; esac # Check if there is another session of the script is running: [Avoid performance impact] RUNCOUNTT=`ps -ef|grep -v grep|grep -v vi|grep ${SCRIPT_NAME}|wc -l` if [ ${RUNCOUNTT} -gt 2 ] then echo -e "\033[32;5m${SCRIPT_NAME}.sh script is currently running by another session.\033[0m" echo "" echo "Please make sure the following sessions are completed before running dbalarm script: [ps -ef|grep -v grep|grep -v vi|grep ${SCRIPT_NAME}]" ps -ef|grep -v grep|grep -v vi|grep ${SCRIPT_NAME}.sh echo "Script Terminated !" echo exit fi export MAIL_LIST="${EMAIL}" #export MAIL_LIST="-r ${SRV_NAME} ${EMAIL}" echo echo "[${SCRIPT_NAME} Script Started ...]" echo # Verify log location: LOGDIR=/tmp if [ ! -w "${LOGDIR}" ]; then LOGDIR=~ fi # ########################### # Check the Linux OS version: # ########################### export PATH=${PATH}:/usr/local/bin FILE_NAME=/etc/redhat-release export FILE_NAME if [ -f ${FILE_NAME} ] then LNXVER=`cat /etc/redhat-release | grep -o '[0-9]'|head -1` export LNXVER fi # ########################## # MACHINE TIMEZONE: # ########################## # When machine is not in UTC: export SYSDATE_PATTERN="new_time(sysdate - ${MINUTES}/1440,'gmt','edt')" # When machine is in UTC: FILE_NAME=/etc/localtime export FILE_NAME if [ -f ${FILE_NAME} ] then UTC_EXIST=`ls -l /etc/localtime|grep 'UTC\|GMT'|wc -l` if [ ${UTC_EXIST} -gt 0 ] then export SYSDATE_PATTERN="sysdate - ${MINUTES}/1440" fi fi # Run the script on each DB: for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID # ################### # Getting ORACLE_HOME: # ################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi printf "`echo "Reporting AUDIT records on Database ["` `echo -e "\033[33;5m${ORACLE_SID}\033[0m"` `echo "]"`\n" echo "" # ################### # WARNINGS SECTION: # ################### # Display a WARNING message if AUDITING is not enabled: AUDCOUNTRAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; prompt SELECT COUNT(*) FROM V\$PARAMETER WHERE NAME='audit_trail' AND VALUE='NONE'; exit; EOF ) AUDCOUNT=`echo ${AUDCOUNTRAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` if [ ${AUDCOUNT} -ge 1 ] then echo "" printf "`echo -e "\033[33;5mINFO!\033[0m"` `echo " AUDITING IS NOT ENABLED ON DATABASE [${ORACLE_SID}] ..."`\n" echo "" fi # Display a WARNING message if NTIMESTAMP# column in sys.aud$ is not indexed: INDEXCOUNTRAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; prompt select count(*) from dba_ind_columns where table_owner='SYS' and table_name='AUD\$' and column_name='NTIMESTAMP#'; exit; EOF ) INDEXCOUNT=`echo ${INDEXCOUNTRAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` if [ ${INDEXCOUNT} -le 0 ] then echo "" printf "`echo -e "\033[33;5mWARNING:\033[0m"` `echo " NTIMESTAMP# Column in sys.aud$ table is"` `echo -e "\033[33;5mNOT INDEXED\033[0m"`\n" echo "" echo "This script may cause a performance degradation when it run!" echo "In order to avoid execution slowness, create an index on aud$ (NTIMESTAMP#) column by executing this CREATE INDEX statement:" echo "" echo "CREATE INDEX sys.idx_ntimestamp# ON sys.aud\$(ntimestamp#) ONLINE;" echo "EXEC DBMS_STATS.GATHER_TABLE_STATS (ownname => 'SYS', tabname => 'AUD\$', cascade => TRUE, estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE);" echo "" echo "" export NOINDEXWARNING="PROMPT" export NOINDEXWARNING1="PROMPT RECOMMENDATION: sys.aud$ table should be INDEXED to speed up this script using these statements:" export NOINDEXWARNING2="PROMPT CREATE INDEX sys.idx_ntimestamp# ON sys.aud\$(ntimestamp#) ONLINE;;" export NOINDEXWARNING3="PROMPT EXEC DBMS_STATS.GATHER_TABLE_STATS (ownname => 'SYS', tabname => 'AUD$', cascade => TRUE, estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE);;" sleep 2 fi # ################### # Check failed logins: # ################### case ${REPORT_FAILED_LOGINS} in y|Y|yes|YES|Yes|ON|On|on) FAILEDLOGINCOUNTRAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; prompt select count(*) from aud\$ where ntimestamp# >= ${SYSDATE_PATTERN} and action# between 100 and 102 and returncode = 1017 ${HASHDBUSERNAME} and lower (USERID) not in (${EXCLUDE_DBUSERS}) ${HASHOSUSERNAME} and lower (SPARE1) not in (${EXCLUDE_OSUSERS}) / /* select count(*) from DBA_AUDIT_SESSION where returncode = 1017 and timestamp >= ${SYSDATE_PATTERN} ${HASHDBUSERNAME} and lower (USERNAME) not in (${EXCLUDE_DBUSERS}) ${HASHOSUSERNAME} and lower (OS_USERNAME) not in (${EXCLUDE_OSUSERS}) / */ exit; EOF ) FAILEDLOGINCOUNT=`echo ${FAILEDLOGINCOUNTRAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` if [ ${FAILEDLOGINCOUNT} -gt 0 ] then echo "FAILED LOGIN ATTEMPTS DETECTED. SENDING AN EMAIL ALERT ..." FAILEDLOGINLOG=/tmp/failed_login_report_${ORACLE_SID}.log touch ${FAILEDLOGINLOG} # HTML Preparation: # ################# case ${HTMLENABLE} in y|Y|yes|YES|Yes|ON|On|on) if [ -x /usr/sbin/sendmail ] then export SENDMAIL="/usr/sbin/sendmail -t" export MAILEXEC="echo #" export HASHHTML="" export HASHHTMLOS="" export ENDHASHHTMLOS="" export HASHNONHTML="--" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${FAILEDLOGINLOG} ) export SENDMAILARGS else export SENDMAIL="echo #" export MAILEXEC="mail -s" export HASHHTML="--" export HASHHTMLOS="echo #" export ENDHASHHTMLOS="" export HASHNONHTML="" fi ;; *) export SENDMAIL="echo #" export HASHHTML="--" export HASHHTMLOS="echo #" export ENDHASHHTMLOS="" export HASHNONHTML="" export MAILEXEC="mail -s" ;; esac FAILEDLOGINOUTPUT=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 termout off echo off feedback off linesize ${SQLLINESIZE} EXEC DBMS_SESSION.set_identifier('${SCRIPT_NAME}'); -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF SPOOL ${FAILEDLOGINLOG} prompt ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FAILED LOGIN ATTEMPTS: [Last ${MINUTES} Minutes] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt **************************************** ${HASHNONHTML} Prompt FAILED LOGIN ATTEMPTS [Last ${MINUTES} Minutes] ${HASHNONHTML} prompt **************************************** set feedback off linesize ${SQLLINESIZE} pages 1000 timing on col TERMINAL FOR A30 col ACTION_NAME FOR A20 col TIMESTAMP FOR A21 col OS_USERNAME FOR A20 col DB_USERNAME FOR A20 col DATE FOR A22 col USERHOST FOR A30 select to_char (ntimestamp#,'DD-MON-YYYY HH24:MI:SS') TIMESTAMP,USERID DB_USERNAME, spare1 OS_USERNAME, USERHOST, TERMINAL from aud\$ Where ntimestamp# >= ${SYSDATE_PATTERN} and action# between 100 and 102 and returncode = 1017 ${HASHDBUSERNAME} and lower (USERID) not in (${EXCLUDE_DBUSERS}) ${HASHOSUSERNAME} and lower (spare1) not in (${EXCLUDE_OSUSERS}) order by ntimestamp# / PROMPT ${NOINDEXWARNING} ${NOINDEXWARNING1} ${NOINDEXWARNING2} ${NOINDEXWARNING3} /* select to_char (EXTENDED_TIMESTAMP,'DD-MON-YYYY HH24:MI:SS') TIMESTAMP,OS_USERNAME,DB_USERNAME,TERMINAL,USERHOST,ACTION_NAME from DBA_AUDIT_SESSION where returncode = 1017 and timestamp >= ${SYSDATE_PATTERN} ${HASHDBUSERNAME} and lower (USERNAME) not in (${EXCLUDE_DBUSERS}) ${HASHOSUSERNAME} and lower (OS_USERNAME) not in (${EXCLUDE_OSUSERS}) order by EXTENDED_TIMESTAMP / */ SPOOL OFF exit; EOF ) export MSGSUBJECT="ALERT: FAILED LOGIN ATTEMPT DETECTED ON [${ORACLE_SID}] ON [${SRV_NAME}]" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "From: ${SENDER};" echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${FAILEDLOGINLOG} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${FAILEDLOGINLOG} echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} fi echo "FAILED LOGIN CHECK COMPLETED." echo ;; esac # #################### # Check AUDIT RECORDS: # #################### case ${REPORT_AUDIT_RECORDS} in y|Y|yes|YES|Yes|ON|On|on) AUDITRECORDSCOUNTRAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; prompt -- Avoided using DBA_AUDIT_TRAIL view to not get the index on AUD\$(NTIMESTAMP#) ignored in the execution plan! select count(*) from aud\$ a, audit_actions act where a.action# = act.action (+) and a.ntimestamp# >= ${SYSDATE_PATTERN} ${HASHDBUSERNAME} and lower (a.USERID) not in (${EXCLUDE_DBUSERS}) ${HASHOSUSERNAME} and lower (a.spare1) not in (${EXCLUDE_OSUSERS}) ${HASHACTIONNAME} and upper (act.NAME) not in (${EXCLUDE_ACTIONS}) / /* select count(*) from DBA_AUDIT_TRAIL where timestamp >= ${SYSDATE_PATTERN} ${HASHDBUSERNAME} and lower (USERNAME) not in (${EXCLUDE_DBUSERS}) ${HASHOSUSERNAME} and lower (OS_USERNAME) not in (${EXCLUDE_OSUSERS}) ${HASHACTIONNAME} and upper (ACTION_NAME) not in (${EXCLUDE_ACTIONS}) / */ exit; EOF ) AUDITRECORDSCOUNT=`echo ${AUDITRECORDSCOUNTRAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` if [ ${AUDITRECORDSCOUNT} -gt 0 ] then echo "AUDIT RECORDS DETECTED. SENDING AN EMAIL ALERT ..." AUDITRECORDSLOG=/tmp/audit_records_report_${ORACLE_SID}.log touch ${AUDITRECORDSLOG} # HTML Preparation: # ################# case ${HTMLENABLE} in y|Y|yes|YES|Yes|ON|On|on) if [ -x /usr/sbin/sendmail ] then export SENDMAIL="/usr/sbin/sendmail -t" export MAILEXEC="echo #" export HASHHTML="" export HASHHTMLOS="" export ENDHASHHTMLOS="" export HASHNONHTML="--" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${AUDITRECORDSLOG} ) export SENDMAILARGS else export SENDMAIL="echo #" export MAILEXEC="mail -s" export HASHHTML="--" export HASHHTMLOS="echo #" export ENDHASHHTMLOS="" export HASHNONHTML="" fi ;; *) export SENDMAIL="echo #" export HASHHTML="--" export HASHHTMLOS="echo #" export ENDHASHHTMLOS="" export HASHNONHTML="" export MAILEXEC="mail -s" ;; esac AUDITRECORDSOUTPUT=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 termout off echo off feedback off linesize ${SQLLINESIZE} col name for A40 EXEC DBMS_SESSION.set_identifier('${SCRIPT_NAME}'); -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='1' bordercolor='#E67E22'" ENTMAP OFF SPOOL ${AUDITRECORDSLOG} prompt ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Audit Records [Last ${MINUTES} Minutes] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ********************************** ${HASHNONHTML} Prompt Audit Records [Last ${MINUTES} Minutes] ${HASHNONHTML} prompt ********************************** set feedback off linesize ${SQLLINESIZE} pages 1000 timing on col OS_USERNAME FOR A15 col DB_USERNAME FOR A15 col DATE FOR A22 col OWNER FOR A15 col OBJ_NAME FOR A25 col USERHOST FOR A21 col ACTION_NAME FOR A20 col "ACTION_OWNER.OBJECT" FOR A80 col SQL_TEXT FOR A100 -- Avoided using DBA_AUDIT_TRAIL view to not get the index on AUD\$(NTIMESTAMP#) ignored in the execution plan! select to_char(a.NTIMESTAMP#,'DD-Mon-YYYY HH24:MI:SS')"DATE",a.spare1 OS_USERNAME, a.USERID DB_USERNAME, a.USERHOST, act.NAME||' '||a.OBJ\$CREATOR||' . '||a.OBJ\$NAME "ACTION_OWNER.OBJECT", a.RETURNCODE, a.SQLTEXT from aud\$ a, audit_actions act where a.action# = act.action (+) and a.ntimestamp# >= ${SYSDATE_PATTERN} ${HASHDBUSERNAME} and lower (a.USERID) not in (${EXCLUDE_DBUSERS}) ${HASHOSUSERNAME} and lower (a.spare1) not in (${EXCLUDE_OSUSERS}) ${HASHACTIONNAME} and upper (act.NAME) not in (${EXCLUDE_ACTIONS}) order by a.ntimestamp# / PROMPT ${NOINDEXWARNING} ${NOINDEXWARNING1} ${NOINDEXWARNING2} ${NOINDEXWARNING3} SPOOL OFF exit; EOF ) export MSGSUBJECT="ALERT: AUDIT RECORDS DETECTED ON [${ORACLE_SID}] ON [${SRV_NAME}]" echo ${MSGSUBJECT} SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${AUDITRECORDSLOG} ) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${AUDITRECORDSLOG} echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} fi echo "AUDIT RECORDS CHECK COMPLETED." echo ;; esac done # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/sql_tune.sh 0000740 0152073 0152061 00000112005 14121654514 014633 0 ustar oracle oinstall # ######################################################################################################################################## # Retrieve the SQLTEXT + BIND VARIABLES + EXEC PLAN + PLAN HISTORY + BASELINE + FIX PLAN + TUNING ADVISOR VER="[3.5]" # # # # # Authors: Mahmmoud ADEL # # # # # # # Farrukh Salman # # # #### # Created: 24-12-11 # # # # # # Modified: 31-12-13 Customized the script to run on various environments. # 06-05-14 Getting the Bind Variable info for the SQLID # 05-11-15 Fix Divided by Zero error # 16-06-16 Added SQL Tuning Option # 26-02-17 Added Execution History quoted from sqlhistory.sql written by: Tim Gorman (Evergreen Database Technologies, Inc.) # 14-11-17 Added a check for available tuning tasks # 26-07-18 Enhanced the display of Execution Plan # 11-09-18 Display SQL Advisor recommendation for the statement if it was already been vetted by SQL Advisor. # 28-08-19 Added Post Tuning note for hard parsing enforcement command. # 10-06-20 Adjust page formatting. # 02-07-20 Added Execution Plan History. # 05-10-20 Added SQL PLAN BASELINE Details. # 06-10-20 Added the feature of fixing an EXECUTION PLAN by creating a new BASELINE. # 06-10-20 Added the feature of fixing an EXECUTION PLAN from an EXIST BASELINE [if found]. # 11-10-20 Added a hint to help the user display the complete execution plan for a plan inside the BASELINE. # 13-02-21 Search the Execution Plans in AWR if the SQLID is not loaded in Cursor Cache. # 15-02-21 Show Drop Baseline SQL command for the user. # 19-09-21 Add the option of manually adding a plan to the SQL PLAN BASELINE using plan HASH VALUE. # 19-09-21 Control the SQLID displayed statistics history in days using HIST_DAYS variable. # ######################################################################################################################################## # ########### # Description: # ########### echo echo "=====================================================================================================" echo "This script display SQLTEXT, BIND VARIABLES, EXEC PLAN, BASELINE, FIX PLAN, SQL TUNING of a SQLID ..." echo "=====================================================================================================" echo ORACLE_OWNER_VFY="N" SKIPDBS="ASM\|MGMTDB|APX" HIST_DAYS=10 # Define how many DAYs back the script will dig for SQLID statistics. # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|grep -v ${SKIPDBS}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|grep -v ${SKIPDBS}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -f /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## case ${ORACLE_OWNER_VFY} in "Y") CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi;; esac # ######################################## # SQLPLUS: Check SQL FULLTEXT & EXEC PLAN: # ######################################## # Variables echo echo "Enter the SQL_ID:" echo "================" while read SQLID do VAL1=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off SELECT COUNT(*) FROM V\$SQL WHERE SQL_ID='${SQLID}'; EOF ) VAL2=`echo ${VAL1}| awk '{print $NF}'` if [ ${VAL2} -gt 0 ] then ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off set linesize 156 pages 50000 long 2000000000 col SQL_FULLTEXT for a140 PROMPT PROMPT ************************* PROMPT Statement Info: [Per Execution | in Seconds] PROMPT ************************* SET LONG 999999999 PAGESIZE 10000 LINESIZE 200 col "ELAPSED|CPU TIME" for a16 col "PLSQL|JAVA TIME" for a24 col "APP|USR_IO|CLS WAIT" for a19 col "BUF_GET|DISK_R|DIRECT_W" for a23 col P_MEM_MB for 99999999 col "ROWS" for 999999999 col MODULE for a15 col FIRST_LOAD_TIME for a19 col LAST_LOAD_TIME for a19 col sql_plan_baseline for a30 col plan_hash_value for 999999999999999 col signature for 99999999999999999999 col SQL_PROFILE for a35 VARIABLE A REFCURSOR; DECLARE l_cursor SYS_REFCURSOR; BEGIN open :A for select executions EXEC,round(ELAPSED_TIME /1000000/(case when executions=0 then 1 else executions end),2) ||' | '|| round(CPU_TIME /1000000/(case when executions=0 then 1 else executions end),2) "ELAPSED|CPU TIME", --round(d.ELAPSED_TIME /1000000/(case when executions=0 then 1 else executions end),2) ELAPSED_TIME, round(APPLICATION_WAIT_TIME /1000000/(case when executions=0 then 1 else executions end),2) ||' | '|| round(USER_IO_WAIT_TIME /1000000/(case when executions=0 then 1 else executions end),2) ||' | '|| round(CLUSTER_WAIT_TIME /1000000/(case when executions=0 then 1 else executions end),2) "APP|USR_IO|CLS WAIT", --round(PLSQL_EXEC_TIME /1000000/(case when executions=0 then 1 else executions end),2)||' | '||round(JAVA_EXEC_TIME/1000000/(case when executions=0 then 1 else executions end),2) "PLSQL|JAVA TIME", round(ROWS_PROCESSED /(case when executions=0 then 1 else executions end),1)"ROWS", round(BUFFER_GETS /(case when executions=0 then 1 else executions end),2) ||' | '|| round(DISK_READS /(case when executions=0 then 1 else executions end),2) ||' | '|| round(DIRECT_WRITES /(case when executions=0 then 1 else executions end),2) "BUF_GET|DISK_R|DIRECT_W", --round(PERSISTENT_MEM/1024/1024,2) "P_MEM_MB", substr(MODULE,1,15)"MODULE", FIRST_LOAD_TIME, LAST_LOAD_TIME --,SQL_PLAN_BASELINE, SQL_PROFILE from v\$sql where SQL_ID='${SQLID}'; END; / PRINT A; / PROMPT PROMPT ************************* PROMPT BIND VARIABLES + SQL TEXT: PROMPT ************************* set heading off wrap off SET LONG 999999999 PAGESIZE 10000 LINESIZE 200 select 'VARIABLE '||trim (leading ':' from name)||' '||case when datatype_string= 'DATE' then 'VARCHAR2(60)' else datatype_string end||';' from v\$sql_bind_capture where SQL_ID='${SQLID}' and CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}'); select 'EXECUTE '||name||' := '||''''||value_string||''''||';' from v\$sql_bind_capture where SQL_ID='${SQLID}' and CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}'); select sql_fulltext from v\$sql where sql_id='${SQLID}' and CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql where SQL_ID='${SQLID}'); set heading on PROMPT set heading off select 'Notes: (11g Onwards)' from dual; PROMPT ------- select decode(IS_BIND_SENSITIVE,'Y','- The Bind Variables for this statement are Being CHANGED.','N','- The Bind Variables for this statement have NEVER CHANGED.'), decode(IS_BIND_AWARE,'Y','- Adaptive Cursor Sharing CHANGED the initial execution plan for that SQL_ID at least one time.','N',''), ' Child Number: '||CHILD_NUMBER from v\$sql where sql_id='${SQLID}' and CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql where SQL_ID='${SQLID}'); set heading on /* PROMPT PROMPT PROMPT ********************* PROMPT BIND VARIABLE VALUES: PROMPT ********************* col BIND_VARIABLE for a20 col VALUE for a100 col DATATYPE for a20 select name BIND_VARIABLE,value_string VALUE,datatype_string DATATYPE from v\$sql_bind_capture where SQL_ID='${SQLID}' and CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}'); PROMPT SEARCH STATSPACK TABLES: [May take very long time] PROMPT *********************** select SQL_TEXT from STATS\$SQLTEXT where sql_id='${SQLID}'; select executions from STATS\$SQL_SUMMARY where sql_id='${SQLID}'; */ PROMPT PROMPT PROMPT ********************* PROMPT EXECUTION PLAN: PROMPT ********************* col PLAN_TABLE_OUTPUT for a156 --SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR(('${SQLID}'))); select plan_table_output from table(dbms_xplan.display_cursor('${SQLID}',null,'all')); PROMPT PROMPT ****************************** PROMPT Execution Plan History Summary: [Change of PLAN_HASH_VALUE means a new Execution Plan] PROMPT ****************************** select distinct to_char(TIMESTAMP,'DD-MON-YY HH24:MI:SS') TIMESTAMP,SQL_ID,PLAN_HASH_VALUE from DBA_HIST_SQL_PLAN where sql_id='${SQLID}' group by TIMESTAMP,SQL_ID,PLAN_HASH_VALUE order by TIMESTAMP; PROMPT PROMPT PROMPT *********************** PROMPT EXECUTION PLAN History: Written By: Tim Gorman (Evergreen Database Technologies, Inc.) PROMPT *********************** /********************************************************************** * File: sqlhistory.sql * Type: SQL*Plus script * Author: Tim Gorman (Evergreen Database Technologies, Inc.) * Date: 29sep08 * * Description: * SQL*Plus script to query the "history" of a specified SQL * statement, using its "SQL ID" across all database instances * in a database, using the AWR repository. This report is useful * for obtaining an hourly perspective on SQL statements seen in * more aggregated reports. * * Modifications: * TGorman 29sep08 adapted from the earlier STATSPACK-based * "sphistory.sql" script *********************************************************************/ set echo off set feedback off timing off verify off linesize 200 pages 50000 recsep off echo off set serveroutput on size 1000000 col phv heading "Plan|Hash Value" col snap_time format a12 truncate heading "Snapshot|Time" col execs format 999,999,990 heading "Execs" col lio_per_exec format 999,999,999,990.00 heading "Avg Logical IO|Per Exec" col pio_per_exec format 999,999,999,990.00 heading "Avg Physical IO|Per Exec" col cpu_per_exec format 999,999,999,990.00 heading "Avg|CPU (secs)|Per Exec" col ela_per_exec format 999,999,999,990.00 heading "Avg|Elapsed (secs)|Per Exec" col sql_text format a64 heading "Text of SQL statement" clear breaks computes ttitle off btitle off --variable v_nbr_days number declare cursor get_phv(in_sql_id in varchar2, in_days in integer) is select ss.plan_hash_value, min(s.begin_interval_time) min_time, max(s.begin_interval_time) max_time, min(s.snap_id) min_snap, max(s.snap_id) max_snap, sum(ss.executions_delta) sum_execs, sum(ss.disk_reads_delta) sum_disk_reads, sum(ss.buffer_gets_delta) sum_buffer_gets, sum(ss.cpu_time_delta)/1000000 sum_cpu_time, sum(ss.elapsed_time_delta)/1000000 sum_elapsed_time from dba_hist_sqlstat ss, dba_hist_snapshot s where ss.dbid = s.dbid and ss.instance_number = s.instance_number and ss.snap_id = s.snap_id and ss.sql_id = in_sql_id /* and ss.executions_delta > 0 */ and s.begin_interval_time >= sysdate-in_days group by ss.plan_hash_value order by sum_elapsed_time desc; -- cursor get_xplan(in_sql_id in varchar2, in_phv in number) is select plan_table_output from table(dbms_xplan.display_awr(in_sql_id, in_phv, null, 'ALL -ALIAS')); -- v_prev_plan_hash_value number := -1; v_text_lines number := 0; v_errcontext varchar2(100); v_errmsg varchar2(100); v_display_sql_text boolean; -- begin /* v_errcontext := 'query NBR_DAYS from DUAL'; select decode('100','',10,to_number(nvl('100','10'))) into :v_nbr_days from dual; */ v_errcontext := 'open/fetch get_phv'; --for phv in get_phv('${SQLID}', :v_nbr_days) loop for phv in get_phv('${SQLID}', ${HIST_DAYS}) loop -- if get_phv%rowcount = 1 then -- dbms_output.put_line('+'|| rpad('-',12,'-')|| rpad('-',10,'-')|| rpad('-',10,'-')|| rpad('-',12,'-')|| rpad('-',15,'-')|| rpad('-',15,'-')|| rpad('-',12,'-')|| rpad('-',12,'-')||'+'); dbms_output.put_line('|'|| rpad('Plan HV',12,' ')|| rpad('Min Snap',10,' ')|| rpad('Max Snap',10,' ')|| rpad('Execs',12,' ')|| rpad('LIO',15,' ')|| rpad('PIO',15,' ')|| rpad('CPU',12,' ')|| rpad('Elapsed',12,' ')||'|'); dbms_output.put_line('+'|| rpad('-',12,'-')|| rpad('-',10,'-')|| rpad('-',10,'-')|| rpad('-',12,'-')|| rpad('-',15,'-')|| rpad('-',15,'-')|| rpad('-',12,'-')|| rpad('-',12,'-')||'+'); -- end if; -- dbms_output.put_line('|'|| rpad(trim(to_char(phv.plan_hash_value)),12,' ')|| rpad(trim(to_char(phv.min_snap)),10,' ')|| rpad(trim(to_char(phv.max_snap)),10,' ')|| rpad(trim(to_char(phv.sum_execs,'999,999,990')),12,' ')|| rpad(trim(to_char(phv.sum_buffer_gets,'999,999,999,990')),15,' ')|| rpad(trim(to_char(phv.sum_disk_reads,'999,999,999,990')),15,' ')|| rpad(trim(to_char(phv.sum_cpu_time,'999,990.00')),12,' ')|| rpad(trim(to_char(phv.sum_elapsed_time,'999,990.00')),12,' ')||'|'); -- v_errcontext := 'fetch/close get_phv'; -- end loop; dbms_output.put_line('+'|| rpad('-',12,'-')|| rpad('-',10,'-')|| rpad('-',10,'-')|| rpad('-',12,'-')|| rpad('-',15,'-')|| rpad('-',15,'-')|| rpad('-',12,'-')|| rpad('-',12,'-')||'+'); -- v_errcontext := 'open/fetch get_phv'; --for phv in get_phv('${SQLID}', :v_nbr_days) loop for phv in get_phv('${SQLID}', ${HIST_DAYS}) loop -- if v_prev_plan_hash_value <> phv.plan_hash_value then -- v_prev_plan_hash_value := phv.plan_hash_value; v_display_sql_text := FALSE; -- v_text_lines := 0; v_errcontext := 'open/fetch get_xplan'; for s in get_xplan('${SQLID}', phv.plan_hash_value) loop -- if v_text_lines = 0 then dbms_output.put_line('.'); dbms_output.put_line('========== PHV = ' || phv.plan_hash_value || '=========='); dbms_output.put_line('First seen from "'|| to_char(phv.min_time,'MM/DD/YY HH24:MI:SS') || '" (snap #'||phv.min_snap||')'); dbms_output.put_line('Last seen from "'|| to_char(phv.max_time,'MM/DD/YY HH24:MI:SS') || '" (snap #'||phv.max_snap||')'); dbms_output.put_line('.'); dbms_output.put_line( rpad('Execs',15,' ')|| rpad('LIO',15,' ')|| rpad('PIO',15,' ')|| rpad('CPU',15,' ')|| rpad('Elapsed',15,' ')); dbms_output.put_line( rpad('=====',15,' ')|| rpad('===',15,' ')|| rpad('===',15,' ')|| rpad('===',15,' ')|| rpad('=======',15,' ')); dbms_output.put_line( rpad(trim(to_char(phv.sum_execs,'999,999,999,990')),15,' ')|| rpad(trim(to_char(phv.sum_buffer_gets,'999,999,999,990')),15,' ')|| rpad(trim(to_char(phv.sum_disk_reads,'999,999,999,990')),15,' ')|| rpad(trim(to_char(phv.sum_cpu_time,'999,999,990.00')),15,' ')|| rpad(trim(to_char(phv.sum_elapsed_time,'999,999,990.00')),15,' ')); dbms_output.put_line('.'); end if; -- if v_display_sql_text = FALSE and s.plan_table_output like 'Plan hash value: %' then -- v_display_sql_text := TRUE; -- end if; -- if v_display_sql_text = TRUE then -- dbms_output.put_line(s.plan_table_output); -- end if; -- v_text_lines := v_text_lines + 1; -- end loop; -- end if; -- v_errcontext := 'fetch/close get_phv'; -- end loop; -- exception when others then v_errmsg := sqlerrm; raise_application_error(-20000, v_errcontext || ': ' || v_errmsg); end; / break on report compute sum of execs on report compute avg of lio_per_exec on report compute avg of pio_per_exec on report compute avg of cpu_per_exec on report compute avg of ela_per_exec on report ttitle center 'Summary Execution Statistics Over Time' select to_char(s.begin_interval_time, 'DD-MON HH24:MI') snap_time, ss.executions_delta execs, ss.buffer_gets_delta/decode(ss.executions_delta,0,1,ss.executions_delta) lio_per_exec, ss.disk_reads_delta/decode(ss.executions_delta,0,1,ss.executions_delta) pio_per_exec, (ss.cpu_time_delta/1000000)/decode(ss.executions_delta,0,1,ss.executions_delta) cpu_per_exec, (ss.elapsed_time_delta/1000000)/decode(ss.executions_delta,0,1,ss.executions_delta) ela_per_exec from dba_hist_snapshot s, dba_hist_sqlstat ss where ss.dbid = s.dbid and ss.instance_number = s.instance_number and ss.snap_id = s.snap_id and ss.sql_id = '${SQLID}' /* and ss.executions_delta > 0 */ --and s.begin_interval_time >= sysdate - :v_nbr_days and s.begin_interval_time >= sysdate - ${HIST_DAYS} order by s.snap_id; clear breaks computes set verify on echo on feedback on ttitle off PROMPT PROMPT ****************************** PROMPT Execution Plan History Summary: [Change of PLAN_HASH_VALUE means a new Execution Plan] PROMPT ****************************** select distinct to_char(TIMESTAMP,'DD-MON-YY HH24:MI:SS') TIMESTAMP,SQL_ID,PLAN_HASH_VALUE from DBA_HIST_SQL_PLAN where sql_id='${SQLID}' group by TIMESTAMP,SQL_ID,PLAN_HASH_VALUE order by TIMESTAMP; /* PROMPT PROMPT *********************** PROMPT SQL PLAN BASELINE: [For ${SQLID}] PROMPT *********************** col signature format 99999999999999999999 col sql_handle format a25 col plan_name format a30 col ELAPSED_TIME for 9999999.99 col CPU_TIME for 9999999.99 col BUFFER_GETS for 9999999.99 col enabled format a5 col accepted format a5 col fixed format a5 select distinct d.plan_name, d.sql_handle, d.signature, d.OPTIMIZER_COST COST, d.executions, round(d.ELAPSED_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) ELAPS_TIME, round(d.CPU_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) CPU_TIME, round(d.BUFFER_GETS /1000000/(case when d.executions=0 then 1 else d.executions end),2) BUFFER_GETS, d.enabled, d.accepted, d.fixed, to_char(d.LAST_EXECUTED,'DDMONYY HH24:MI:SS') LAST_EXECUTED from dba_sql_plan_baselines d, v\$sql s where s.sql_id='${SQLID}' and d.signature = s.exact_matching_signature --and s.CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}') ; */ EOF # ###################################### # Checking the Existance of SPM Feature: # ###################################### CHK_SPM_OPTION_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off echo off; SELECT count(*) from v\$option where parameter='SQL Plan Management' and value='TRUE'; exit; EOF ) CHK_SPM_OPTION=`echo ${CHK_SPM_OPTION_RAW} | awk '{print $NF}'` # IF SPM feature is available offer the option of fixing the SQL Plan through creating a BASELINE: if [ ${CHK_SPM_OPTION} -eq 1 ] then BASELINE_PLAN_COUNT_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) from dba_sql_plan_baselines d, v\$sql s where s.sql_id='${SQLID}' and d.signature = s.exact_matching_signature --and s.CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}') ; exit; EOF ) BASELINE_PLAN_COUNT=`echo ${BASELINE_PLAN_COUNT_RAW}| awk '{print $NF}'` # IF no Baseline found, offer to create a new baseline from current available plans from CURSOR CACHE and fix the plan: if [ ${BASELINE_PLAN_COUNT} -le 0 ] then echo "" echo "Do you want to FIX a plan for [${SQLID}] by creating a NEW BASELINE: [Y|N]" echo "=========================================================================" while read INPUT do case ${INPUT} in y|Y|yes|YES|Yes) echo "" echo "Creating a BASELINE for [${SQLID}] containing the current loaded plans from cursor cache" PLANS_COUNT_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; set serveroutput on declare plans_loaded pls_integer ; begin plans_loaded := dbms_spm.load_plans_from_cursor_cache( sql_id => '${SQLID}' ) ; dbms_output.put_line( 'plans loaded: '||plans_loaded ) ; end ; / exit; EOF ) PLANS_COUNT=`echo ${PLANS_COUNT_RAW}| awk '{print $NF}'` if [ ${PLANS_COUNT} -gt 0 ] then echo "" echo "Loaded Plans: ${PLANS_COUNT}" echo "" ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 1000 lines 169 pages 50000 long 2000000000 col signature format 99999999999999999999 col sql_handle format a25 col plan_name format a30 col ELAPSED_TIME for 9999999.99 col CPU_TIME for 9999999.99 col BUFFER_GETS for 9999999.99 col enabled format a5 col accepted format a5 col fixed format a5 PROMPT PROMPT CURRENT PLANS INSIDE THE NEW BASELINE for [${SQLID}]: PROMPT select distinct d.plan_name, d.sql_handle, d.signature, d.OPTIMIZER_COST COST, d.executions, round(d.ELAPSED_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) ELAPSED_TIME, round(d.CPU_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) CPU_TIME, round(d.BUFFER_GETS /1000000/(case when d.executions=0 then 1 else d.executions end),2) BUFFER_GETS, d.enabled, d.accepted, d.fixed from dba_sql_plan_baselines d, v\$sql s where sql_id='${SQLID}' and d.signature = s.exact_matching_signature --and s.CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}') ; EOF read -p "Enter the PLAN_NAME for the plan you want to fix [From the above output]: " PLAN_NAME read -p "Enter the SQL_HANDLE for the plan you want to fix [From the above output]: " SQL_HANDLE echo "" ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 1000 feedback off lines 169 long 2000000000 col signature format 99999999999999999999 col sql_handle format a25 col plan_name format a30 col ELAPSED_TIME for 9999999.99 col CPU_TIME for 9999999.99 col BUFFER_GETS for 9999999.99 col enabled format a5 col accepted format a5 col fixed format a5 set serveroutput on declare plans_loaded pls_integer ; begin plans_loaded := dbms_spm.alter_sql_plan_baseline( sql_handle => '${SQL_HANDLE}', plan_name => '${PLAN_NAME}', attribute_name => 'fixed', attribute_value =>'YES' ) ; dbms_output.put_line( 'plans modified: '||plans_loaded ) ; end ; / PROMPT select distinct d.plan_name, d.sql_handle, d.signature, d.OPTIMIZER_COST COST, d.executions, round(d.ELAPSED_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) ELAPSED_TIME, round(d.CPU_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) CPU_TIME, round(d.BUFFER_GETS /1000000/(case when d.executions=0 then 1 else d.executions end),2) BUFFER_GETS, d.enabled, d.accepted, d.fixed from dba_sql_plan_baselines d, v\$sql s where sql_id='${SQLID}' and d.signature = s.exact_matching_signature --and s.CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}') ; set escape on feedback off echo off pages 0 -- Set SQL_HANDLE: column SQL_HANDLE NEW_VALUE SQL_HANDLE; select distinct d.sql_handle SQL_HANDLE from dba_sql_plan_baselines d, v\$sql s where sql_id='${SQLID}' and d.signature = s.exact_matching_signature; PROMPT PROMPT -- TO ADD a PLAN to the BASELINE: [From SQLPlus] [Provide the PLAN HASH VALUE] PROMPT var pls number PROMPT exec :pls := dbms_spm.load_plans_from_cursor_cache(sql_id => '${SQLID}', plan_hash_value => '\&PLAN_HASH_VALUE', sql_handle => '&SQL_HANDLE');; PROMPT PROMPT -- TO DROP the BASELINE: [From SQLPlus] [FOR ROLLBACK PURPOSE] PROMPT var pls number PROMPT exec :pls := dbms_spm.drop_sql_plan_baseline(sql_handle => '&SQL_HANDLE');; PROMPT EOF fi break;; *) break;; esac done fi # IF SQL BASELINE is already exist, but having more than one plan, offer the option to change/fix the plan from the list of baseline plans: #if [ ${BASELINE_PLAN_COUNT} -gt 1 ] if [ ${BASELINE_PLAN_COUNT} -ge 1 ] then #echo "" #echo -e "\033[33;5mMultiple Plans Detected for this SQLID ...\033[0m" echo "" ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT PROMPT *********************** PROMPT SQL PLAN BASELINE: [For ${SQLID}] PROMPT *********************** set pages 1000 lines 169 pages 50000 long 2000000000 col signature format 99999999999999999999 col sql_handle format a25 col plan_name format a30 col ELAPSED_TIME for 9999999.99 col CPU_TIME for 9999999.99 col BUFFER_GETS for 9999999.99 col enabled format a5 col accepted format a5 col fixed format a5 col LAST_EXECUTED format a13 select distinct d.plan_name, d.sql_handle, d.signature, d.OPTIMIZER_COST COST, d.executions, round(d.ELAPSED_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) ELAPS_TIME, round(d.CPU_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) CPU_TIME, round(d.BUFFER_GETS /1000000/(case when d.executions=0 then 1 else d.executions end),2) BUFFER_GETS, d.enabled, d.accepted, d.fixed, to_char(d.LAST_EXECUTED,'DDMONYY HH24:MI') LAST_EXECUTED from dba_sql_plan_baselines d, v\$sql s where s.sql_id='${SQLID}' and d.signature = s.exact_matching_signature --and s.CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}') ; set escape on feedback off echo off pages 0 -- Set SQL_HANDLE: column SQL_HANDLE NEW_VALUE SQL_HANDLE select distinct d.sql_handle SQL_HANDLE from dba_sql_plan_baselines d, v\$sql s where sql_id='${SQLID}' and d.signature = s.exact_matching_signature; PROMPT PROMPT -- TO ADD a PLAN to the BASELINE: [From SQLPlus] [Provide the PLAN HASH VALUE] PROMPT var pls number PROMPT exec :pls := dbms_spm.load_plans_from_cursor_cache(sql_id => '${SQLID}', plan_hash_value => '\&PLAN_HASH_VALUE', sql_handle => '&SQL_HANDLE');; PROMPT PROMPT -- TO DROP the BASELINE: [From SQLPlus] [FOR ROLLBACK PURPOSE] PROMPT var pls number PROMPT exec :pls := dbms_spm.drop_sql_plan_baseline(sql_handle => '&SQL_HANDLE');; EOF echo "" echo "Do you want to FIX a plan for [${SQLID}] in the CURRENT exist BASELINE: [Y|N]" echo "============================================================================" while read ANS do case ${ANS} in y|Y|yes|YES|Yes) echo "" read -p "Enter the PLAN_NAME for the plan you want to fix [From the above query output]: " PLAN_NAME read -p "Enter the SQL_HANDLE for the plan you want to fix [From the above query output]: " SQL_HANDLE echo "" ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 1000 feedback off lines 169 pages 50000 long 2000000000 col signature format 99999999999999999999 col sql_handle format a25 col plan_name format a30 col ELAPSED_TIME for 9999999.99 col CPU_TIME for 9999999.99 col BUFFER_GETS for 9999999.99 col enabled format a5 col accepted format a5 col fixed format a5 set serveroutput on declare plans_loaded pls_integer ; begin plans_loaded := dbms_spm.alter_sql_plan_baseline( sql_handle => '${SQL_HANDLE}', plan_name => '${PLAN_NAME}', attribute_name => 'fixed', attribute_value =>'YES' ) ; dbms_output.put_line( 'plans modified: '||plans_loaded ) ; end ; / PROMPT select distinct d.plan_name, d.sql_handle, d.signature, d.OPTIMIZER_COST COST, d.executions, round(d.ELAPSED_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) ELAPSED_TIME, round(d.CPU_TIME /1000000/(case when d.executions=0 then 1 else d.executions end),2) CPU_TIME, round(d.BUFFER_GETS /1000000/(case when d.executions=0 then 1 else d.executions end),2) BUFFER_GETS, d.enabled, d.accepted, d.fixed from dba_sql_plan_baselines d, v\$sql s where sql_id='${SQLID}' and d.signature = s.exact_matching_signature --and s.CHILD_NUMBER = (select max(CHILD_NUMBER) from v\$sql_bind_capture where SQL_ID='${SQLID}') ; set escape on feedback off echo off pages 0 -- Set SQL_HANDLE: column SQL_HANDLE NEW_VALUE SQL_HANDLE select distinct d.sql_handle SQL_HANDLE from dba_sql_plan_baselines d, v\$sql s where sql_id='${SQLID}' and d.signature = s.exact_matching_signature; PROMPT PROMPT -- TO ADD a PLAN to the BASELINE: [From SQLPlus] [Provide the PLAN HASH VALUE] PROMPT var pls number PROMPT exec :pls := dbms_spm.load_plans_from_cursor_cache(sql_id => '${SQLID}', plan_hash_value => '\&PLAN_HASH_VALUE', sql_handle => '&SQL_HANDLE');; PROMPT PROMPT -- TO DROP the BASELINE: [From SQLPlus] [FOR ROLLBACK PURPOSE] PROMPT var pls number PROMPT exec :pls := dbms_spm.drop_sql_plan_baseline(sql_handle => '&SQL_HANDLE');; PROMPT EOF break;; *) break;; esac done fi fi VAL_TUN_TASK_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_ADVISOR_TASKS where TASK_NAME='${SQLID}_Tuning_Task'; EOF ) VAL_TUN_TASK=`echo ${VAL_TUN_TASK_RAW}| awk '{print $NF}'` case ${VAL_TUN_TASK} in 1) echo echo "-----------------------------------------------------------------------------------------------" # echo -e "\033[33;5mA Tuning Task already been found for SQLID [${SQLID}] You can view this task result using:\033[0m" echo -e "\033[33;5mA Tuning Task already been found for SQLID [${SQLID}]\033[0m" echo "Displaying the Recommendations:" echo "-----------------------------------------------------------------------------------------------" # echo "SET LONG 2000000000 pages 10000 lines 200" # echo "SELECT DBMS_SQLTUNE.report_tuning_task('${SQLID}_Tuning_Task') AS recommendations FROM dual;";; ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SET LONG 999999999 PAGESIZE 10000 LINESIZE 167 SELECT DBMS_SQLTUNE.report_tuning_task('${SQLID}_Tuning_Task') AS recommendations FROM dual; EOF ;; esac echo "" printf "`echo "Do you want to Tune SQLID [${SQLID}] Using SQL Tuning Advisor? (NO/YES) Default is [NO] |"` `echo -e "\033[33;5m[Licensed Feature]\033[0m"` \n" echo "===================================================================" echo "Note: Please make sure that Diagnostic & Tuning License is already acquired before using this feature." while read ANS1 do case ${ANS1} in ""|n|N|no|NO|No) break ;; ""|y|Y|yes|YES|Yes) ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF --PROMPT --PROMPT SQL Statement Full Text: --PROMPT ----------------------- --SET LONG 2000000000 PAGESIZE 10000 LINESIZE 200 --col SQL_FULLTEXT for a200 --select SQL_FULLTEXT from V\$SQL where SQL_ID='${SQLID}'; PROMPT PROMPT Creating SQL Tuning Task: "${SQLID}_Tuning_Task" ... DECLARE l_sql_tune_task_id VARCHAR2(100); BEGIN l_sql_tune_task_id := DBMS_SQLTUNE.create_tuning_task ( sql_id => '${SQLID}', scope => DBMS_SQLTUNE.scope_comprehensive, time_limit => 3600, task_name => '${SQLID}_Tuning_Task', description => 'Tuning task for statement ${SQLID}'); DBMS_OUTPUT.put_line('l_sql_tune_task_id: ' || l_sql_tune_task_id); END; / PROMPT Executing TUNING Task: "${SQLID}_Tuning_Task" ... PROMPT PROMPT Please Wait! This May Take Several Minutes ... EXEC DBMS_SQLTUNE.execute_tuning_task(task_name => '${SQLID}_Tuning_Task'); PROMPT PROMPT SQL Tuning Recommendations: PROMPT -------------------------- spool ${SQLID}_Tuning_Task_details.log SET LONG 999999999 PAGESIZE 10000 LINESIZE 200 SELECT DBMS_SQLTUNE.report_tuning_task('${SQLID}_Tuning_Task') AS recommendations FROM dual; PROMPT PROMPT Post Tuning: You may need to enforce HARD PARSING this statement to enforce using the new execution plan: PROMPT ----------- PROMPT SELECT CHILD_NUMBER,ADDRESS,HASH_VALUE,LAST_LOAD_TIME FROM V\$SQL WHERE SQL_ID='${SQLID}';; PROMPT EXEC FOR I IN (SELECT ADDRESS,HASH_VALUE,USERS_EXECUTING,SQL_TEXT FROM V\$SQLAREA WHERE SQL_ID='${SQLID}') LOOP SYS.DBMS_SHARED_POOL.PURGE(I.ADDRESS||','||I.HASH_VALUE,'C'); END LOOP;; PROMPT SELECT CHILD_NUMBER,ADDRESS,HASH_VALUE,LAST_LOAD_TIME FROM V\$SQL WHERE SQL_ID='${SQLID}';; PROMPT PROMPT For Dropping Tuning Task "${SQLID}_Tuning_Task" Use this SQL command: PROMPT ------------------------ PROMPT EXEC dbms_sqltune.drop_tuning_task(task_name => '${SQLID}_Tuning_Task');; PROMPT spool off EOF break ;; *) echo "Please enter a VALID answer [N|Y]" ;; esac done break else echo echo "SQLID [${SQLID}] is not found in the SHARED POOL!" echo echo "Searching the AWR ..." echo AWR_COUNT_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off select count(*) from table(dbms_xplan.display_awr('${SQLID}')); EOF ) AWR_COUNT=`echo ${AWR_COUNT_RAW}| awk '{print $NF}'` if [ ${AWR_COUNT} -gt 0 ] then echo "SQLID found in AWR." echo echo "Displaying the Execution Plans History ..." echo ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off set linesize 159 pages 50000 long 2000000000 col PLAN_TABLE_OUTPUT for a156 select * from table(dbms_xplan.display_awr('${SQLID}')); EOF else echo "The given SQLID is NOT found neither in the Shared Pool nor in AWR!" echo "" fi break fi done # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/bundle_remove.sh 0000740 0152073 0152061 00000002326 13526474761 015647 0 ustar oracle oinstall ################################################### # ROLLBACK the work done by aliases_DBA_BUNDLE.sh # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 03-06-2014 # # # # # # ################################################### CURR_USER=`whoami` USR_ORA_HOME=`grep ${CURR_USER} /etc/passwd| cut -f6 -d ':'|tail -1` rm -f ${USR_ORA_HOME}/.DBA_BUNDLE_profile if [ -f ${USR_ORA_HOME}/.bashrc ] then USRPROF=${USR_ORA_HOME}/.bashrc sed '/DBA_BUNDLE/d' ${USRPROF} > ${USRPROF}.tmp && mv ${USRPROF}.tmp ${USRPROF} fi if [ -f ${USR_ORA_HOME}/.profile ] then USRPROF=${USR_ORA_HOME}/.profile sed '/DBA_BUNDLE/d' ${USRPROF} > ${USRPROF}.tmp && mv ${USRPROF}.tmp ${USRPROF} fi if [ -f ${USR_ORA_HOME}/.bash_profile ] then USRPROF=${USR_ORA_HOME}/.bash_profile sed '/DBA_BUNDLE/d' ${USRPROF} > ${USRPROF}.tmp && mv ${USRPROF}.tmp ${USRPROF} fi echo echo 'The BUNDLE profie has been removed successfully from your system.' echo "If you didn't like the bundle kindly write to me on: mahmmoudadel@hotmail.com" echo DBA_BUNDLE6/object_locks.sh 0000740 0152073 0152061 00000030154 13775063411 015452 0 ustar oracle oinstall # ########################################################################### # This script shows all held locks on an object # To be run by ORACLE user # Ver 1.0 # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 01-08-2019 # # # # # # Modified: # # # ########################################################################### # ########### # Description: # ########### echo echo "=============================================" echo "This script shows all held lock on an object." echo "=============================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi # ######################### # SQLPLUS Section: # ######################### # PROMPT FOR VARIABLES: # #################### echo echo "Please Enter the OBJECT NAME:" echo "============================" while read OBJECT_NAME do if [ -z ${OBJECT_NAME} ] then echo echo "Enter the OBJECT NAME:" echo "=====================" else OBJECT_COUNT_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_OBJECTS WHERE OBJECT_TYPE in ('TABLE','MATERIALIZED VIEW') and OBJECT_NAME=UPPER('${OBJECT_NAME}'); EOF ) OBJECT_COUNT=`echo ${OBJECT_COUNT_RAW}| awk '{print $NF}'` if [ ${OBJECT_COUNT} -eq 0 ] then echo echo "INFO: OBJECT [${OBJECT_NAME}] IS NOT EXIST !" echo; echo "Searching the database for objects having similar name ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off col OBJECT_NAME for a45 col OBJECT_TYPE for a45 select OWNER,OBJECT_NAME,OBJECT_TYPE FROM DBA_OBJECTS WHERE OBJECT_TYPE in ('TABLE','MATERIALIZED VIEW') and OBJECT_NAME like UPPER('%${OBJECT_NAME}%') order by OWNER; EOF echo; echo "Enter a VALID OBJECT NAME:" echo "=========================" else break fi fi done if [ ${OBJECT_COUNT} -eq 1 ] then OBJECT_OWNER_RAW=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT OWNER FROM DBA_OBJECTS WHERE OBJECT_TYPE in ('TABLE','MATERIALIZED VIEW') and OBJECT_NAME=UPPER('${OBJECT_NAME}'); EOF ) export OBJECT_OWNER=`echo ${OBJECT_OWNER_RAW}| awk '{print $NF}'` fi if [ ${OBJECT_COUNT} -gt 1 ] then ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off col OBJECT_NAME for a45 col OBJECT_TYPE for a45 select OWNER,OBJECT_NAME,OBJECT_TYPE FROM DBA_OBJECTS WHERE OBJECT_TYPE in ('TABLE','MATERIALIZED VIEW') and OBJECT_NAME like UPPER('%${OBJECT_NAME}%') order by OWNER; EOF echo "" echo "Please Enter the OBJECT OWNER:" echo "=============================" while read OBJECT_OWNER do if [ -z ${OBJECT_OWNER} ] then echo echo "Enter the OBJECT OWNER:" echo "======================" else VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 feedback off; SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('${OBJECT_OWNER}'); EOF ) VAL22=`echo ${VAL11}| awk '{print $NF}'` if [ ${VAL22} -eq 0 ] then echo echo "INFO: SCHEMA [${OBJECT_OWNER}] IS NOT EXIST ON DATABASE [${ORACLE_SID}] !" echo; echo "Searching for existing SCHEMAS matching the provided string ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off select username "Users match provided string" from dba_users where username like upper ('%${OBJECT_OWNER}%'); EOF echo; echo "Enter a VALID SCHEMA USER:" echo "=========================" else break fi fi done fi # Execution of SQL Statement: # ########################## ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${DB_BASELINE} export LOGFILE=${DB_BASELINE} case ${HTMLENABLE} in y|Y|yes|YES|Yes|ON|On|on) if [ -x /usr/sbin/sendmail ] then export SENDMAIL="/usr/sbin/sendmail -t" export MAILEXEC="echo #" export HASHHTML="" export HASHNONHTML="--" export HASHHTMLOS="" export HASHNOHTMLOS="echo #" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) export SENDMAILARGS else export SENDMAIL="echo #" export MAILEXEC="mail -s" export HASHHTML="--" export HASHNONHTML="" export HASHHTMLOS="echo #" export HASHNOHTMLOS="" fi ;; *) export SENDMAIL="echo #" export HASHHTML="--" export HASHNONHTML="" export HASHHTMLOS="echo #" export HASHNOHTMLOS="" export MAILEXEC="mail -s" ;; esac # ############################################ # Populating Database Configuration Baseline: # ############################################ if [ ${INS_COUNT} -gt 0 ] then VAL611=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize 158 pages 300 ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF spool ${DB_BASELINE} ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CONFIGURATION BASELINE FOR DATABASE: ${ORACLE_SID} [Collected on: ${LOGDATE}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT #################################### ######## ${HASHNONHTML} PROMPT CONFIGURATION BASELINE FOR DATABASE: ${ORACLE_SID} ${HASHNONHTML} PROMPT #################################### ######## ${HASHNONHTML} PROMPT [COLLECTED ON: ${LOGDATE}] ${HASHNONHTML} PROMPT PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Database General Information: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ----------------------------- ${HASHNONHTML} PROMPT Database General Information: ${HASHNONHTML} PROMPT ----------------------------- PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT INSTANCE INFO: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF PROMPT ${HASHNONHTML} PROMPT INSTANCE INFO: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^ col INST_ID for 9999999 col inst_name for a20 col host_name for a30 col BLOCKED for a7 col STARTUP_TIME for a19 select INST_ID,instance_name INS_NAME,STATUS,DATABASE_STATUS DB_STATUS,VERSION,INSTANCE_ROLE,LOGINS,BLOCKED,to_char(STARTUP_TIME,'DD-MON-YY HH24:MI:SS') STARTUP_TIME from gv\$instance; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DATABASE INFO: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DATABASE INFO: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^ col name for a8 col DB_UNIQUE_NAME for a14 col FLASHBACK for a9 col CURRENT_SCN for 9999999999999999999 col "LOG_MODE | FORCE" for a18 col "PLATFORM_NAME | ID" for a23 col created for a9 col RESETLOGS_TIME for a15 select DBID,NAME, DB_UNIQUE_NAME, DATABASE_ROLE, PROTECTION_MODE, to_char(CREATED,'DD-MON-YY') CREATED, PLATFORM_NAME||' | '||PLATFORM_ID "PLATFORM_NAME | ID", LOG_MODE||' | '||FORCE_LOGGING "LOG_MODE | FORCE", FLASHBACK_ON FLASHBACK,OPEN_MODE, LAST_OPEN_INCARNATION# LAST_INCR#, to_char(RESETLOGS_TIME,'DD-MON-YY HH24:MI') RESETLOGS_TIME,CURRENT_SCN from v\$DATABASE; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT INSTANCE NON-DEFAULT PARAMETERS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT INSTANCE NON-DEFAULT PARAMETERS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ col INST_ID for 9999999 col "PARAMETER_VALUE" for a130 select INST_ID,NAME||'='''||VALUE||'''' "PARAMETER_VALUE" from gv\$parameter where ISDEFAULT='FALSE' order by INST_ID,NAME; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DATABASE ENABLED FEATURES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DATABASE ENABLED FEATURES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^ col PARAMETER for a45 col value for a100 select * from v\$option order by 2,1; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DATABASE FEATURES USAGE HISTORY: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DATABASE FEATURES USAGE HISTORY: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ col name for a65 select NAME,FIRST_USAGE_DATE,LAST_USAGE_DATE,DETECTED_USAGES,AUX_COUNT,ERROR_COUNT from SYS.wri\$_dbu_feature_usage order by 3,2; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DATABASE SETTINGS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DATABASE SETTINGS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ col PROPERTY_NAME for a45 col PROPERTY_VALUE for a100 select PROPERTY_NAME,PROPERTY_VALUE from database_properties order by 1; col PRODUCT for a60 col VERSION for a20 select PRODUCT,VERSION from product_component_version; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT BLOCK CHANGE TRACKING: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT BLOCK CHANGE TRACKING: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^ col FILENAME for a80 select * from v\$block_change_tracking; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT ALL SERVICES: [DBA_SERVICES] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ALL SERVICES: [DBA_SERVICES] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^ col SERVICE_NAME for a30 col NETWORK_NAME for a40 col FAILOVER_METHOD for a15 col FAILOVER_TYPE for a15 col ENABLED for a7 col CLB_GOAL for a8 select NAME SERVICE_NAME, NETWORK_NAME, ENABLED, FAILOVER_METHOD, FAILOVER_TYPE, GOAL, CLB_GOAL, to_char(CREATION_DATE,'DD-MON-YY') CREATED, AQ_HA_NOTIFICATIONS from dba_services order by 1; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CLUSTERWARE INTERCONNECT: [GV\$CLUSTER_INTERCONNECTS] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT CLUSTERWARE INTERCONNECT: [GV\$CLUSTER_INTERCONNECTS] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^ select * from SYS.GV\$CLUSTER_INTERCONNECTS; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT PATCHING HISTORY: [DBA_REGISTRY_HISTORY] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT PATCHING HISTORY: [DBA_REGISTRY_HISTORY] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ col ACTION_TIME for a19 col "ACTION | COMMENT" for a80 col VERSION for a12 select to_char(ACTION_TIME,'DD-MON-YY HH24:MI:SS') ACTION_TIME, ACTION||' | '||COMMENTS "ACTION | COMMENT", VERSION from dba_registry_history; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DATABASE LINKS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DATABASE LINKS: ${HASHNONHTML} PROMPT --------------- col "OWNER | TARGET_USER" for a45 col DB_LINK for a24 col host for a60 col created format A19 Heading "created" select OWNER||' | '||USERNAME "OWNER | TARGET_USER", DB_LINK, HOST, to_char(CREATED,'MM/DD/YYYY HH24:MI:SS') created from dba_db_links order by OWNER,DB_LINK; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DIRECTORIES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DIRECTORIES: ${HASHNONHTML} PROMPT ------------ col owner for a30 col DIRECTORY_NAME for a35 col DIRECTORY_PATH for a85 select OWNER,DIRECTORY_NAME,DIRECTORY_PATH from DBA_DIRECTORIES; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT SECURITY SETTINGS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ------------------- ${HASHNONHTML} PROMPT SECURITY SETTINGS: ${HASHNONHTML} PROMPT ------------------- PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT ACLS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ACLS: ${HASHNONHTML} PROMPT ----- SET lines 160 col host for a35 col ACL for a30 col PRINCIPAL for a15 col ACLID for a35 col start_date for a19 col end_date for a19 col ACL_OWNER for a30 col PRIVILEGE for a20 select * from dba_network_acls; SELECT * FROM dba_network_acl_privileges; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT AUDIT SETTINGS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT AUDIT SETTINGS: ${HASHNONHTML} PROMPT -------------- PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT AUDITED SYSTEM PRIVILEGES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT AUDITED SYSTEM PRIVILEGES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^ Select user_name,PRIVILEGE,success,failure from DBA_PRIV_AUDIT_OPTS order by 1,2; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT AUDITED OBJECT PRIVILEGES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT AUDITED OBJECT PRIVILEGES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^ col "OWNER.OBJECT_NAME" for a30 select OWNER||'.'||OBJECT_NAME "OWNER.OBJECT_NAME",OBJECT_TYPE,ALT,AUD,COM,DEL,GRA,IND,INS,LOC,REN,SEL,UPD,EXE,CRE,REA,WRI,FBK from DBA_OBJ_AUDIT_OPTS order by 1; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FINE GRAINED AUDITING SETTINGS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT FINE GRAINED AUDITING SETTINGS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Select POLICY_NAME,ENABLED,OBJECT_SCHEMA,OBJECT_NAME,POLICY_COLUMN from DBA_AUDIT_POLICIES; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT USERS AND PROFILES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT -------------------- ${HASHNONHTML} PROMPT USERS AND PROFILES: ${HASHNONHTML} PROMPT -------------------- PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT USERS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT USERS: ${HASHNONHTML} PROMPT ^^^^^ set lines 160 pages 300 col USERNAME for a21 col ACCOUNT_STATUS for a20 col EXPIRY_DATE for a11 col LOCK_DATE for a11 col PROFILE for a15 col "CREATE_DATE | PASS_LAST_CHANGE" for a28 col "DEFAULT | TEMPORARY TABLESPACE" for a25 col hash for a16 col LIMIT for a30 select u.USERNAME,u.ACCOUNT_STATUS,u.PROFILE,u.DEFAULT_TABLESPACE||' | '||u.TEMPORARY_TABLESPACE "DEFAULT | TEMPORARY TABLESPACE",to_char(u.EXPIRY_DATE,'DD-MON-YY')EXPIRY_DATE,to_char(u.LOCK_DATE,'DD-MON-YY')LOCK_DATE,s.PASSWORD HASH, to_char(CTIME,'DD-MON-YY') ||' | '||to_char(s.PTIME,'DD-MON-YY') "CREATE_DATE | PASS_LAST_CHANGE" from sys.dba_users u, sys.user\$ s where u.username=s.name order by 1; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT PROFILES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT PROFILES: ${HASHNONHTML} PROMPT ^^^^^^^^ col PROFILE for a35 select * from dba_profiles order by profile,resource_name; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT NUMBER OF OBJECTS IN EACH SCHEMA: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT NUMBER OF OBJECTS IN EACH SCHEMA: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ col USERNAME for a25 select USERNAME, count(decode(o.TYPE#, 2,o.OBJ#,'')) Tables, count(decode(o.TYPE#, 1,o.OBJ#,'')) Indexes, count(decode(o.TYPE#, 5,o.OBJ#,'')) Syns, count(decode(o.TYPE#, 4,o.OBJ#,'')) Views, count(decode(o.TYPE#, 6,o.OBJ#,'')) Seqs, count(decode(o.TYPE#, 7,o.OBJ#,'')) Procs, count(decode(o.TYPE#, 8,o.OBJ#,'')) Funcs, count(decode(o.TYPE#, 9,o.OBJ#,'')) Pkgs, count(decode(o.TYPE#,12,o.OBJ#,'')) Trigs, count(decode(o.TYPE#,10,o.OBJ#,'')) Deps from SYS.obj\$ o, SYS.dba_users u where u.USER_ID = o.OWNER# (+) group by USERNAME order by USERNAME; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT SCHEMAS SIZE: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT SCHEMAS SIZE: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^ set pages 999 col "size MB" format 999,999,999 col "Objects" format 999,999,999 select obj.owner "Owner" , obj_cnt "Objects" , decode(seg_size, NULL, 0, seg_size) "size MB" from (select owner, count(*) obj_cnt from dba_objects group by owner) obj , (select owner, ceil(sum(bytes)/1024/1024) seg_size from dba_segments group by owner) seg where obj.owner = seg.owner(+) order by 3 desc ,2 desc, 1; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT BIGGEST 100 OBJECTS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT BIGGEST 100 OBJECTS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^ col owner for a35 col tablespace_name format a35 col segment_name for a35 Select * from (select OWNER,SEGMENT_NAME,SEGMENT_TYPE,TABLESPACE_NAME,BYTES/1024/1024 SIZE_MB from dba_segments order by 5 desc)where rownum <101 order by SIZE_MB desc; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Super Users: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ------------- ${HASHNONHTML} PROMPT Super Users: ${HASHNONHTML} PROMPT ------------- PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT SYSDBA USERS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT SYSDBA USERS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^ select * from v\$pwfile_users; ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DBA USERS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DBA USERS: ${HASHNONHTML} PROMPT ^^^^^^^^^ select GRANTEE,GRANTED_ROLE from dba_role_privs where granted_role='DBA' order by 1; --PROMPT --${HASHNONHTML} PROMPT USERS PERMISSIONS: --${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT PHYSICAL STRUCTURE: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT -------------------- ${HASHNONHTML} PROMPT PHYSICAL STRUCTURE: ${HASHNONHTML} PROMPT -------------------- PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CONTORLFILES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT -------------- ${HASHNONHTML} PROMPT CONTORLFILES: ${HASHNONHTML} PROMPT -------------- col name for a120 select NAME from V\$CONTROLFILE; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT REDOLOG GROUPS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT REDOLOG GROUPS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^ select THREAD#,GROUP#,MEMBERS,BLOCKSIZE,BYTES/1024/1024"SIZE_MB" from v\$log order by THREAD#,GROUP#; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT REDOLOG FILES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT REDOLOG FILES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^ col MEMBER for a120 select GROUP#,TYPE,MEMBER from v\$logfile order by GROUP#; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT TABLESPACES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ------------ ${HASHNONHTML} PROMPT Tablespaces: ${HASHNONHTML} PROMPT ------------ col FORCE_LOGGING for a13 col EXTENT_MANAGEMENT for a12 col ALLOCATION_TYPE for a15 col SEG_SPACE_MANAG for a15 col BIGFILE for a7 col COMPRESSED for a10 col ENCRYPTED for a4 select TABLESPACE_NAME,BLOCK_SIZE,STATUS,CONTENTS,LOGGING,FORCE_LOGGING,EXTENT_MANAGEMENT,ALLOCATION_TYPE,SEGMENT_SPACE_MANAGEMENT SEG_SPACE_MANAG,BIGFILE,DEF_TAB_COMPRESSION COMPRESSED,ENCRYPTED from dba_tablespaces order by TABLESPACE_NAME; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DATAFILES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DATAFILES: ${HASHNONHTML} PROMPT ^^^^^^^^^ col FILE_NAME for a90 select TABLESPACE_NAME,FILE_NAME,BYTES/1024/1024 SIZE_MB,MAXBYTES/1024/1024 MAXSIZE_MB,ONLINE_STATUS from dba_data_files order by 1; ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT TABLESPACES UTILIZATION: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT TABLESPACES UTILIZATION: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^ col tablespace_name for A25 col Total_MB for 999999999999 col Used_MB for 999999999999 col '%Used' for 999.99 comp sum of Total_MB on report comp sum of Used_MB on report comp sum of FREE_MB on report bre on report select tablespace_name, (tablespace_size*$blksize)/(1024*1024) Total_MB, (used_space*$blksize)/(1024*1024) Used_MB, used_percent "%Used" from dba_tablespace_usage_metrics; ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT ASM DISKGROUPS AND DISKFILES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ASM DISKGROUPS AND DISKFILES: ${HASHNONHTML} PROMPT ------------------------------ set lines 160 col DISK_FILE_PATH for a40 col DISK_GROUP_NAME for a15 col DISK_FILE_NAME for a15 col DISK_FILE_PATH for a35 col fail_group for a12 col "PCT_USED%" for 999.99 SELECT NVL(a.name, '[CANDIDATE]') disk_group_name --, b.HEADER_STATUS , a.type REDUNDANCY , a.state MOUNT_STAT --, b.MOUNT_STATUS , b.STATE , b.path disk_file_path , b.name disk_file_name , b.failgroup fail_group ,b.TOTAL_MB, b.COLD_USED_MB, b.FREE_MB, b.COLD_USED_MB*100/b.TOTAL_MB "PCT_USED%" FROM v\$asm_diskgroup a RIGHT OUTER JOIN v\$asm_disk b USING (group_number) ORDER BY a.name, b.path; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FRA_SIZE: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT FRA_SIZE: ${HASHNONHTML} PROMPT --------- col name for a25 SELECT NAME,NUMBER_OF_FILES,SPACE_LIMIT/1024/1024/1024 AS TOTAL_SIZE_GB,SPACE_USED/1024/1024/1024 SPACE_USED_GB, SPACE_RECLAIMABLE/1024/1024/1024 SPACE_RECLAIMABLE_GB,ROUND((SPACE_USED-SPACE_RECLAIMABLE)/SPACE_LIMIT * 100, 1) AS "%FULL_AFTER_CLAIM", ROUND((SPACE_USED)/SPACE_LIMIT * 100, 1) AS "%FULL_NOW" FROM V\$RECOVERY_FILE_DEST; ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FRA_COMPONENTS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT FRA_COMPONENTS: ${HASHNONHTML} PROMPT --------------- select * from v\$flash_recovery_area_usage; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT RMAN CONFIGURATIONS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ---------------------- ${HASHNONHTML} PROMPT RMAN CONFIGURATIONS: ${HASHNONHTML} PROMPT ---------------------- col name for a45 col VALUE for a100 select name, value from v\$rman_configuration; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Active Incidents: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ---------------------- ${HASHNONHTML} PROMPT Active Incidents: ${HASHNONHTML} PROMPT ---------------------- set linesize 158 col PROBLEM_KEY for a65 select PROBLEM_KEY,to_char(FIRSTINC_TIME,'DD-MON-YY HH24:mi:ss') FIRST_OCCURENCE,to_char(LASTINC_TIME,'DD-MON-YY HH24:mi:ss') LAST_OCCURENCE FROM V\$DIAG_PROBLEM; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT OUTSTANDING ALERTS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT OUTSTANDING ALERTS: ${HASHNONHTML} PROMPT -------------------------- select * from DBA_OUTSTANDING_ALERTS; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT SCHEDULED JOBS STATUS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ------------------------------------ ${HASHNONHTML} PROMPT SCHEDULED JOBS STATUS: ${HASHNONHTML} PROMPT ------------------------------------ PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DBMS_JOBS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DBMS_JOBS: ${HASHNONHTML} PROMPT ---------- set linesize 158 col LAST_RUN for a25 col NEXT_RUN for a25 select job,schema_user,failures,to_char(LAST_DATE,'DD-Mon-YYYY hh24:mi:ss')LAST_RUN,to_char(NEXT_DATE,'DD-Mon-YYYY hh24:mi:ss')NEXT_RUN from dba_jobs; ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DBMS_SCHEDULER: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT DBMS_SCHEDULER: ${HASHNONHTML} PROMPT --------------- col OWNER for a15 col JOB_NAME for a30 col STATE for a10 col FAILURE_COUNT for 9999 heading 'Fail' col "DURATION(d:hh:mm:ss)" for a22 col REPEAT_INTERVAL for a75 col "LAST_RUN || REPEAT_INTERVAL" for a60 col "DURATION(d:hh:mm:ss)" for a12 --col LAST_START_DATE for a40 select OWNER,JOB_NAME,ENABLED,STATE,FAILURE_COUNT,to_char(LAST_START_DATE,'DD-Mon-YYYY hh24:mi:ss')||' || '||REPEAT_INTERVAL "LAST_RUN || REPEAT_INTERVAL", extract(day from last_run_duration) ||':'|| lpad(extract(hour from last_run_duration),2,'0')||':'|| lpad(extract(minute from last_run_duration),2,'0')||':'|| lpad(round(extract(second from last_run_duration)),2,'0') "DURATION(d:hh:mm:ss)" from dba_scheduler_jobs where JOB_NAME NOT LIKE 'AQ$_PLSQL_NTFN%' order by ENABLED,STATE; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT AUTOTASK INTERNAL MAINTENANCE WINDOWS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT AUTOTASK INTERNAL MAINTENANCE WINDOWS: ${HASHNONHTML} PROMPT -------------------------------------- col WINDOW_NAME for a17 col NEXT_RUN for a20 col ACTIVE for a6 col OPTIMIZER_STATS for a15 col SEGMENT_ADVISOR for a15 col SQL_TUNE_ADVISOR for a16 col HEALTH_MONITOR for a15 SELECT WINDOW_NAME,TO_CHAR(WINDOW_NEXT_TIME,'DD-MM-YYYY HH24:MI:SS') NEXT_RUN,AUTOTASK_STATUS STATUS,WINDOW_ACTIVE ACTIVE,OPTIMIZER_STATS,SEGMENT_ADVISOR,SQL_TUNE_ADVISOR,HEALTH_MONITOR FROM DBA_AUTOTASK_WINDOW_CLIENTS; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FAILED DBMS_SCHEDULER JOBS IN THE LAST 24H: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT FAILED DBMS_SCHEDULER JOBS IN THE LAST 24H: ${HASHNONHTML} PROMPT ------------------------------------------- col LOG_DATE for a36 col OWNER for a15 col JOB_NAME for a35 col STATUS for a11 col RUN_DURATION for a20 col ID for 99 select INSTANCE_ID ID,JOB_NAME,OWNER,LOG_DATE,STATUS,ERROR#,RUN_DURATION from DBA_SCHEDULER_JOB_RUN_DETAILS where LOG_DATE > sysdate-1 and STATUS='FAILED' order by JOB_NAME,LOG_DATE; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT ADVISORS STATUS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ------------------------------ ${HASHNONHTML} PROMPT ADVISORS STATUS: ${HASHNONHTML} PROMPT ------------------------------ col CLIENT_NAME for a40 col window_group for a30 col STATUS for a15 col CONSUMER_GROUP for a25 SELECT client_name, status, consumer_group, window_group FROM dba_autotask_client ORDER BY client_name; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CURRENT OS / HARDWARE STATISTICS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT -------------------------------------------------------- ${HASHNONHTML} PROMPT CURRENT OS / HARDWARE STATISTICS: ${HASHNONHTML} PROMPT -------------------------------------------------------- col value for 99999999999999999999999 select stat_name,value from v\$osstat; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT RESOURCE LIMIT: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT -------------------------------- ${HASHNONHTML} PROMPT RESOURCE LIMIT: ${HASHNONHTML} PROMPT -------------------------------- col INST_ID for 9999999 col INITIAL_ALLOCATION for a20 col LIMIT_VALUE for a20 select * from gv\$resource_limit order by RESOURCE_NAME; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT RECYCLEBIN OBJECTS# ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT -------------------------------- ${HASHNONHTML} PROMPT RECYCLEBIN OBJECTS#: ${HASHNONHTML} PROMPT -------------------------------- set feedback off select count(*) "RECYCLED_OBJECTS#",sum(space)*$blksize/1024/1024 "TOTAL_SIZE_MB" from dba_recyclebin group by 1; set feedback on ${HASHNONHTML} PROMPT PROMPT [Note: Consider purging DBA_RECYCLEBIN for better performance] PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FLASHBACK RESTORE POINTS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ------------------------------------------ ${HASHNONHTML} PROMPT FLASHBACK RESTORE POINTS: ${HASHNONHTML} PROMPT ------------------------------------------ col TIME for a35 col RESTORE_POINT_TIME for a17 col "DATABASE_INCARNATION#" heading "DB_INCR#" for 99999999 col RESTORE_POINT_TIME for a18 select * from V\$RESTORE_POINT; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT HEALTH MONITOR: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ---------------------------------- ${HASHNONHTML} PROMPT HEALTH MONITOR: ${HASHNONHTML} PROMPT ---------------------------------- select * from V\$HM_RECOMMENDATION where time_detected > sysdate -1; PROMPT ${HASHNONHTML} PROMPT ======================================================================================================== PROMPT PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT OBJECTS HIGHLIGHTS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='3' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT ------------------- ${HASHNONHTML} PROMPT OBJECTS HIGHLIGHTS: ${HASHNONHTML} PROMPT ------------------- PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT INVALID OBJECTS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT INVALID OBJECTS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^ col SUBOBJECT_NAME for a30 col status for a15 col "OWNER.OBJECT_NAME" for a55 col LAST_DDL_TIME for a20 select OWNER||'.'||OBJECT_NAME "OWNER.OBJECT_NAME",SUBOBJECT_NAME,OBJECT_TYPE,status,to_char(LAST_DDL_TIME,'DD-MON-YY HH24:mi:ss') LAST_DDL_TIME from DBA_INVALID_OBJECTS; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT UNUSABLE INDEXES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT UNUSABLE INDEXES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ col INDEX_NAME for a50 col TABLE_NAME for a50 select owner||'.'||INDEX_NAME "INDEX_NAME",INDEX_TYPE,TABLE_OWNER||'.'||TABLE_NAME "TABLE_NAME",COMPRESSION,TABLESPACE_NAME from dba_indexes where status='UNUSABLE'; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FOREIGN KEY COLUMNS WITHOUT INDEXES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT FOREIGN KEY COLUMNS WITHOUT INDEXES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ set linesize 158 col TABLE_NAME for a35 col CONSTRAINT_NAME for a35 col COLUMN_NAME for a22 select acc.OWNER, acc.TABLE_NAME, acc.COLUMN_NAME, acc.CONSTRAINT_NAME, acc.POSITION, 'No Index' Problem from dba_cons_columns acc, dba_constraints ac where ac.CONSTRAINT_NAME = acc.CONSTRAINT_NAME and ac.CONSTRAINT_TYPE = 'R' and acc.OWNER not in ('SYS','SYSTEM','DBSNMP','EXFSYS','MDSYS','ORDDATA','PERFSTAT','STDBYPERF','APEX_050000','SYSMAN','ORDSYS','OLAPSYS') and not exists ( select 'TRUE' from dba_ind_columns b where b.TABLE_OWNER = acc.OWNER and b.TABLE_NAME = acc.TABLE_NAME and b.COLUMN_NAME = acc.COLUMN_NAME and b.COLUMN_POSITION = acc.POSITION) order by acc.OWNER, acc.CONSTRAINT_NAME, acc.COLUMN_NAME, acc.POSITION; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DISABLED CONSTRAINTS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT DISABLED CONSTRAINTS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^ column OWNER format A20 Heading "OWNER" column TABLE_NAME format A35 Heading "TABLE_NAME" column CONSTRAINT_NAME format A35 Heading "CONSTRAINT_NAME" column STATUS format A12 Heading "STATUS" column type format A20 Heading "type" select OWNER, TABLE_NAME, CONSTRAINT_NAME, decode(CONSTRAINT_TYPE, 'C','Check', 'P','Primary Key', 'U','Unique', 'R','Foreign Key', 'V','With Check Option') type, STATUS from dba_constraints where STATUS = 'DISABLED' and OWNER <> 'SYSTEM' order by OWNER, TABLE_NAME, CONSTRAINT_NAME; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Monitored INDEXES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT Monitored INDEXES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ col Index_NAME for a40 col TABLE_NAME for a40 select io.name Index_NAME, t.name TABLE_NAME,decode(bitand(i.flags, 65536),0,'NO','YES') Monitoring, decode(bitand(ou.flags, 1),0,'NO','YES') USED,ou.start_monitoring,ou.end_monitoring from sys.obj$ io,sys.obj$ t,sys.ind$ i,sys.object_usage ou where i.obj# = ou.obj# and io.obj# = ou.obj# and t.obj# = i.bo# order by 1; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT COMPRESSED TABLES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT COMPRESSED TABLES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ SELECT OWNER,TABLE_NAME,TABLESPACE_NAME,COMPRESSION,COMPRESS_FOR FROM DBA_TABLES WHERE COMPRESSION='ENABLED' AND OWNER <> 'SYSMAN' ORDER BY OWNER; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT PARTITIONED TABLES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT PARTITIONED TABLES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^ col table_name format a40 select owner,table_name,DEF_TABLESPACE_NAME,partitioning_type,partition_count from dba_part_tables where owner not in ('SYS','SYSTEM','SYSMAN','SQLTXPLAIN') order by owner; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT IOT TABLES: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT IOT TABLES: ${HASHNONHTML} PROMPT ^^^^^^^^^^ select owner,table_name,IOT_TYPE from dba_tables where IOT_TYPE='IOT' and owner not in ('SYS','EXFSYS','DBSNMP','WMSYS','CTXSYS','SYSMAN'); PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT OBJECTS WITH NON-DEFAULT DEGREE OF PARALLELISM: [Query from: http://blog.tanelpoder.com/?s=index+rebuild] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT OBJECTS WITH NON-DEFAULT DEGREE OF PARALLELISM: [Query from: http://blog.tanelpoder.com/?s=index+rebuild] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ col DEGREE for a6 SELECT 'INDEX' OBJECT_TYPE, OWNER, INDEX_NAME, TRIM(DEGREE) DEGREE FROM DBA_INDEXES WHERE TRIM(DEGREE) > TO_CHAR(1) UNION ALL SELECT 'TABLE', OWNER, TABLE_NAME, TRIM(DEGREE) DEGREE FROM DBA_TABLES WHERE TRIM(DEGREE) > TO_CHAR(1) order by 1,2; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT OBJECTS WITH NOLOGGING OPTION: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT OBJECTS WITH NOLOGGING OPTION: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SELECT 'INDEX' OBJECT_TYPE, OWNER, INDEX_NAME, LOGGING FROM DBA_INDEXES WHERE LOGGING='NO' AND TEMPORARY='N' AND owner not in ('SYS','XDB','DBSNMP','SQLTXPLAIN','WMSYS','SYSMAN','SYSTEM','MDSYS','EXFSYS') UNION ALL SELECT 'TABLE', OWNER, TABLE_NAME, LOGGING FROM DBA_TABLES WHERE LOGGING='NO' AND TEMPORARY='N' AND owner not in ('SYS','XDB','DBSNMP','SQLTXPLAIN','WMSYS','SYSMAN','SYSTEM','MDSYS','EXFSYS') order by 1,2; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CORRUPTED BLOCKS: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT CORRUPTED BLOCKS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ select * from V\$DATABASE_BLOCK_CORRUPTION; PROMPT ${HASHHTML} SET PAGES 1000 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CONTROLFILE TRACE BACKUP: ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHNONHTML} PROMPT CONTROLFILE TRACE BACKUP: ${HASHNONHTML} PROMPT ------------------------- set feedback off ALTER DATABASE BACKUP CONTROLFILE TO TRACE AS '${LOG_DIR}/Controlfile_Trc_Bkp_${DB_NAME}.trc' REUSE NORESETLOGS; spool off exit; EOF ) FILE_NAME=${LOG_DIR}/Controlfile_Trc_Bkp_${DB_NAME}.trc export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${DB_BASELINE} cat ${FILE_NAME} >> ${DB_BASELINE} fi case ${COLLECT_DBUSERS_DDL} in y|Y|yes|YES|Yes) export LOGDATE=`date +%d-%b-%y` SPOOLLOF=${LOG_DIR}/List_Of_Users_${DB_NAME}_${LOGDATE}.log SPOOL_FILE=${LOG_DIR}/ALL_USERS_DDL_${DB_NAME}_${LOGDATE}.log cat /dev/null > ${SPOOLLOF} echo "-------------------" > ${SPOOL_FILE} echo "-- ALL DB USERS DLL: [Excluding SYSTEM USERS" >> ${SPOOL_FILE} echo "-------------------" >> ${SPOOL_FILE} echo "" >> ${SPOOL_FILE} # Building a list of users --excluding system users to loop on: VAL_LOOPUSERS=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF PROMPT spool ${SPOOLLOF} set pages 0 set echo off heading off feedback off -- Excluding System users: select username from dba_users where username not in ('ANONYMOUS','APEX_030200','APEX_PUBLIC_USER','APPQOSSYS','CTXSYS','DBSNMP','EXFSYS','MDDATA','MDSYS','MGMT_VIEW','OLAPSYS','ORACLE_OCM','ORDDATA','ORDPLUGINS','ORDSYS','OUTLN','OWBSYS','OWBSYS_AUDIT','PERFSTAT','SCOTT','SPATIAL_CSW_ADMIN_USR','SPATIAL_WFS_ADMIN_USR','SYS','SYSMAN','SYSTEM','WMSYS','XDB') order by 1; spool off EOF ) # Loop on each user with generating its DDL: for USERNAME in `cat ${SPOOLLOF}` do export USERNAME VAL_USERSDDL=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF spool ${SPOOL_FILE} APPEND set termout off set linesize 150 set pages 50000 set feedback off set trim on set echo off col USERNAME for a30 col account_status for a23 PROMPT ${HASHNONHTML} PROMPT -------------------------------------- ${HASHNONHTML} PROMPT -- USER [${USERNAME}] ${HASHNONHTML} PROMPT -------------------------------------- PROMPT select a.username,a.account_status,a.profile,q.tablespace_name,q.bytes/1024/1024 USED_MB, q.max_bytes "MAX_QUOTA_Bytes" from dba_users a, dba_ts_quotas q where a.username=q.username and a.username='${USERNAME}'; set pages 0 set echo off heading off feedback off -- Generate Creation Statement: SELECT 'CREATE USER ' || u.username ||' IDENTIFIED ' ||' BY VALUES ''' || c.password || ''' DEFAULT TABLESPACE ' || u.default_tablespace ||' TEMPORARY TABLESPACE ' || u.temporary_tablespace ||' PROFILE ' || u.profile || case when account_status= 'OPEN' then ';' else ' Account LOCK;' end "--Creation Statement" FROM dba_users u,user$ c where u.username=c.name and u.username=upper('${USERNAME}') UNION -- Generate Granted Roles: select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted Roles" from dba_role_privs where grantee= upper('${USERNAME}') UNION -- Generate System Privileges: select 'GRANT '||PRIVILEGE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted System Privileges" from dba_sys_privs where grantee= upper('${USERNAME}') UNION -- Generate Object Privileges: select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where GRANTEE=upper('${USERNAME}'); spool off EOF ) done echo "" >> ${DB_BASELINE} echo "-----------------------------" >> ${DB_BASELINE} echo "-- ALL DB USERS DDL SAVED TO: ${SPOOL_FILE}" >> ${DB_BASELINE} echo "-----------------------------" >> ${DB_BASELINE} echo "" >> ${DB_BASELINE} esac echo "" >> ${DB_BASELINE} #echo "" >> ${DB_BASELINE} #echo "# REPORT BUGS to: mahmmoudadel@hotmail.com" >> ${DB_BASELINE} #echo "# EVERY MONTH A NEW VERSION OF DBA BUNDLE GET RELEASED, DOWNLOAD IT FROM:" >> ${DB_BASELINE} #echo "# http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html" >> ${DB_BASELINE} case ${MAIL_CONFBASE} in y|Y|yes|YES|Yes) sed -i '/^--/d' ${DB_BASELINE} sed -i '/^rows will be truncated/d' ${DB_BASELINE} sed -i '/^truncating/d' ${DB_BASELINE} sed -i '/STARTUP NOMOUNT/d' ${DB_BASELINE} export LOGFILE=${DB_BASELINE} export MSGSUBJECT="CONFIGURATION BASELINE | DATABASE [${DB_NAME}] On Server [${SRV_NAME}]" ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} ( echo "To: ${EMAIL};" echo "MIME-Version: 1.0" echo "Content-Type: text/html;" echo "Subject: ${MSGSUBJECT}" cat ${LOGFILE} ) | ${SENDMAIL} #mail -s "CONFIGURATION BASELINE | DATABASE [${DB_NAME}] On Server [${SRV_NAME}]" ${MAIL_LIST} < ${DB_BASELINE};; esac echo "Configuration Baseline for DATABASE [${DB_NAME}]: ${DB_BASELINE}" # End looping for databases: fi done # Decide to go forward and collect OS configuration baseline or exit: case ${DB_CONFBASE_ONLY} in y|Y|yes|YES|Yes) # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi exit;; esac # ############################################################### # OS CONFIGURATION BASELINE # ############################################################### echo "# ########################################################" > ${OS_BASELINE} echo "# OS Configuration Baseline" >> ${OS_BASELINE} echo "# ########################################################" >> ${OS_BASELINE} echo "[COLLECTED ON: ${LOGDATE}]" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "============ =============================================" >> ${OS_BASELINE} echo "SERVER NAME: ${SRV_NAME}" >> ${OS_BASELINE} echo "============ =============================================" >> ${OS_BASELINE} FILE_NAME=/etc/oracle-release export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "OS Version:" >> ${OS_BASELINE} echo "----------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} elif [ -f /etc/redhat-release ] then cat /etc/redhat-release >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "Uptime Info:" >> ${OS_BASELINE} echo "-----------" >> ${OS_BASELINE} uptime >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "Kernel Version:" >> ${OS_BASELINE} echo "--------------" >> ${OS_BASELINE} uname -a >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} INST_COUNT=`/bin/ps -ef|grep pmon|grep -v grep |wc -l` if [ ${INST_COUNT} -gt 0 ] then echo "RUNNING DATABASE INSTANCES:" >> ${OS_BASELINE} echo "--------------------------" >> ${OS_BASELINE} /bin/ps -ef|grep pmon|grep -v grep >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi LISTENER_COUNT=`/bin/ps -ef|grep tnslsnr|grep -v grep|wc -l` if [ ${LISTENER_COUNT} -gt 0 ] then echo "RUNNING LISTENERS:" >> ${OS_BASELINE} echo "------------------" >> ${OS_BASELINE} /bin/ps -ef|grep tnslsnr|grep -v grep >> ${OS_BASELINE} #for LISTENER_NAME in $( ps -ef|grep -v grep|grep tnslsnr|awk 'NR==1{for (i=1;i<=NF;i++)if ($i=="-inherit"){n=i-1;m=NF-(i==NF)}} {for(i=1;i<=NF;i+=1+(i==n))printf "%s%s",$i,i==m?ORS:OFS}'|awk 'NR==1{for (i=1;i<=NF;i++)if ($i=="-no_crs_notify"){n=i-1;m=NF-(i==NF)}} {for(i=1;i<=NF;i+=1+(i==n))printf "%s%s",$i,i==m?ORS:OFS}'|awk '{print $NF}' ) for LISTENER_NAME in $( ps -ef|grep -v grep|grep tnslsnr|awk '{print $9}' ) do export LISTENER_NAME #LISTENER_HOME=`ps -ef|grep -v grep|grep tnslsnr|grep -i ${LISTENER_NAME}|awk 'NR==1{for (i=1;i<=NF;i++)if ($i=="-inherit"){n=i-1;m=NF-(i==NF)}} {for(i=1;i<=NF;i+=1+(i==n))printf "%s%s",$i,i==m?ORS:OFS}'|awk 'NR==1{for (i=1;i<=NF;i++)if ($i=="-no_crs_notify"){n=i-1;m=NF-(i==NF)}} {for(i=1;i<=NF;i+=1+(i==n))printf "%s%s",$i,i==m?ORS:OFS}'|awk '{print $(NF-1)}' |sed -e 's/\/bin\/tnslsnr//g'|grep -v sed|grep -v "s///g"|head -1` LISTENER_HOME=`ps -ef|grep -v grep|grep tnslsnr|grep -i ${LISTENER_NAME}|awk '{print $8}' |sed -e 's/\/bin\/tnslsnr//g'|grep -v sed|grep -v "s///g"|head -1` export LISTENER_HOME TNS_ADMIN=${LISTENER_HOME}/network/admin; export TNS_ADMIN # For DEBUGGING purpose: #echo "Listener_name is: $LISTENER_NAME" #echo "listener_home is: $LISTENER_HOME" #echo "TNS_ADMIN is: $TNS_ADMIN" FILE_NAME=${LISTENER_HOME}/bin/lsnrctl export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "LISTENER STATUS: [${LISTENER_NAME}]" >> ${OS_BASELINE} echo "^^^^^^^^^^^^^^^" >> ${OS_BASELINE} ${LISTENER_HOME}/bin/lsnrctl status ${LISTENER_NAME} >> ${OS_BASELINE} fi done fi FILE_NAME=/etc/sysconfig/grub export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "Boot Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "-------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi # Hashed STARTUP configurations to be run only by root user: #FILE_NAME=/etc/inittab #export FILE_NAME #if [ -f ${FILE_NAME} ] #then #echo "" >> ${OS_BASELINE} #echo "Startup Configurations: ${FILE_NAME}" >> ${OS_BASELINE} #echo "-------------------------------------" >> ${OS_BASELINE} #cat ${FILE_NAME} >> ${OS_BASELINE} #fi # ############################################ # Checking RAC/ORACLE_RESTART Services: # ############################################ case ${CLUSTER_CHECK} in y|Y|yes|YES|Yes) # Check for ocssd clusterware process: CHECK_OCSSD=`ps -ef|grep 'ocssd.bin'|grep -v grep|wc -l` CHECK_CRSD=`ps -ef|grep 'crsd.bin'|grep -v grep|wc -l` if [ ${CHECK_CRSD} -gt 0 ] then CLS_STR=crs export CLS_STR CLUSTER_TYPE=CLUSTERWARE export CLUSTER_TYPE else CLS_STR=has export CLS_STR CLUSTER_TYPE=ORACLE_RESTART export CLUSTER_TYPE fi if [ ${CHECK_OCSSD} -gt 0 ] then GRID_HOME=`ps -ef|grep 'ocssd.bin'|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v sed|grep -v "//g"|tail -1` export GRID_HOME if [ ! -d ${GRID_HOME} ] then ASM_INSTANCE_NAME=`ps -ef|grep pmon|grep -v grep|grep asm_pmon_|awk '{print $NF}'|sed -e 's/asm_pmon_//g'|grep -v sed|grep -v "s///g"|tail -1` GRID_HOME=`dbhome ${ASM_INSTANCE_NAME}` export GRID_HOME fi GRID_BASE=`cat ${GRID_HOME}/crs/install/crsconfig_params|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/crs/utl/appvipcfg|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "${CLUSTER_TYPE} DETAILS" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=${GRID_HOME}/bin/crsctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "CLUSTER VERSION: crsctl query ${CLS_STR} softwareversion" >> ${OS_BASELINE} echo "---------------" >> ${OS_BASELINE} ${GRID_HOME}/bin/crsctl query ${CLS_STR} softwareversion >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi if [ ${CHECK_CRSD} -gt 0 ] then GRID_HOME=`ps -ef|grep 'ocssd.bin'|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v sed|grep -v "//g"` export GRID_HOME FILE_NAME=${GRID_HOME}/bin/olsnodes export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "CLUSTER NAME: ${FILE_NAME} -c" >> ${OS_BASELINE} echo "------------" >> ${OS_BASELINE} ${GRID_HOME}/bin/olsnodes -c >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "CLUSTER NODES: ${FILE_NAME} -n -s -t" >> ${OS_BASELINE} echo "-------------" >> ${OS_BASELINE} ${GRID_HOME}/bin/olsnodes -n -s -t >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=${GRID_HOME}/bin/oifcfg export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "CLUSTER INTERCONNECT & PUBLIC IP NAME: oifcfg getif" >> ${OS_BASELINE} echo "-------------------------------------" >> ${OS_BASELINE} ${GRID_HOME}/bin/oifcfg getif >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=${ORACLE_HOME}/bin/srvctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "CLUSTER SCAN IPs: srvctl config scan" >> ${OS_BASELINE} echo "----------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl config scan >> ${OS_BASELINE} fi FILE_NAME=${ORACLE_HOME}/bin/srvctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "CLUSTER VIRTUAL IP NAME: srvctl config nodeapps" >> ${OS_BASELINE} echo "-----------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl config nodeapps >> ${OS_BASELINE} fi FILE_NAME=${ORACLE_HOME}/bin/srvctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "CLUSTER SCAN Listeners: srvctl config scan_listener" >> ${OS_BASELINE} echo "----------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl config scan_listener >> ${OS_BASELINE} fi FILE_NAME=${ORACLE_HOME}/bin/srvctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "CLUSTER SCAN Listeners status: srvctl status scan_listener" >> ${OS_BASELINE} echo "-----------------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl status scan_listener >> ${OS_BASELINE} fi FILE_NAME=${GRID_HOME}/bin/ocrcheck export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "^^^^^^^^^^" >> ${OS_BASELINE} echo "OCR DISKS:" >> ${OS_BASELINE} echo "^^^^^^^^^^" >> ${OS_BASELINE} ${GRID_HOME}/bin/ocrcheck >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=${GRID_HOME}/bin/crsctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "^^^^^^^^^^^" >> ${OS_BASELINE} echo "VOTE DISKS:" >> ${OS_BASELINE} echo "^^^^^^^^^^^" >> ${OS_BASELINE} ${GRID_HOME}/bin/crsctl query css votedisk >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi fi FILE_NAME=${ORACLE_HOME}/bin/srvctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "ASM CONFIGURATIONS: srvctl config asm" >> ${OS_BASELINE} echo "------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl config asm >> ${OS_BASELINE} fi FILE_NAME=${GRID_HOME}/bin/crsctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "CLUSTERWARE SERVICES: crsctl status resource" >> ${OS_BASELINE} echo "---------------------" >> ${OS_BASELINE} AWK=/usr/bin/awk $AWK \ 'BEGIN {printf "%-55s %-24s %-18s\n", "HA Resource", "Target", "State"; printf "%-55s %-24s %-18s\n", "-----------", "------", "-----";}' >> ${OS_BASELINE} $GRID_HOME/bin/crsctl status resource | $AWK \ 'BEGIN { FS="="; state = 0; } $1~/NAME/ && $2~/'$1'/ {appname = $2; state=1}; state == 0 {next;} $1~/TARGET/ && state == 1 {apptarget = $2; state=2;} $1~/STATE/ && state == 2 {appstate = $2; state=3;} state == 3 {printf "%-55s %-24s %-18s\n", appname, apptarget, appstate; state=0;}' >> ${OS_BASELINE} fi # Clustered Databases Configurations: FILE_NAME=${ORACLE_HOME}/bin/srvctl export FILE_NAME if [ -x ${FILE_NAME} ] then # Loop for the clustered configured databases: for CLUSTER_DB in $(${ORACLE_HOME}/bin/srvctl config database) do export CLUSTER_DB echo "" >> ${OS_BASELINE} echo "^^^^^^^^^^^^^^^^^^^" >> ${OS_BASELINE} echo "Database [${CLUSTER_DB}]" >> ${OS_BASELINE} echo "^^^^^^^^^^^^^^^^^^^" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "DATABASE CONFIGURATIONS: srvctl config database -d ${CLUSTER_DB}" >> ${OS_BASELINE} echo "-----------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl config database -d ${CLUSTER_DB} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "DATABASE SERVICES STATUS: srvctl status service -d ${CLUSTER_DB}" >> ${OS_BASELINE} echo "------------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl status service -d ${CLUSTER_DB} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "DATABASE SERVICES CONFIGURATIONS: srvctl config service" >> ${OS_BASELINE} echo "--------------------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/bin/srvctl config service -d ${CLUSTER_DB} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} done fi FILE_NAME=${GRID_HOME}/crs/install/s_crsconfig_${SRV_NAME}_env.txt export FILE_NAME if [ -f ${FILE_NAME} ] then echo "CLUSTERWARE NLS_LANG CONFIGURATIONS: ${FILE_NAME}" >> ${OS_BASELINE} echo "-----------------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/oracle/ocr.loc export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "OCR DISKS LOCATION: ${FILE_NAME}" >> ${OS_BASELINE} echo "-------------------" >> ${OS_BASELINE} cat /etc/oracle/ocr.loc >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi fi ;; esac echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "ORACLE FILES" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=${ORATAB} export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "ORATAB: ${FILE_NAME}" >> ${OS_BASELINE} echo "------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi # Oracle Network Files: #TNS_ADMIN=${ORACLE_HOME}/network/admin #export TNS_ADMIN FILE_NAME=${TNS_ADMIN}/listener.ora export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "LISTENER: ${FILE_NAME}" >> ${OS_BASELINE} echo "--------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=${TNS_ADMIN}/tnsnames.ora export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "TNSNAMES: ${FILE_NAME}" >> ${OS_BASELINE} echo "--------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=${TNS_ADMIN}/sqlnet.ora export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "SQLNET: ${FILE_NAME}" >> ${OS_BASELINE} echo "------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi # APPLIED PATCHES DETAILS: FILE_NAME=${ORACLE_HOME}/OPatch/opatch export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "ORACLE PATCHES DETAILS: opatch lsinventory -details" >> ${OS_BASELINE} echo "-----------------------" >> ${OS_BASELINE} ${ORACLE_HOME}/OPatch/opatch lsinventory -details >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi # Workaround df command output bug "`/root/.gvfs': Permission denied" if [ -f /etc/redhat-release ] then export DF='df -hTPx fuse.gvfs-fuse-daemon' else export DF='df -hT' fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "FILESYSTEM Settings" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "df -h" >> ${OS_BASELINE} echo "------" >> ${OS_BASELINE} /bin/${DF} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "mount Command:" >> ${OS_BASELINE} echo "--------------" >> ${OS_BASELINE} /bin/mount >> ${OS_BASELINE} FILE_NAME=/etc/fstab export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "/etc/fstab" >> ${OS_BASELINE} echo "----------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/sbin/blkid export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "ASM DISKS MOUNT AND LABELS: ${FILE_NAME}" >> ${OS_BASELINE} echo "--------------------------" >> ${OS_BASELINE} echo "NOTE: IT'S HIGHLY RECOMMENDED TO RUN THIS COMMAND AS ROOT TO GET AN ACCURATE LIST OF DISKS: /sbin/blkid |sort -k 2 -t:|grep oracleasm" >> ${OS_BASELINE} # oracleasm listdisks | xargs oracleasm querydisk -p | grep TYPE | sort -k 2 /sbin/blkid |sort -k 2 -t:|grep oracleasm >> ${OS_BASELINE} fi FILE_NAME=/etc/exports export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "NFS Shares: ${FILE_NAME}" >> ${OS_BASELINE} echo "----------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/sysconfig/rawdevices export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "RAW Devices: ${FILE_NAME}" >> ${OS_BASELINE} echo "------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/multipath.conf export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "Multipath Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "-------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/sysconfig/oracleasm export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "Oracle ASM Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "--------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/bin/lsblk export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "List of ALL Disks Connected to this Host: lsblk -fo +size" >> ${OS_BASELINE} echo "----------------------------------------" >> ${OS_BASELINE} /bin/lsblk -fo +size >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "USERS AND GROUPS" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "Oracle Owner Configuration:" >> ${OS_BASELINE} echo "---------------------------" >> ${OS_BASELINE} /usr/bin/id ${ORA_USER} >> ${OS_BASELINE} /usr/bin/id >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "ACCOUNT Settings:" >> ${OS_BASELINE} echo "................." >> ${OS_BASELINE} /usr/bin/chage -l ${ORA_USER} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "RESOURCE Limits:" >> ${OS_BASELINE} echo "................" >> ${OS_BASELINE} ulimit -a >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "CRONTAB Jobs:" >> ${OS_BASELINE} echo "............." >> ${OS_BASELINE} /usr/bin/crontab -l 2>/dev/null >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "bash_profile:" >> ${OS_BASELINE} echo "............." >> ${OS_BASELINE} cat ~/.bash_profile >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=/etc/passwd export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "USERS Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "---------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/group export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "GROUPS Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "----------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/security/limits.conf export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "USERS LIMITS Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "---------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/profile export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "GENERIC USERS PROFILE: ${FILE_NAME}" >> ${OS_BASELINE} echo "----------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/bashrc export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "GENERIC BASHRC PROFILE: ${FILE_NAME}" >> ${OS_BASELINE} echo "----------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "SECURITY Settings" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=/etc/pam.d/system-auth export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "PAM Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "-------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/login.defs export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "LOGINS DEFAULT Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "------------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi # Hashed FIREWALL configurations to be run only by root user: #FILE_NAME=/etc/sysconfig/iptables-config #export FILE_NAME #if [ -f ${FILE_NAME} ] #then #echo "" >> ${OS_BASELINE} #echo "FIREWALL Configurations: ${FILE_NAME}" >> ${OS_BASELINE} #echo "-----------------------" >> ${OS_BASELINE} #cat ${FILE_NAME} >> ${OS_BASELINE} #fi #FILE_NAME=/etc/sysconfig/iptables #export FILE_NAME #if [ -f ${FILE_NAME} ] #then #echo "" >> ${OS_BASELINE} #echo "FIREWALL RULES: ${FILE_NAME}" >> ${OS_BASELINE} #echo "--------------" >> ${OS_BASELINE} #cat ${FILE_NAME} >> ${OS_BASELINE} #fi FILE_NAME=/etc/sysconfig/selinux export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "SELINUX Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "-----------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/etc/issue export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "INTRO Message Configuration: ${FILE_NAME}" >> ${OS_BASELINE} echo "----------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "SERVICES Configurations" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} #FILE_NAME=/sbin/service #export FILE_NAME #if [ -f ${FILE_NAME} ] #then #echo "" >> ${OS_BASELINE} #echo "RUNNING SERVICES: /sbin/service --status-all" >> ${OS_BASELINE} #echo "-----------------" >> ${OS_BASELINE} #/sbin/service --status-all 2>/dev/null >> ${OS_BASELINE} #echo "" >> ${OS_BASELINE} #fi FILE_NAME=/sbin/chkconfig export FILE_NAME if [ -x ${FILE_NAME} ] then if [ -f /etc/rc.d/init.d ] then echo "" >> ${OS_BASELINE} echo "SERVICES Settings: chkconfig --list" >> ${OS_BASELINE} echo "-----------------" >> ${OS_BASELINE} /sbin/chkconfig --list|sort >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "NETWORK Settings" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=/etc/sysconfig/network export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "GENERAL NETWORK Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "------------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/resolv.conf export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "DNS Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/sbin/ifconfig export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "NICs Configurations: [ifconfig -a]" >> ${OS_BASELINE} echo "--------------------" >> ${OS_BASELINE} /sbin/ifconfig -a >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "Routing Table: [netstat -rn]" >> ${OS_BASELINE} echo "--------------" >> ${OS_BASELINE} netstat -rn >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "NICs Config Files:" >> ${OS_BASELINE} echo "------------------" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} for FILE_NAME in /etc/sysconfig/network-scripts/ifcfg-* do export FILE_NAME if [ -f ${FILE_NAME} ] then echo "cat ${FILE_NAME}" >> ${OS_BASELINE} echo "............................................." >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi done echo "" >> ${OS_BASELINE} FILE_NAME=/etc/modprobe.conf export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "NICs/BONDING ALIASES: ${FILE_NAME}" >> ${OS_BASELINE} echo "--------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/hosts export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "${FILE_NAME} Configurations:" >> ${OS_BASELINE} echo "---------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/hosts.allow export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "TCP WRAPPER: ALLOWED HOSTS: ${FILE_NAME}" >> ${OS_BASELINE} echo "---------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/hosts.deny export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "TCP WRAPPER: DENIED HOSTS: ${FILE_NAME}" >> ${OS_BASELINE} echo "--------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/mail/sendmail.mc export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "SMTP SERVER: ${FILE_NAME}" >> ${OS_BASELINE} echo "-----------" >> ${OS_BASELINE} cat /etc/mail/sendmail.mc|grep SMART >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi # https://superuser.com/questions/529830/get-a-list-of-open-ports-in-linux [datashaman] FILE_NAME=/bin/netstat export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "Open Ports:" >> ${OS_BASELINE} echo "^^^^^^^^^^^" >> ${OS_BASELINE} netstat -lnt | awk 'NR>2{print $4}' | grep -E '(0.0.0.0:|:::)' | sed 's/.*://' | sort -n | uniq >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "TIME AND DATE Configurations" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=/etc/localtime export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "LOCAL TIME Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "-------------------------" >> ${OS_BASELINE} tail -1 ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/sbin/chkconfig export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "NTP SERVICE STATUS: chkconfig --list|grep ntp" >> ${OS_BASELINE} echo "------------------" >> ${OS_BASELINE} /sbin/chkconfig --list|grep ntp >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/ntp.conf export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "NTP Configurations: ${FILE_NAME}" >> ${OS_BASELINE} echo "------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/sysconfig/ntpd export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "NTP Settings: ${FILE_NAME}" >> ${OS_BASELINE} echo "------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "LOGGING Settings" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=/etc/sysconfig/syslog export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "SYSLOG Settings: ${FILE_NAME}" >> ${OS_BASELINE} echo "---------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/sysconfig/sysstat export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "KEEP LOG Settings: ${FILE_NAME}" >> ${OS_BASELINE} echo "-----------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/etc/logrotate.conf export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "ROTATE LOG Settings: ${FILE_NAME}" >> ${OS_BASELINE} echo "-------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "CURRENT RESOURCES INFORMATION" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=/dev/mem export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "ALL HARDWARE DETAILS: dmidecode" >> ${OS_BASELINE} echo "---------------------" >> ${OS_BASELINE} /usr/sbin/dmidecode >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/sbin/lspci export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "PCI DEVICES DETAILS: lspci" >> ${OS_BASELINE} echo "-------------------" >> ${OS_BASELINE} /sbin/lspci >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/proc/cpuinfo export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "CPU DETAILS: ${FILE_NAME}" >> ${OS_BASELINE} echo "-----------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/proc/meminfo export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "MEMORY DETAILS: ${FILE_NAME}" >> ${OS_BASELINE} echo "--------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "KERNEL Settings" >> ${OS_BASELINE} echo "==========================================================" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} FILE_NAME=/etc/sysctl.conf export FILE_NAME if [ -f ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "Kernel NON-DEFAULT PARAMETERS: ${FILE_NAME}" >> ${OS_BASELINE} echo "-----------------------------" >> ${OS_BASELINE} cat ${FILE_NAME} >> ${OS_BASELINE} fi FILE_NAME=/sbin/sysctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "ALL KERNEL PARAMETERS:" >> ${OS_BASELINE} echo "----------------------" >> ${OS_BASELINE} /sbin/sysctl -a 2>/dev/null >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi FILE_NAME=/bin/rpm export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_BASELINE} echo "List Of ALL INSTALLED PACKAGES:" >> ${OS_BASELINE} echo "------------------------------" >> ${OS_BASELINE} /bin/rpm -qa|sort >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} fi echo "" >> ${OS_BASELINE} echo "---------------------------------" >> ${OS_BASELINE} echo "END OF OS CONFIGURATION BASELINE." >> ${OS_BASELINE} echo "---------------------------------" >> ${OS_BASELINE} echo "" >> ${OS_BASELINE} echo "# REPORT BUGS to: mahmmoudadel@hotmail.com" >> ${OS_BASELINE} echo "# DOWNLOAD THE LATEST VERSION OF DBA BUNDLE FROM:" >> ${OS_BASELINE} echo "# http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html" >> ${OS_BASELINE} case ${MAIL_CONFBASE} in y|Y|yes|YES|Yes) mail -s "CONFIGURATION BASELINE | SERVER [${SRV_NAME}]" ${MAIL_LIST} < ${OS_BASELINE};; esac echo "Configuration Baseline for OPERATING SYSTEM: ${OS_BASELINE}" echo "" # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/login.sql.bundle 0000640 0152073 0152061 00000014064 14122405700 015543 0 ustar oracle oinstall -- -------------------------------------------------------------------------------- -- Ver 2.3 -- This script improves the display of SQLPlus environment -- -- Author: Mahmmoud ADEL -- Updates: 14-09-21 Enabled Parallelism on session level if used by the DBA. -- 14-09-21 Enabled DDL LOCK Timeout to avoid getting resource -- busy error when altering busy table. -- -------------------------------------------------------------------------------- PROMPT <> PROMPT set sqlprompt "_date' '_user'@'_connect_identifier> " set linesize 170 set pages 1000 set long 32000 col name for a60 col OWNER for a25 col SCHEMANAME for a25 col OBJECT_NAME for a40 col PASSWORD for a30 col OSPID for a10 col PROGRAM for a40 col MODULE for a40 col MACHINE for a40 col ACTION for a25 col EVENT for a25 col WAIT_CLASS for a25 col TRACEID for a25 col TRACEFILE for a65 col inst_name for a20 col host_name for a30 col host for a45 col member for a70 col file_name for a70 col OS_USERNAME for a20 col OSUSER for a20 col username for a20 col user_name for a20 col userhost for a20 col DB_LINK for a30 col TERMINAL for a15 col P1TEXT for a15 col P2TEXT for a15 col P3TEXT for a15 col ID for 99 col TIMESTAMP for a30 col ACTION_NAME for a10 col OPNAME for a21 col limit for a30 col LAST_LOGIN for a30 col profile for a35 col COMMENTS for a60 col DESCRIPTION for a60 col resource for a30 col ACTION_TIME for a30 col MESSAGE for a77 col SERVICE_NAME for a15 col EXTERNAL_NAME for a15 col resource_name for a30 col DEFAULT_COLLATION for a20 col ACCOUNT_STATUS for a16 col tablespace_name for a40 col DIRECTORY_NAME for a30 col DIRECTORY_PATH for a60 col PROPERTY_NAME for a27 col PROPERTY_VALUE for a30 col CURRENT_SCN for 99999999999999999 col INITIAL_RSRC_CONSUMER_GROUP for a20 -- Used by Trusted Oracle COLUMN ROWLABEL FORMAT A15 -- Used for the SHOW ERRORS command COLUMN LINE/COL FORMAT A8 COLUMN ERROR FORMAT A65 WORD_WRAPPED -- Used for the SHOW SGA command COLUMN name_col_plus_show_sga FORMAT a24 -- Defaults for SHOW PARAMETERS COLUMN name_col_plus_show_param FORMAT a36 HEADING NAME COLUMN value_col_plus_show_param FORMAT a99 HEADING VALUE -- Defaults for SET AUTOTRACE EXPLAIN report COLUMN id_plus_exp FORMAT 990 HEADING i COLUMN parent_id_plus_exp FORMAT 990 HEADING p COLUMN plan_plus_exp FORMAT a60 COLUMN object_node_plus_exp FORMAT a8 COLUMN other_tag_plus_exp FORMAT a29 COLUMN other_plus_exp FORMAT a44 set pages 0 feedback off lines 25 -- Setting DATE format: alter session set nls_date_format = 'DD-Mon-YYYY HH24:MI:SS'; -- Setting Session identifier: EXEC DBMS_SESSION.set_identifier('LOCAL_SESSION_POWERDED_BY_DBA_BUNDLE'); -- Setting DDL LOCK Timeout: [30 seconds] alter session set ddl_lock_timeout=30; -- Enable Parallelism on Session level: alter session enable parallel dml; alter session enable parallel ddl; alter session enable parallel query; col INS_NAME for a11 col INST_ID heading ID for 99 col STATUS for a9 col DB_OPEN_MODE for a12 col "DB_STATUS|OPEN_MODE" for a27 col "LOG_MODE|FORCE" for a15 col FLASHBACK for a9 col BLOCKED for a7 col STARTUP_TIME for a18 PROMPT My Session Details: PROMPT ------------------- select /*+RULE*/ 'SID | '||s.sid, 'Serial# | '||s.serial#, 'OSPID | '||p.spid from v$session s, v$process p where s.sid = (select sid from v$mystat where rownum = 1) and s.paddr=p.addr; set pages 100 lines 170 select /*+RULE*/ s.inst_id ID,s.instance_name INS_NAME,d.NAME DB_NAME,s.STATUS INS_STATUS,s.DATABASE_STATUS||'|'||d.OPEN_MODE "DB_STATUS|OPEN_MODE",d.DATABASE_ROLE DB_ROLE,d.LOG_MODE||'|'||d.FORCE_LOGGING "LOG_MODE|FORCE",d.FLASHBACK_ON FLASHBACK,s.LOGINS,to_char(s.STARTUP_TIME,'DD-MON-YY HH24:MI:SS') STARTUP_TIME from gv$instance s, v$database d order by 1; /* set serveroutput on declare ins_bundle varchar2(10); insstatus_bundle varchar2(20); dbstatus_bundle varchar2(20); logins_bundle varchar2(20); blocked_bundle varchar2(20); startupt_bundle varchar2(40); db_bundle varchar2(20); logmode_bundle varchar2(20); forcelog_bundle varchar2(20); flashback_bundle varchar2(20); openmode_bundle varchar2(30); dbrole_bundle varchar2(20); sid_bundle number; serial_bundle number; spid_bundle number; begin select s.sid, s.serial#, p.spid into sid_bundle, serial_bundle, spid_bundle from v$session s, v$process p where s.sid = (select sid from v$mystat where rownum = 1) and s.paddr=p.addr; select instance_name,STATUS,DATABASE_STATUS,LOGINS,BLOCKED,to_char(STARTUP_TIME,'DD-MON-YY HH24:MI:SS') into ins_bundle,insstatus_bundle,dbstatus_bundle,logins_bundle,blocked_bundle,startupt_bundle from gv$instance; select name,LOG_MODE,FORCE_LOGGING,flashback_on,OPEN_MODE,DATABASE_ROLE into db_bundle,logmode_bundle,forcelog_bundle,flashback_bundle,openmode_bundle,dbrole_bundle from v$database; dbms_output.put_line('------------------ ------------------'); dbms_output.put_line('INS Name|Status: ' || ins_bundle || ' | ' || insstatus_bundle); dbms_output.put_line('DB Name|Status: ' || db_bundle || ' | ' || dbstatus_bundle); dbms_output.put_line('DB Mode: ' || openmode_bundle); dbms_output.put_line('DB Role: ' || dbrole_bundle); dbms_output.put_line('Logins: ' || logins_bundle); dbms_output.put_line('Services Blocked: ' || blocked_bundle); dbms_output.put_line('ARCHIVELOG Mode: ' || logmode_bundle); dbms_output.put_line('FORCE LOGGING: ' || forcelog_bundle); dbms_output.put_line('FLASHBACK Mode: ' || flashback_bundle); dbms_output.put_line('Startup Time: ' || startupt_bundle); dbms_output.put_line('------------------ ------------------'); dbms_output.put_line('My SID: ' || sid_bundle); dbms_output.put_line('My Serial#: ' || serial_bundle); dbms_output.put_line('My OSPID: ' || spid_bundle); dbms_output.put_line('------------------ ------------------'); end; / */ set pages 1000 feedback on prompt DBA_BUNDLE6/dbdailychk.sh 0000740 0152073 0152061 00000317271 14122402715 015106 0 ustar oracle oinstall # ################################################################################################################################## # DATABASE DAILY HEALTH CHECK MONITORING SCRIPT VER="[6.2]" # =================================================================================================== # CAUTION: THIS SCRIPT MAY CAUSE A SLIGHT OVEARHEAD, DO NOT RUN IT TOO FREQUENT, ONCE A DAY IS IDEAL. # =================================================================================================== # *********** # How To Use: # *********** # 1- Set your Email by modifying this parameter below: EMAIL="youremail@yourcompany.com" # 2- Check the THRESHOLDS section and make sure they meet your policy. # 3- You can DISABLE/ENABLE some section by altering the parameter that accept Y or N values # e.g. Disable Memory Check Section in the report: # Go to THRESHOLDS section and set: # CHECK_MEMORY=N # **************************************************************************************************** # FEATURES: # ******** # CHECKING CPU UTILIZATION. # CHECKING FILESYSTEM UTILIZATION. # CHECKING TABLESPACES UTILIZATION. # CHECKING FLASH RECOVERY AREA UTILIZATION. # CHECKING ASM DISKGROUPS UTILIZATION. # CHECKING BLOCKING SESSIONS ON THE DATABASE. # CHECKING UNUSABLE INDEXES ON THE DATABASE. # CHECKING INVALID OBJECTS ON THE DATABASE. # CHECKING CORRUPTED BLOCKS ON THE DATABASE. # CHECKING FAILED JOBS IN THE DATABASE. # CHECKING LONG RUNNING JOBS [For More than 1 Day]. # CHECKING ACTIVE INCIDENTS. # CHECKING OUTSTANDING ALERTS. # CHECKING DATABASE SIZE GROWTH. # CHECKING RMAN BACKUPs. # REPORT UNRECOVERABLE DB FILES. # CHECKING OS / HARDWARE STATISTICS. # CHECKING RESOURCE LIMITS. # CHECKING RECYCLEBIN. # CHECKING CURRENT RESTORE POINTS. # CHECKING HEALTH MONITOR CHECKS RECOMMENDATIONS THAT RUN BY DBMS_HM PACKAGE. # CHEKCING MONITORED INDEXES. # CHECKING REDOLOG SWITCHES. # CHECKING MODIFIED INTIALIZATION PARAMETERS SINCE THE LAST DB STARTUP. # CHECKING ADVISORS RECOMMENDATIONS: # - SQL TUNING ADVISOR # - SGA ADVISOR # - PGA ADVISOR # - BUFFER CACHE ADVISOR # - SHARED POOL ADVISOR # - SEGMENT ADVISOR # CHECKING NEW CREATED OBJECTS. # CHECKING AUDIT RECORDS. # CHECKING FAILED LOGIN ATTEMPTS. # # # # # # Author: Mahmmoud ADEL # # # # ### # # # # # # # # Created: 22-12-13 Based on dbalarm.sh script. # Modifications:18-05-14 Added Filsystem monitoring. # 19-05-14 Added CPU monitoring. # 09-12-14 Added Tablespaces monitoring # Added BLOCKING SESSIONS monitoring # Added UNUSABLE INDEXES monitoring # Added INVALID OBJECTS monitoring # Added FAILED LOGINS monitoring # Added AUDIT RECORDS monitoring # Added CORRUPTED BLOCKS monitoring # [It will NOT run a SCAN. It will look at V$DATABASE_BLOCK_CORRUPTION] # Added FAILED JOBS monitoring. # 06-10-15 Replaced mpstat with iostat for CPU Utilization Check # 02-11-15 Enhanced "FAILED JOBS monitoring" part. # 13-12-15 Added Advisors Recommendations to the report # 04-04-16 dba_tablespace_usage_metrics view will be used for 11g onwards versions # for checking tablespaces size, advised by: Satyajit Mohapatra # 10-04-16 Add Flash Recovery Area monitoring # 10-04-16 Add ASM Disk Groups monitoring # 15-07-16 Add ACTIVE INCIDENTS, RESOURCE LIMITS, RECYCLEBIN, RESTORE POINTS, # MONITORED INDEXES, REDOLOG SWITCHES, MODIFIED SPFILE PARAMETERS checks. # 02-01-17 Removed ALERTLOG check for DB & Listener + # Merged alerts with advisors. [Recommended by: ABD-ELGAWAD] # 03-01-17 Added checking RAC status feature. [Recommended by: Samer ALJazzar] # 09-01-17 Added RMAN BACKUP CHECK. # 04-05-17 Added Reporting of Newly Created Objects in the last 24Hours. # 12-06-17 Added Long Running Jobs Alert. # 20-07-17 Neutralize login.sql if found under Oracle user home directory due to bugs. # 10-10-17 Added reporting Long Running Queries to the report. # 09-01-18 Workaround for df command bug "`/root/.gvfs': Permission denied" # 16-05-18 Added SHOWSQLTUNINGADVISOR, SHOWMEMORYADVISORS, SHOWSEGMENTADVVISOR, SHOWJOBS # and SHOWHASHEDCRED parameters to allow the user to decide whether to show their # results in the report or not. # 21-06-18 Added MODOBJCONTTHRESHOLD to control the display of LAST MODIFIED OBJECTS in the report. # 15-08-18 Added REPORT UNRECOVERABLE DATABASE FILES that don't have a valid backup. # 10-02-19 Removed the failed jobs alerting from the script. # 19-02-19 Added HTML email format content. # 04-04-19 Added Reporting of Top Fragmented Tables. # 16-06-20 Excluding goldengate modules from Long Running Queries reporting. # 22-06-20 Modified the check for cluster services to get compatible with 12c+. # 23-06-20 Listed: Running Instances/listeners, open ports in the report. # 14-09-20 Added Memory utilization check feature, combining both RAM and SWAP in the calculation. # 14-09-20 Reorganize script sections to make it easy to edit by users. # 23-11-20 Enhance df command output in HTML mode # 04-04-21 Listing Dormant accounts in the report. # 04-04-21 Auditing data will be included in the report by default. [If AUD$ is big this section will take much time] # 20-09-21 Show yesterday's hardware (CPU & Memory) stats if crossed the thresholds. # # # # ################################################################################################################################## # HERE YOU SET YOUR EMAIL: EMAIL="youremail@yourcompany.com" # HERE YOU SET THE SMTP SERVER IF EXIST. UNHASH THE BELOW LINE AND REPLACE "mailrelay.mycompany.com" WITH YOUR COMPANY's SMTP: #export smtp="mailrelay.mycompany.com:25" # This is an example, your Network Admin knows the SMTP NAME & PORT to use. # ######################### # THRESHOLDS: # ######################### # Send an E-mail for each THRESHOLD if been reached: # ADJUST the following THRESHOLD VALUES as per your requirements: HTMLENABLE=Y # Enable HTML Email Format [DB] FSTHRESHOLD=95 # THRESHOLD FOR FILESYSTEM %USED [OS] CPUTHRESHOLD=95 # THRESHOLD FOR CPU %UTILIZATION [OS] CHECK_MEMORY=Y # REPORT LOW MEMORY USING BELOW TWO DEFINED THRESHOLDS COMBINED [OS] USEDPHYSICALMEM_PCT=95 # THRESHOLD FOR RAM %UTILIZATION [OS] USEDSWAPMEM_PCT=75 # THRESHOLD FOR SWAP SPACE %UTILIZATION [OS] CHECK_CLUSTER=Y # CHECK CLUSTERWARE HEALTH [CL] CHKAUDITRECORDS=Y # INCLUDE AUDIT RECORDS IN THE REPORT [increases CPU Load] [DB] SHOWDORMANTACCOUNTS=Y # SHOW INACTIVE ACCOUNTS IN THE REPORT [DB] DORMANT_INACTIVE_DAYS=45 # SHOW Inactive Accounts with NO login attempts since 45 days.[DB] SHOWSQLTUNINGADVISOR=Y # INCLUDE SQL TUNING ADVISOR RESULTS IN THE REPORT [DB] SHOWMEMORYADVISORS=Y # INCLUDE MEMORY ADVISORS RESULTS IN THE REPORT [DB] SHOWSEGMENTADVVISOR=N # INCLUDE SEGMENT ADVISOR RESULTS IN THE REPORT [DB] SHOWJOBS=Y # INCLUDE DB JOBS DETAILS IN THE REPORT [DB] SHOWHASHEDCRED=N # INCLUDE DB USERS HASHED VERSION CREDENTIALS IN THE REPORT [DB] REPORTUNRECOVERABLE=Y # INCLUDE UNRECOVERABLE DATAFILES IN THE REPORT. [DB] TBSTHRESHOLD=95 # THRESHOLD FOR TABLESPACE %USED [DB] FRATHRESHOLD=95 # THRESHOLD FOR FLASH RECOVERY AREA %USED [DB] ASMTHRESHOLD=95 # THRESHOLD FOR ASM DISK GROUPS [DB] UNUSEINDXTHRESHOLD=1 # THRESHOLD FOR NUMBER OF UNUSABLE INDEXES [DB] INVOBJECTTHRESHOLD=1 # THRESHOLD FOR NUMBER OF INVALID OBJECTS [DB] FAILLOGINTHRESHOLD=1 # THRESHOLD FOR NUMBER OF FAILED LOGINS [DB] AUDITRECOTHRESHOLD=1 # THRESHOLD FOR NUMBER OF AUDIT RECORDS [DB] CORUPTBLKTHRESHOLD=1 # THRESHOLD FOR NUMBER OF CORRUPTED BLOCKS [DB] FAILDJOBSTHRESHOLD=1 # THRESHOLD FOR NUMBER OF FAILED JOBS [DB] JOBSRUNSINCENDAY=1 # THRESHOLD FOR JOBS RUNNING LONGER THAN N DAY [DB] NEWOBJCONTTHRESHOLD=1 # THRESHOLD FOR NUMBER OF NEWLY CREATED OBJECTS [DB] MODOBJCONTTHRESHOLD=1 # THRESHOLD FOR NUMBER OF MODIFIED OBJECTS [DB] LONG_RUN_QUR_HOURS=1 # THRESHOLD FOR QUERIES RUNNING LONGER THAN N HOURS [DB] SHOW_YESTERDAY_STATS=Y # CHECKER FOR SHOWING HARDWARE RESOURCES THAT CROSSED THRESHOLDS[OS] # ####################################### # Excluded Modules: # ####################################### # Here you can exclude the modules you don't want their queries to get reported in the Long Running Queries list: # goldegate modules are excluded below, to add extra modules, make sure to enclose them between single quote and separating them by a comma: EXCLUDED_MODULES="'OGG-USE_OCI_THREAD','OGG-OCI_META_THREAD'" # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluding INSTANCES [Will get excluded from the report]. # ######################### # Excluded ERRORS: # ######################### # Here you can exclude the errors that you don't want to be alerted when they appear in the logs: # Use pipe "|" between each error. EXL_ALERT_ERR="ORA-2396|TNS-00507|TNS-12502|TNS-12560|TNS-12537|TNS-00505" #Excluded ALERTLOG ERRORS [Will not get reported]. EXL_LSNR_ERR="TNS-00507|TNS-12502|TNS-12560|TNS-12537|TNS-00505" #Excluded LISTENER ERRORS [Will not get reported]. # ################################ # Excluded FILESYSTEM/MOUNT POINTS: # ################################ # Here you can exclude specific filesystems/mount points from being reported by the script: # e.g. Excluding: /dev/mapper, /dev/asm mount points: EXL_FS="\/dev\/mapper\/|\/dev\/asm\/" #Excluded mount points [Will be skipped during the check]. # Workaround df command output bug "`/root/.gvfs': Permission denied" if [ -f /etc/redhat-release ] then export DF='df -hTPx fuse.gvfs-fuse-daemon' else export DF='df -hT' fi export SRV_NAME="`uname -n`" case ${EMAIL} in "youremail@yourcompany.com") echo echo "##############################################################################################" echo "You Missed Something! :-)" echo "In order to receive the HEALTH CHECK report via Email, set your E-mail at line# 110" echo "by replacing this template [youremail@yourcompany.com] with YOUR E-mail address." echo "DB HEALTH CHECK report will be saved on disk..." echo "##############################################################################################" export SQLLINESIZE=165 echo;; *) export SQLLINESIZE=200 export OSLINESIZE=300 ;; esac SCRIPT_NAME="dbdailychk${VER}" # In case your company Emails go through a specific SMTP server. Specify it in the below line and UN-HASH it: #export smtp="mailrelay.mycompany.com:25" #This is an example, you have to check with your Network Admin for the SMTP NAME/PORT to use. export MAIL_LIST="${EMAIL}" #export MAIL_LIST="-r ${SRV_NAME} ${EMAIL}" echo echo "[dbdailychk Script Started ...]" # ######################### # Checking The FILESYSTEM: # ######################### # Report Partitions that reach the threshold of Used Space: FSLOG=/tmp/filesystem_DBA_BUNDLE.log echo "[Reported By ${SCRIPT_NAME} Script" > ${FSLOG} echo "" >> ${FSLOG} ${DF} >> ${FSLOG} ${DF} | grep -v "^Filesystem" |awk '{print substr($0, index($0, $2))}'| egrep -v "${EXL_FS}"|awk '{print $(NF-1)" "$NF}'| while read OUTPUT do PRCUSED=`echo ${OUTPUT}|awk '{print $1}'|cut -d'%' -f1` FILESYS=`echo ${OUTPUT}|awk '{print $2}'` if [ ${PRCUSED} -ge ${FSTHRESHOLD} ] then mail -s "ALARM: Filesystem [${FILESYS}] on Server [${SRV_NAME}] has reached ${PRCUSED}% of USED space" ${MAIL_LIST} < ${FSLOG} fi done rm -f ${FSLOG} # ######################### # Getting ORACLE_SID: # ######################### # Exit with sending Alert mail if No DBs are running: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) if [ $INS_COUNT -eq 0 ] then echo "[Reported By ${SCRIPT_NAME} Script]" > /tmp/oracle_processes_DBA_BUNDLE.log echo " " >> /tmp/oracle_processes_DBA_BUNDLE.log echo "Current running INSTANCES on server [${SRV_NAME}]:" >> /tmp/oracle_processes_DBA_BUNDLE.log echo "***************************************************" >> /tmp/oracle_processes_DBA_BUNDLE.log ps -ef|grep -v grep|grep pmon >> /tmp/oracle_processes_DBA_BUNDLE.log echo " " >> /tmp/oracle_processes_DBA_BUNDLE.log echo "Current running LISTENERS on server [${SRV_NAME}]:" >> /tmp/oracle_processes_DBA_BUNDLE.log echo "***************************************************" >> /tmp/oracle_processes_DBA_BUNDLE.log ps -ef|grep -v grep|grep tnslsnr >> /tmp/oracle_processes_DBA_BUNDLE.log mail -s "ALARM: No Databases Are Running on Server ${SRV_NAME} !!!" ${MAIL_LIST} < /tmp/oracle_processes_DBA_BUNDLE.log rm -f /tmp/oracle_processes_DBA_BUNDLE.log exit fi # ######################### # Setting ORACLE_SID: # ######################### for ORACLE_SID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do export ORACLE_SID # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" mail -s "dbdailychk script on Server [${SRV_NAME}] failed to locate ORACLE_HOME for SID [${ORACLE_SID}], Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory" ${MAIL_LIST} < /dev/null exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ############################# # Getting hostname in lowercase: # ############################# HOSTNAMELOWER=$( echo "`hostname --short`"| tr '[A-Z]' '[a-z]' ) export HOSTNAMELOWER # ######################## # Getting GRID_HOME: # ######################## CHECK_OCSSD=`ps -ef|grep 'ocssd.bin'|grep -v grep|wc -l` CHECK_CRSD=`ps -ef|grep 'crsd.bin'|grep -v grep|wc -l` if [ ${CHECK_OCSSD} -gt 0 ] then GRID_HOME=`ps -ef|grep 'ocssd.bin'|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v sed|grep -v "//g"|tail -1` export GRID_HOME if [ ! -d ${GRID_HOME} ] then ASM_INSTANCE_NAME=`ps -ef|grep pmon|grep -v grep|grep asm_pmon_|awk '{print $NF}'|sed -e 's/asm_pmon_//g'|grep -v sed|grep -v "s///g"|tail -1` GRID_HOME=`dbhome ${ASM_INSTANCE_NAME}` export GRID_HOME fi # ######################## # Getting GRID_BASE: # ######################## # Locating GRID_BASE: GRID_BASE=`cat ${GRID_HOME}/crs/install/crsconfig_params|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/crs/utl/appvipcfg|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi if [ ! -d ${GRID_BASE} ] then GRID_BASE=`cat ${GRID_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export GRID_BASE fi fi # ######################### # Variables: # ######################### export PATH=${PATH}:${ORACLE_HOME}/bin export LOG_DIR=${USR_ORA_HOME}/BUNDLE_Logs mkdir -p ${LOG_DIR} chown -R ${ORA_USER} ${LOG_DIR} chmod -R go-rwx ${LOG_DIR} if [ ! -d ${LOG_DIR} ] then mkdir -p /tmp/BUNDLE_Logs export LOG_DIR=/tmp/BUNDLE_Logs chown -R ${ORA_USER} ${LOG_DIR} chmod -R go-rwx ${LOG_DIR} fi cat /dev/null > ${LOG_DIR}/dbdailychk.part.log export LOGFILE=${LOG_DIR}/dbdailychk.part.log # ######################### # HTML Preparation: # ######################### case ${HTMLENABLE} in y|Y|yes|YES|Yes|ON|On|on) if [ -x /usr/sbin/sendmail ] then export SENDMAIL="/usr/sbin/sendmail -t" export MAILEXEC="echo #" export HASHHTML="" export HASHNONHTML="--" export HASHHTMLOS="" export HASHNOHTMLOS="echo #" SENDMAILARGS=$( echo "To: ${EMAIL};" echo "Subject: ${MSGSUBJECT} ;" echo "Content-Type: text/html;" echo "MIME-Version: 1.0;" cat ${LOGFILE} ) export SENDMAILARGS else export SENDMAIL="echo #" export MAILEXEC="mail -s" export HASHHTML="--" export HASHNONHTML="" export HASHHTMLOS="echo #" export HASHNOHTMLOS="" fi ;; *) export SENDMAIL="echo #" export HASHHTML="--" export HASHNONHTML="" export HASHHTMLOS="echo #" export HASHNOHTMLOS="" export MAILEXEC="mail -s" ;; esac export LOGFILE=${LOG_DIR}/dbdailychk.part.log export SRV_NAME="`uname -n`" # ########################## # Neutralize login.sql file: [Bug Fix] # ########################## # Existance of login.sql file under Oracle user Linux home directory eliminates many functions during the execution of this script from crontab: if [ -f ${USR_ORA_HOME}/login.sql ] then #echo "login.sql file found and will be neutralized." mv ${USR_ORA_HOME}/login.sql ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} fi # ######################## # Getting ORACLE_BASE: # ######################## # Get ORACLE_BASE from user's profile if it EMPTY: if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`cat ${ORACLE_HOME}/install/envVars.properties|grep ^ORACLE_BASE|tail -1|awk '{print $NF}'|sed -e 's/ORACLE_BASE=//g'` export ORACLE_BASE fi if [ ! -d "${ORACLE_BASE}" ] then ORACLE_BASE=`grep -h 'ORACLE_BASE=\/' ${USR_ORA_HOME}/.bash* ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_BASE fi # ######################### # Getting DB_NAME: # ######################### DB_NAME_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < ${JOBSRUNSINCENDAY} and SESSION_ID is not null; SELECT count(*) from dba_scheduler_running_jobs where extract(day FROM elapsed_time) > ${JOBSRUNSINCENDAY}; exit; EOF ) VAL510=`echo ${VAL410} | awk '{print $NF}'` if [ ${VAL510} -ge 1 ] then VAL610=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} pages 1000 -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF spool ${LOGFILE} ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Long Running Jobs [${ORACLE_SID}] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT Long Running Jobs: [${ORACLE_SID}] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ col INS for 999 col "JOB_NAME|OWNER|SPID|SID" for a55 col ELAPSED_TIME for a17 col CPU_USED for a17 col "WAIT_SEC" for 9999999999 col WAIT_CLASS for a15 col "BLKD_BY" for 9999999 col "WAITED|WCLASS|EVENT" for a45 select j.RUNNING_INSTANCE INS,j.JOB_NAME ||' | '|| j.OWNER||' |'||SLAVE_OS_PROCESS_ID||'|'||j.SESSION_ID"JOB_NAME|OWNER|SPID|SID" ,s.FINAL_BLOCKING_SESSION "BLKD_BY",ELAPSED_TIME,CPU_USED ,substr(s.SECONDS_IN_WAIT||'|'||s.WAIT_CLASS||'|'||s.EVENT,1,45) "WAITED|WCLASS|EVENT",S.SQL_ID from dba_scheduler_running_jobs j, gv\$session s where j.RUNNING_INSTANCE=S.INST_ID(+) and j.SESSION_ID=S.SID(+) and extract(day FROM elapsed_time) > ${JOBSRUNSINCENDAY} order by "JOB_NAME|OWNER|SPID|SID",ELAPSED_TIME; spool off exit; EOF ) #mail -s "WARNING: JOBS running for more than ${JOBSRUNSINCENDAY} day detected on database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" ${MAIL_LIST} < ${LOG_DIR}/long_running_jobs.log export MSGSUBJECT="WARNING: JOBS running for more than ${JOBSRUNSINCENDAY} day detected on database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" #SENDMAILARGS=$( #echo "To: ${EMAIL};" #echo "Subject: ${MSGSUBJECT} ;" #echo "Content-Type: text/html;" #echo "MIME-Version: 1.0;" #cat ${LOGFILE} #) ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} #echo ${SENDMAILARGS} | tr \; '\n' |awk 'length == 1 || NR == 1 {print $0} length && NR > 1 { print substr($0,2) }'| ${SENDMAIL} ( echo "To: ${EMAIL};" echo "MIME-Version: 1.0" echo "Content-Type: text/html;" echo "Subject: ${MSGSUBJECT}" cat ${LOGFILE} ) | ${SENDMAIL} cat /dev/null > ${LOGFILE} fi # ############################################ # LOGFILE SETTINGS: # ############################################ # Logfile path variable: DB_HEALTHCHK_RPT=${LOG_DIR}/${DB_NAME_UPPER}_HEALTH_CHECK_REPORT.log OS_HEALTHCHK_RPT=${LOG_DIR}/OS_HEALTH_CHECK_REPORT.log export DB_HEALTHCHK_RPT # Flush the logfile: export LOGDATE=`date +%d-%b-%y` echo "HEALTH_CHECK_REPORT_FOR_DATABASE_[${DB_NAME_UPPER}]_ON_{${LOGDATE}}" > ${DB_HEALTHCHK_RPT} cat /dev/null > ${OS_HEALTHCHK_RPT} # ########################### # Checking Memory Utilization: # ########################### case ${CHECK_MEMORY} in y|Y|yes|YES|Yes|ON|On|on) # Check the Linux OS version: export PATH=${PATH}:/usr/local/bin FILE_NAME=/etc/redhat-release export FILE_NAME if [ -f ${FILE_NAME} ] then LNXVER=`cat /etc/redhat-release | grep -o '[0-9]'|head -1` export LNXVER # IF LINUX VERSION IS 6 OR LOWER: if [ ${LNXVER} -le 6 ] then MEMTOTAL=`cat /proc/meminfo|grep MemTotal|awk '{print $(NF-1)}'` MEMUSEDRAW=`free -k|grep 'Mem:'|awk '{print $(3)}'` MEMCACHED=`cat /proc/meminfo|grep '^Cached:'|awk '{print $(NF-1)}'` MEMFREE=$(awk "BEGIN {print ${MEMTOTAL} - ${MEMUSEDRAW} + ${MEMCACHED}}") MEMUSED=$(awk "BEGIN {print ${MEMTOTAL} - ${MEMFREE}}") MEMUSEDPCTFLOAT=$(awk "BEGIN {print ${MEMUSED} * 100 / ${MEMTOTAL}}") MEMUSEDPCT=${MEMUSEDPCTFLOAT%.*} SWAPTOTAL=`cat /proc/meminfo|grep SwapTotal|awk '{print $(NF-1)}'` SWAPFREE=`cat /proc/meminfo|grep SwapFree|awk '{print $(NF-1)}'` SWAPUSED=$(awk "BEGIN {print ${SWAPTOTAL} - ${SWAPFREE}}") SWAPUSEDPCTFLOAT=$(awk "BEGIN {print ${SWAPUSED} * 100 / ${SWAPTOTAL}}") SWAPUSEDPCT=${SWAPUSEDPCTFLOAT%.*} fi # IF LINUX VERSION IS 7 OR HIGHER: if [ ${LNXVER} -ge 7 ] then MEMTOTAL=`cat /proc/meminfo|grep MemTotal|awk '{print $(NF-1)}'` MEMUSEDRAW=`free -k|grep 'Mem:'|awk '{print $(3)}'` MEMCACHED=`cat /proc/meminfo|grep '^Cached:'|awk '{print $(NF-1)}'` MEMFREE=`cat /proc/meminfo|grep MemAvailable|awk '{print $(NF-1)}'` MEMUSED=$(awk "BEGIN {print ${MEMTOTAL} - ${MEMFREE}}") MEMUSEDPCTFLOAT=$(awk "BEGIN {print ${MEMUSED} * 100 / ${MEMTOTAL}}") MEMUSEDPCT=${MEMUSEDPCTFLOAT%.*} SWAPTOTAL=`cat /proc/meminfo|grep SwapTotal|awk '{print $(NF-1)}'` SWAPFREE=`cat /proc/meminfo|grep SwapFree|awk '{print $(NF-1)}'` SWAPUSED=$(awk "BEGIN {print ${SWAPTOTAL} - ${SWAPFREE}}") SWAPUSEDPCTFLOAT=$(awk "BEGIN {print ${SWAPUSED} * 100 / ${SWAPTOTAL}}") SWAPUSEDPCT=${SWAPUSEDPCTFLOAT%.*} fi # Show MEMORY ALERT if both MEMUSEDPCT and SWAPUSEDPCT are below their defined thresholds: if [ ${MEMUSEDPCT} -ge ${USEDPHYSICALMEM_PCT} ] && [ ${SWAPUSEDPCT} -ge ${USEDSWAPMEM_PCT} ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "MEMORY_WARNING: " >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "Looks_The_Server_Is_Running_Out_of_Memory!." >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} echo "%USED_PHYSICAL_RAM:${MEMUSEDPCT}%" >> ${OS_HEALTHCHK_RPT} echo "%USED_SWAP_SPACE:${SWAPUSEDPCT}%" >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} echo "Memory_Details:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} free -g >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} mail -s "ALARM: OUT OF MEMORY Scenario is Imminent on Server [${SRV_NAME}]" ${MAIL_LIST} < ${OS_HEALTHCHK_RPT} fi fi ;; esac # Show yesterday's hardware stats if crossed threshold: case ${SHOW_YESTERDAY_STATS} in Y|y|YES|Yes|yes|ON|On|on) # Yesterday's High CPU Utilization: # ################################# # If CPU IDLE is below 5% or CPU Utilization is higher than 95%: HIGH_CPU_CNT=`sar -f /var/log/sa/sa$(date +%d -d yesterday) | sed -r '/^\s*$/d' | awk '{ if ( $NF < 5 ) print $NF,$1,$2 }'|wc -l` if [ ${HIGH_CPU_CNT} -gt 1 ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "Yesterday's_High_CPU_Periods:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} sar -f /var/log/sa/sa$(date +%d -d yesterday) | sed -r '/^\s*$/d' | grep -v Linux | awk '{ if ( $NF < 5 ) print $NF,$1,$2 }' >> ${OS_HEALTHCHK_RPT} fi # Yesterday's High Memory Utilization: # #################################### # If Memory utilization cross 95%: HIGH_MEM_CNT=`sar -r -f /var/log/sa/sa$(date +%d -d yesterday) | grep -Ev 'Average|Linux' | awk '{ if ( $5 > 95 ) print $5,$1,$2 }'|wc -l` if [ ${HIGH_MEM_CNT} -ge 1 ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "Yesterday's_High_Memory_Periods:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} sar -r -f /var/log/sa/sa$(date +%d -d yesterday) | grep -Ev 'Average|Linux' | awk '{ if ( $5 > 95 ) print $5,$1,$2 }' >> ${OS_HEALTHCHK_RPT} fi ;; esac # Filesystem Utilization: # ####################### echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "Local_Filesystem:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} ${DF} >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} sed -i 's/Mounted on/Mounted_on/g' ${OS_HEALTHCHK_RPT} # ############################################ # Checking RAC/ORACLE_RESTART Services: # ############################################ case ${CHECK_CLUSTER} in y|Y|yes|YES|Yes|ON|On|on) # Check for ocssd clusterware process: CHECK_OCSSD=`ps -ef|grep 'ocssd.bin'|grep -v grep|wc -l` CHECK_CRSD=`ps -ef|grep 'crsd.bin'|grep -v grep|wc -l` if [ ${CHECK_CRSD} -gt 0 ] then CLS_STR=crs export CLS_STR CLUSTER_TYPE=CLUSTERWARE export CLUSTER_TYPE else CLS_STR=has export CLS_STR CLUSTER_TYPE=ORACLE_RESTART export CLUSTER_TYPE fi if [ ${CHECK_CRSD} -gt 0 ] then GRID_HOME=`ps -ef|grep 'ocssd.bin'|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v sed|grep -v "//g"` export GRID_HOME echo "^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "CLUSTERWARE CHECKS:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} FILE_NAME=${GRID_HOME}/bin/ocrcheck export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "OCR DISKS CHECKING:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} ${GRID_HOME}/bin/ocrcheck >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} fi FILE_NAME=${GRID_HOME}/bin/crsctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "VOTE DISKS CHECKING:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} ${GRID_HOME}/bin/crsctl query css votedisk >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} fi fi if [ ${CHECK_OCSSD} -gt 0 ] then GRID_HOME=`ps -ef|grep 'ocssd.bin'|grep -v grep|awk '{print $NF}'|sed -e 's/\/bin\/ocssd.bin//g'|grep -v sed|grep -v "//g"` export GRID_HOME FILE_NAME=${GRID_HOME}/bin/crsctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "${CLUSTER_TYPE}_SERVICES:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} EXCLUDED_SERVICES="ora.proxy_advm|ora.asmgroup|ora.diskmon|ora.ons" $GRID_HOME/bin/crsctl status res |grep -v "^$"|awk -F "=" 'BEGIN {print " "} {printf("%s",NR%4 ? $2"|" : $2"\n")}'|sed -e 's/ *, /,/g' -e 's/, /,/g'|\ awk -F "|" 'BEGIN { printf "%-50s%-50s\n","Resource_Name","State";printf "%-50s%-50s\n", "-------------------------------------","---------------------"; }{ split ($3,trg,",") split ($4,st,",")} {for (i in trg) {printf "%-50s%-50s\n",$1,st[i]}}'|egrep -v "${EXCLUDED_SERVICES}" >> ${OS_HEALTHCHK_RPT} fi FILE_NAME=${ORACLE_HOME}/bin/srvctl export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "DATABASE_SERVICES_STATUS:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} ${ORACLE_HOME}/bin/srvctl status service -d ${DB_UNQ_NAME} >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} fi fi ;; esac echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "List_of_All_Running_Instances:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} ps -ef|grep pmon|grep -v grep >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "List_of_All_Running_Listeners:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} ps -ef|grep tnslsnr|grep -v grep >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} # https://superuser.com/questions/529830/get-a-list-of-open-ports-in-linux [datashaman] FILE_NAME=/bin/netstat export FILE_NAME if [ -x ${FILE_NAME} ] then echo "" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} echo "List_of_All_Open_Ports:" >> ${OS_HEALTHCHK_RPT} echo "^^^^^^^^^^^^^^^^^^^^^^^" >> ${OS_HEALTHCHK_RPT} netstat -lnt | awk 'NR>2{print $4}' | grep -E '(0.0.0.0:|:::)' | sed 's/.*://' | sort -n | uniq >> ${OS_HEALTHCHK_RPT} echo "" >> ${OS_HEALTHCHK_RPT} fi # Convert OS Checks into HTML format: #${HASHHTMLOS} awk 'BEGIN { print "

"} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${OS_HEALTHCHK_RPT} >> ${DB_HEALTHCHK_RPT} case ${HASHHTMLOS} in 'echo #') cat ${OS_HEALTHCHK_RPT} >> ${DB_HEALTHCHK_RPT};; *) ${HASHHTMLOS} awk 'BEGIN { print ""} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${OS_HEALTHCHK_RPT} >> ${DB_HEALTHCHK_RPT};; esac # ############################################ # REPORT UNRECOVERABLE DATABASE FILES: [RMAN] # ############################################ case ${REPORTUNRECOVERABLE} in Y|y|YES|Yes|yes|ON|On|on) VAL37=$(${ORACLE_HOME}/bin/rman target / << EOF spool log to ${LOG_DIR}/unrecoverable_DBfiles.log; REPORT UNRECOVERABLE; spool log off; exit; EOF ) #${HASHHTMLOS} echo "" > ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log #${HASHHTMLOS} echo "" > ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log #${HASHHTMLOS} echo "UNRECOVERABLE_DATABASE_FILES:RMAN" >> ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log #${HASHHTMLOS} echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >> ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log #${HASHHTMLOS} sed '/Spooling \|Recovery Manager\|RMAN>\|using \|Report \|^$/d' ${LOG_DIR}/unrecoverable_DBfiles.log >> ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log #${HASHHTMLOS} awk 'BEGIN { print ""} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log >> ${DB_HEALTHCHK_RPT} ;; esac # ############################################ # Checking Advisors: # ############################################ # Checking if the Advisors should be enabled in the report: case ${SHOWSQLTUNINGADVISOR} in Y|y|YES|Yes|yes|ON|On|on) export HASHSTA="";; *) export HASHSTA="--";; esac case ${SHOWMEMORYADVISORS} in Y|y|YES|Yes|yes|ON|On|on) export HASHMA="";; *) export HASHMA="--";; esac case ${SHOWSEGMENTADVVISOR} in Y|y|YES|Yes|yes|ON|On|on) export HASHSA="";; *) export HASHSA="--";; esac case ${REPORTUNRECOVERABLE} in Y|y|YES|Yes|yes|ON|On|on) export HASHU="";; *) export HASHU="--";; esac case ${SHOWJOBS} in Y|y|YES|Yes|yes|ON|On|on) export HASHJ="";; *) export HASHJ="--";; esac case ${SHOWHASHEDCRED} in Y|y|YES|Yes|yes|ON|On|on) export HASHCRD="";; *) export HASHCRD="--";; esac case ${SHOWDORMANTACCOUNTS} in Y|y|YES|Yes|yes|ON|On|on) export HASHDORM="";; *) export HASHDORM="--";; esac # If the database version is 10g onward collect the advisors recommendations: if [ ${DB_VER} -gt 9 ] then VAL611=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} pages 100 -- Enable HTML color format: --${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF spool ${DB_HEALTHCHK_RPT} app ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Tablespaces Size ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT Tablespaces Size: [Based on Datafiles MAXSIZE] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ set pages 1000 linesize ${SQLLINESIZE} tab off col tablespace_name for A25 col Total_MB for 999999999999 col Used_MB for 999999999999 col '%Used' for 999.99 comp sum of Total_MB on report comp sum of Used_MB on report bre on report select tablespace_name, (tablespace_size*$blksize)/(1024*1024) Total_MB, (used_space*$blksize)/(1024*1024) Used_MB, -- used_percent "%Used" ${HASHHTML} case when used_percent > 90 then '' || to_char(used_percent,999.99) || '' else to_char(used_percent,999.99) end as "%Used" ${HASHNONHTML} to_char(used_percent,999.99) "%Used" from dba_tablespace_usage_metrics; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT ASM STATISTICS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT ASM STATISTICS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^ select name,state,OFFLINE_DISKS,total_mb,free_mb, ${HASHHTML} case when ROUND((1-(free_mb / total_mb))*100, 2) > 90 then '' || to_char(ROUND((1-(free_mb / total_mb))*100, 2),999.99) || '' else to_char(ROUND((1-(free_mb / total_mb))*100, 2),999.99) end as "%FULL" ${HASHNONHTML} to_char(ROUND((1-(free_mb / total_mb))*100, 2),999.99) "%FULL" from v\$asm_diskgroup; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FRA STATISTICS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT FRA STATISTICS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^ ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FRA SIZE ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT FRA_SIZE: ${HASHNONHTML} PROMPT ^^^^^^^^^ col name for a35 SELECT NAME,NUMBER_OF_FILES,SPACE_LIMIT/1024/1024/1024 AS TOTAL_SIZE_GB,SPACE_USED/1024/1024/1024 SPACE_USED_GB, SPACE_RECLAIMABLE/1024/1024/1024 SPACE_RECLAIMABLE_GB,ROUND((SPACE_USED-SPACE_RECLAIMABLE)/SPACE_LIMIT * 100, 1) AS "%FULL_AFTER_CLAIM", ${HASHHTML} case when ROUND((SPACE_USED)/SPACE_LIMIT * 100, 1) > 90 then '' || to_char(ROUND((SPACE_USED)/SPACE_LIMIT * 100, 1),999.99) || '' else to_char(ROUND((SPACE_USED)/SPACE_LIMIT * 100, 1),999.99) end as "%FULL_NOW" ${HASHNONHTML} to_char(ROUND((SPACE_USED)/SPACE_LIMIT * 100, 1),999.99) "%FULL_NOW" FROM V\$RECOVERY_FILE_DEST; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FRA COMPONENTS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT FRA_COMPONENTS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^ select * from v\$flash_recovery_area_usage; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT DATABASE GROWTH ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT DATABASE GROWTH: [In the Last ~8 days] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF set serveroutput on col SNAP_TIME for a45 col "Database Size(GB)" for 99999999999999999 Declare v_BaselineSize number(20); v_CurrentSize number(20); v_TotalGrowth number(20); v_Space number(20); cursor usageHist is select a.snap_id, SNAP_TIME, sum(TOTAL_SPACE_ALLOCATED_DELTA) over ( order by a.SNAP_ID) ProgSum from (select SNAP_ID, sum(SPACE_ALLOCATED_DELTA) TOTAL_SPACE_ALLOCATED_DELTA from DBA_HIST_SEG_STAT group by SNAP_ID having sum(SPACE_ALLOCATED_TOTAL) <> 0 order by 1 ) a, (select distinct SNAP_ID, to_char(END_INTERVAL_TIME,'DD-Mon-YYYY HH24:Mi') SNAP_TIME from DBA_HIST_SNAPSHOT) b where a.snap_id=b.snap_id; Begin select sum(SPACE_ALLOCATED_DELTA) into v_TotalGrowth from DBA_HIST_SEG_STAT; select sum(bytes) into v_CurrentSize from dba_segments; v_BaselineSize := (v_CurrentSize - v_TotalGrowth) ; dbms_output.put_line('SNAP_TIME Database Size(GB)'); for row in usageHist loop v_Space := (v_BaselineSize + row.ProgSum)/(1024*1024*1024); dbms_output.put_line(row.SNAP_TIME || ' ' || to_char(v_Space) ); end loop; end; / ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Active Incidents ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT Active Incidents: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ set linesize ${SQLLINESIZE} col RECENT_PROBLEMS_1_WEEK_BACK for a45 select PROBLEM_KEY RECENT_PROBLEMS_1_WEEK_BACK,to_char(FIRSTINC_TIME,'DD-MON-YY HH24:mi:ss') FIRST_OCCURENCE,to_char(LASTINC_TIME,'DD-MON-YY HH24:mi:ss') LAST_OCCURENCE FROM V\$DIAG_PROBLEM WHERE LASTINC_TIME > SYSDATE -10; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT OUTSTANDING ALERTS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT OUTSTANDING ALERTS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^ col CREATION_TIME for a40 col REASON for a80 select REASON,CREATION_TIME,METRIC_VALUE from DBA_OUTSTANDING_ALERTS; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CORRUPTED BLOCKS ${HASHHTML} PROMPT


${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT CORRUPTED BLOCKS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ select * from V\$DATABASE_BLOCK_CORRUPTION; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT BLOCKED SESSIONS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT BLOCKED SESSIONS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ col module for a27 col event for a24 col MACHINE for a27 col "WA_ST|WAITD|ACT_SINC|LOG_T" for a38 col "INST|USER|SID,SERIAL#" for a30 col "INS|USER|SID,SER|MACHIN|MODUL" for a65 col "PREV|CURR SQLID" for a27 col "I|BLKD_BY" for a12 select /*+RULE*/ substr(s.INST_ID||'|'||s.USERNAME||'| '||s.sid||','||s.serial#||' |'||substr(s.MACHINE,1,22)||'|'||substr(s.MODULE,1,18),1,65)"INS|USER|SID,SER|MACHIN|MODUL" ,substr(w.state||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||to_char(LOGON_TIME,'ddMon'),1,38) "WA_ST|WAITD|ACT_SINC|LOG_T" ,substr(w.event,1,24) "EVENT" ,s.FINAL_BLOCKING_INSTANCE||'|'||s.FINAL_BLOCKING_SESSION "I|BLKD_BY" from gv\$session s, gv\$session_wait w where s.USERNAME is not null and s.FINAL_BLOCKING_SESSION is not null and s.sid=w.sid and s.STATUS='ACTIVE' order by "I|BLKD_BY" desc,w.event,"INS|USER|SID,SER|MACHIN|MODUL","WA_ST|WAITD|ACT_SINC|LOG_T" desc; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT UN-USABLE INDEXES ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT UN-USABLE INDEXES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^ PROMPT col REBUILD_UNUSABLE_INDEXES for a190 ${HASHNONHTML} set echo on feedback on pages 1000 ${HASHNONHTML} select 'ALTER INDEX '||OWNER||'.'||INDEX_NAME||' REBUILD ONLINE;' REBUILD_UNUSABLE_INDEXES from dba_indexes where status='UNUSABLE'; ${HASHHTML} select OWNER,INDEX_NAME from dba_indexes where status='UNUSABLE'; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT INVALID OBJECTS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT INVALID OBJECTS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT set pages 0 select 'alter package '||owner||'.'||object_name||' compile;' from dba_objects where status <> 'VALID' and object_type like '%PACKAGE%' union select 'alter type '||owner||'.'||object_name||' compile specification;' from dba_objects where status <> 'VALID' and object_type like '%TYPE%'union select 'alter '||object_type||' '||owner||'.'||object_name||' compile;' from dba_objects where status <> 'VALID' and object_type not in ('PACKAGE','PACKAGE BODY','SYNONYM','TYPE','TYPE BODY') union select 'alter public synonym '||object_name||' compile;' from dba_objects where status <> 'VALID' and object_type ='SYNONYM'; set pages 1000 ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT RMAN BACKUP OPERATIONS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT RMAN BACKUP OPERATIONS: [LAST 24H] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^ col START_TIME for a15 col END_TIME for a15 col TIME_TAKEN_DISPLAY for a10 col INPUT_BYTES_DISPLAY heading "DATA SIZE" for a10 col OUTPUT_BYTES_DISPLAY heading "Backup Size" for a11 col OUTPUT_BYTES_PER_SEC_DISPLAY heading "Speed/s" for a10 col output_device_type heading "Device_TYPE" for a11 SELECT to_char (start_time,'DD-MON-YY HH24:MI') START_TIME, to_char(end_time,'DD-MON-YY HH24:MI') END_TIME, time_taken_display, ${HASHHTML} case when status not in ('COMPLETED','RUNNING') then '' || to_char(status) || '' else to_char(status) end as "status", ${HASHNONHTML} status input_type, output_device_type,input_bytes_display, output_bytes_display, output_bytes_per_sec_display ,COMPRESSION_RATIO FROM v\$rman_backup_job_details WHERE end_time > sysdate -1; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHU}PROMPT

${HASHHTML} ${HASHU}PROMPT REPORT UNRECOVERABLE DATAFILES ${HASHHTML} ${HASHU}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHU}PROMPT ${HASHNONHTML} ${HASHU}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} ${HASHU}PROMPT REPORT UNRECOVERABLE DATAFILES: ${HASHNONHTML} ${HASHU}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHU}spool off --${HASHU}host sed '/Spooling \|Recovery Manager\|RMAN>\|^$/d' ${LOG_DIR}/unrecoverable_DBfiles.log >> ${DB_HEALTHCHK_RPT} ${HASHU}host sed '/Spooling \|Recovery Manager\|RMAN>\|using \|Report \|^$/d' ${LOG_DIR}/unrecoverable_DBfiles.log >> ${DB_HEALTHCHK_RPT} --${HASHU}host ${HASHNOHTMLOS} sed '/Spooling \|Recovery Manager\|RMAN>\|^$/d' ${LOG_DIR}/unrecoverable_DBfiles.log >> ${DB_HEALTHCHK_RPT} --${HASHU}host ${HASHHTMLOS} sed '/Spooling \|Recovery Manager\|RMAN>\|using \|Report \|^$/d' ${LOG_DIR}/unrecoverable_DBfiles.log > ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log --${HASHU}host ${HASHHTMLOS} awk 'BEGIN { print "

"} {print ""; for(i=1;i<=NF;i++)print ""; print ""} END{print "
" $i"
" }' ${LOG_DIR}/unrecoverable_DBfiles_FORMATTED.log > ${LOG_DIR}/unrecoverable_DBfiles_HTML.log --${HASHU}host ${HASHHTMLOS} cat ${LOG_DIR}/unrecoverable_DBfiles_HTML.log >> ${DB_HEALTHCHK_RPT} ${HASHU}spool ${DB_HEALTHCHK_RPT} app ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHJ}PROMPT

${HASHHTML} ${HASHJ}PROMPT SCHEDULED JOBS STATUS ${HASHHTML} ${HASHJ}PROMPT


${HASHHTML} ${HASHJ}PROMPT

${HASHHTML} ${HASHJ}PROMPT DBMS_JOBS ${HASHHTML} ${HASHJ}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHJ}PROMPT ${HASHNONHTML} ${HASHJ}PROMPT ^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} ${HASHJ}PROMPT SCHEDULED JOBS STATUS: ${HASHNONHTML} ${HASHJ}PROMPT ^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} ${HASHJ}PROMPT ${HASHNONHTML} ${HASHJ}PROMPT DBMS_JOBS: ${HASHNONHTML} ${HASHJ}PROMPT ^^^^^^^^^^ ${HASHJ}set linesize ${SQLLINESIZE} ${HASHJ}col LAST_RUN for a25 ${HASHJ}col NEXT_RUN for a25 ${HASHJ}select job,schema_user,failures,to_char(LAST_DATE,'DD-Mon-YYYY hh24:mi:ss')LAST_RUN,to_char(NEXT_DATE,'DD-Mon-YYYY hh24:mi:ss')NEXT_RUN from dba_jobs; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHJ}PROMPT

${HASHHTML} ${HASHJ}PROMPT DBMS_SCHEDULER ${HASHHTML} ${HASHJ}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHJ}PROMPT ${HASHNONHTML} ${HASHJ}PROMPT DBMS_SCHEDULER: ${HASHNONHTML} ${HASHJ}PROMPT ^^^^^^^^^^^^^^^ ${HASHJ}col OWNER for a15 ${HASHJ}col JOB_NAME for a30 ${HASHJ}col STATE for a15 ${HASHJ}col FAILURE_COUNT for 9999 heading 'Fail' ${HASHJ}col "DURATION(d:hh:mm:ss)" for a22 ${HASHJ}col REPEAT_INTERVAL for a70 ${HASHJ}col "LAST_RUN || REPEAT_INTERVAL" for a65 ${HASHJ}col "DURATION(d:hh:mm:ss)" for a12 ${HASHJ}select JOB_NAME,OWNER,ENABLED,STATE, ${HASHJ} ${HASHHTML} case when FAILURE_COUNT > 0 then '' || to_char(FAILURE_COUNT,99999) || '' else to_char(FAILURE_COUNT,99999) end as "FAILURE_COUNT", ${HASHJ} ${HASHNONHTML} FAILURE_COUNT, ${HASHJ}to_char(LAST_START_DATE,'DD-Mon-YYYY hh24:mi:ss')||' || '||REPEAT_INTERVAL "LAST_RUN || REPEAT_INTERVAL", ${HASHJ}extract(day from last_run_duration) ||':'|| ${HASHJ}lpad(extract(hour from last_run_duration),2,'0')||':'|| ${HASHJ}lpad(extract(minute from last_run_duration),2,'0')||':'|| ${HASHJ}lpad(round(extract(second from last_run_duration)),2,'0') "DURATION(d:hh:mm:ss)" ${HASHJ}from dba_scheduler_jobs order by ENABLED,STATE; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHJ}PROMPT

${HASHHTML} ${HASHJ}PROMPT AUTOTASK INTERNAL MAINTENANCE WINDOWS ${HASHHTML} ${HASHJ}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHJ}PROMPT ${HASHNONHTML} ${HASHJ}PROMPT AUTOTASK INTERNAL MAINTENANCE WINDOWS: ${HASHNONHTML} ${HASHJ}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHJ}col WINDOW_NAME for a17 ${HASHJ}col NEXT_RUN for a20 ${HASHJ}col ACTIVE for a6 ${HASHJ}col OPTIMIZER_STATS for a15 ${HASHJ}col SEGMENT_ADVISOR for a15 ${HASHJ}col SQL_TUNE_ADVISOR for a16 ${HASHJ}SELECT WINDOW_NAME,TO_CHAR(WINDOW_NEXT_TIME,'DD-MM-YYYY HH24:MI:SS') NEXT_RUN,AUTOTASK_STATUS STATUS,WINDOW_ACTIVE ACTIVE,OPTIMIZER_STATS,SEGMENT_ADVISOR,SQL_TUNE_ADVISOR FROM DBA_AUTOTASK_WINDOW_CLIENTS; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHJ}PROMPT

${HASHHTML} ${HASHJ}PROMPT Current Running Jobs ${HASHHTML} ${HASHJ}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHJ}PROMPT ${HASHNONHTML} ${HASHJ}PROMPT Current Running Jobs: ${HASHNONHTML} ${HASHJ}PROMPT ^^^^^^^^^^^^^^^^^^^^ ${HASHJ}col INS for 999 ${HASHJ}col "JOB_NAME|OWNER|SPID|SID" for a55 ${HASHJ}col ELAPSED_TIME for a17 ${HASHJ}col CPU_USED for a17 ${HASHJ}col "WAIT_SEC" for 9999999999 ${HASHJ}col WAIT_CLASS for a15 ${HASHJ}col "BLKD_BY" for 9999999 ${HASHJ}col "WAITED|WCLASS|EVENT" for a45 ${HASHJ}select j.RUNNING_INSTANCE INS,j.JOB_NAME ||' | '|| j.OWNER||' |'||SLAVE_OS_PROCESS_ID||'|'||j.SESSION_ID"JOB_NAME|OWNER|SPID|SID" ${HASHJ},s.FINAL_BLOCKING_SESSION "BLKD_BY",ELAPSED_TIME,CPU_USED ${HASHJ},substr(s.SECONDS_IN_WAIT||'|'||s.WAIT_CLASS||'|'||s.EVENT,1,45) "WAITED|WCLASS|EVENT",S.SQL_ID ${HASHJ}from dba_scheduler_running_jobs j, gv\$session s ${HASHJ}where j.RUNNING_INSTANCE=S.INST_ID(+) ${HASHJ}and j.SESSION_ID=S.SID(+) ${HASHJ}order by "JOB_NAME|OWNER|SPID|SID",ELAPSED_TIME; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHJ}PROMPT

${HASHHTML} ${HASHJ}PROMPT FAILED DBMS_SCHEDULER JOBS IN THE LAST 24H ${HASHHTML} ${HASHJ}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHJ}PROMPT ${HASHNONHTML} ${HASHJ}PROMPT FAILED DBMS_SCHEDULER JOBS IN THE LAST 24H: ${HASHNONHTML} ${HASHJ}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHJ}col LOG_DATE for a36 ${HASHJ}col OWNER for a15 ${HASHJ}col JOB_NAME for a35 ${HASHJ}col STATUS for a11 ${HASHJ}col RUN_DURATION for a20 ${HASHJ}col ID for 99 ${HASHJ}select INSTANCE_ID ID,JOB_NAME,OWNER,LOG_DATE,STATUS,ERROR#,RUN_DURATION from DBA_SCHEDULER_JOB_RUN_DETAILS where LOG_DATE > sysdate-1 and STATUS='FAILED' order by JOB_NAME,LOG_DATE; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Queries Running For More Than [${LONG_RUN_QUR_HOURS}] Hours ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT Queries Running For More Than [${LONG_RUN_QUR_HOURS}] Hour: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ col module for a30 col DURATION_HOURS for 99999.9 col STARTED_AT for a13 col "USERNAME| SID,SERIAL#" for a30 ${HASHNONHTML} col "SQL_ID | SQL_TEXT" for a120 select username||'| '||sid ||','|| serial# "USERNAME| SID,SERIAL#",substr(MODULE,1,30) "MODULE", to_char(sysdate-last_call_et/24/60/60,'DD-MON HH24:MI') STARTED_AT, last_call_et/60/60 "DURATION_HOURS" --||' | '|| (select SQL_FULLTEXT from v\$sql where address=sql_address) "SQL_ID | SQL_TEXT" ,SQL_ID from v\$session where username is not null and module is not null and module not in (${EXCLUDED_MODULES}) and last_call_et > 60*60*${LONG_RUN_QUR_HOURS} and status = 'ACTIVE'; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHSTA}PROMPT

${HASHHTML} ${HASHSTA}PROMPT ADVISORS STATUS ${HASHHTML} ${HASHSTA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT ADVISORS STATUS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^ col ADVISOR_NAME for a60 col STATUS for a15 ${HASHSTA}SELECT client_name ADVISOR_NAME, status FROM dba_autotask_client ORDER BY client_name; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHSTA}PROMPT

${HASHHTML} ${HASHSTA}PROMPT SQL TUNING ADVISOR ${HASHHTML} ${HASHSTA}PROMPT


${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHSTA}PROMPT ${HASHNONHTML} ${HASHSTA}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} ${HASHSTA}PROMPT SQL TUNING ADVISOR: ${HASHNONHTML} ${HASHSTA}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHSTA}PROMPT

${HASHHTML} ${HASHSTA}PROMPT Last Execution of SQL TUNING ADVISOR ${HASHHTML} ${HASHSTA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHSTA}PROMPT ${HASHNONHTML} ${HASHSTA}PROMPT Last Execution of SQL TUNING ADVISOR: ${HASHNONHTML} ${HASHSTA}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHSTA}col TASK_NAME for a60 ${HASHSTA}set long 2000000000 ${HASHSTA}SELECT task_name, status, TO_CHAR(execution_end,'DD-MON-YY HH24:MI') Last_Execution FROM dba_advisor_executions where TASK_NAME='SYS_AUTO_SQL_TUNING_TASK' and execution_end>sysdate-1; ${HASHSTA}variable Findings_Report CLOB; ${HASHSTA} BEGIN ${HASHSTA} :Findings_Report :=DBMS_SQLTUNE.REPORT_AUTO_TUNING_TASK( ${HASHSTA} begin_exec => NULL, ${HASHSTA} end_exec => NULL, ${HASHSTA} type => 'TEXT', ${HASHSTA} level => 'TYPICAL', ${HASHSTA} section => 'ALL', ${HASHSTA} object_id => NULL, ${HASHSTA} result_limit => NULL); ${HASHSTA} END; ${HASHSTA} / ${HASHSTA} print :Findings_Report ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHMA}PROMPT

${HASHHTML} ${HASHMA}PROMPT MEMORY ADVISORS ${HASHHTML} ${HASHMA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT ORACLE MEMORY UTILIZATION: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT ORACLE MEMORY UTILIZATION ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 col inst_id heading ins for 999 col COMPONENT for a35 col CURRENT_SIZE_MB for 99999999999 col MAX_SIZE_MB for 99999999999 select INST_ID,COMPONENT,USER_SPECIFIED_SIZE/1024/1024 USER_SPECIFIED_SIZE_MB,CURRENT_SIZE/1024/1024 CURRENT_SIZE_MB,MAX_SIZE/1024/1024 MAX_SIZE_MB from gv\$memory_dynamic_components where COMPONENT not like '%K buffer%' and COMPONENT not in ('ASM Buffer Cache','KEEP buffer cache','RECYCLE buffer cache','unified pga pool','Data Transfer Cache') order by COMPONENT,INST_ID; ${HASHNONHTML} ${HASHMA}PROMPT ${HASHNONHTML} ${HASHMA}PROMPT ${HASHNONHTML} ${HASHMA}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} ${HASHMA}PROMPT MEMORY ADVISORS: ${HASHNONHTML} ${HASHMA}PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHMA}PROMPT

${HASHHTML} ${HASHMA}PROMPT SGA ADVISOR ${HASHHTML} ${HASHMA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHMA}PROMPT ${HASHNONHTML} ${HASHMA}PROMPT SGA ADVISOR: ${HASHNONHTML} ${HASHMA}PROMPT ^^^^^^^^^^^^ ${HASHMA}col ESTD_DB_TIME for 99999999999999999 ${HASHMA}col ESTD_DB_TIME_FACTOR for 9999999999999999999999999999 ${HASHMA}select * from V\$SGA_TARGET_ADVICE where SGA_SIZE_FACTOR > .6 and SGA_SIZE_FACTOR < 1.6; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHMA}PROMPT

${HASHHTML} ${HASHMA}PROMPT Buffer Cache ADVISOR ${HASHHTML} ${HASHMA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHMA}PROMPT ${HASHNONHTML} ${HASHMA}PROMPT Buffer Cache ADVISOR: ${HASHNONHTML} ${HASHMA}PROMPT ^^^^^^^^^^^^^^^^^^^^^ ${HASHMA}col ESTD_SIZE_MB for 9999999999999 ${HASHMA}col ESTD_PHYSICAL_READS for 99999999999999999999 ${HASHMA}col ESTD_PHYSICAL_READ_TIME for 99999999999999999999 ${HASHMA}select SIZE_FACTOR "%SIZE",SIZE_FOR_ESTIMATE ESTD_SIZE_MB,ESTD_PHYSICAL_READS,ESTD_PHYSICAL_READ_TIME,ESTD_PCT_OF_DB_TIME_FOR_READS ${HASHMA}from V\$DB_CACHE_ADVICE where SIZE_FACTOR >.8 and SIZE_FACTOR<1.3; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHMA}PROMPT

${HASHHTML} ${HASHMA}PROMPT Shared Pool ADVISOR ${HASHHTML} ${HASHMA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHMA}PROMPT ${HASHNONHTML} ${HASHMA}PROMPT Shared Pool ADVISOR: ${HASHNONHTML} ${HASHMA}PROMPT ^^^^^^^^^^^^^^^^^^^^ ${HASHMA}col SIZE_MB for 99999999999 ${HASHMA}col SIZE_FACTOR for 99999999 ${HASHMA}col ESTD_SIZE_MB for 99999999999999999999 ${HASHMA}col LIB_CACHE_SAVED_TIME for 99999999999999999999999999 ${HASHMA}select SHARED_POOL_SIZE_FOR_ESTIMATE SIZE_MB,SHARED_POOL_SIZE_FACTOR "%SIZE",SHARED_POOL_SIZE_FOR_ESTIMATE/1024/1024 ESTD_SIZE_MB,ESTD_LC_TIME_SAVED LIB_CACHE_SAVED_TIME, ${HASHMA}ESTD_LC_LOAD_TIME PARSING_TIME from V\$SHARED_POOL_ADVICE ${HASHMA}where SHARED_POOL_SIZE_FACTOR > .9 and SHARED_POOL_SIZE_FACTOR < 1.6; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHMA}PROMPT

${HASHHTML} ${HASHMA}PROMPT PGA ADVISOR ${HASHHTML} ${HASHMA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHMA}PROMPT ${HASHNONHTML} ${HASHMA}PROMPT PGA ADVISOR: ${HASHNONHTML} ${HASHMA}PROMPT ^^^^^^^^^^^^ ${HASHMA}col SIZE_FACTOR for 999999999 ${HASHMA}col ESTD_SIZE_MB for 99999999999999999999 ${HASHMA}col MB_PROCESSED for 99999999999999999999 ${HASHMA}col ESTD_TIME for 99999999999999999999 ${HASHMA}select PGA_TARGET_FACTOR "%SIZE",PGA_TARGET_FOR_ESTIMATE/1024/1024 ESTD_SIZE_MB,BYTES_PROCESSED/1024/1024 MB_PROCESSED, ${HASHMA}ESTD_TIME,ESTD_PGA_CACHE_HIT_PERCENTAGE PGA_HIT,ESTD_OVERALLOC_COUNT PGA_SHORTAGE ${HASHMA}from V\$PGA_TARGET_ADVICE where PGA_TARGET_FACTOR > .7 and PGA_TARGET_FACTOR < 1.6; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHSA}PROMPT

${HASHHTML} ${HASHSA}PROMPT SEGMENT ADVISOR ${HASHHTML} ${HASHSA}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHSA}PROMPT ${HASHNONHTML} ${HASHSA}PROMPT SEGMENT ADVISOR: ${HASHNONHTML} ${HASHSA}PROMPT ^^^^^^^^^^^^^^^^ ${HASHSA}select'Task Name : ' || f.task_name || chr(10) || ${HASHSA}'Start Run Time : ' || TO_CHAR(execution_start, 'dd-mon-yy hh24:mi') || chr (10) || ${HASHSA}'Segment Name : ' || o.attr2 || chr(10) || ${HASHSA}'Segment Type : ' || o.type || chr(10) || ${HASHSA}'Partition Name : ' || o.attr3 || chr(10) || ${HASHSA}'Message : ' || f.message || chr(10) || ${HASHSA}'More Info : ' || f.more_info || chr(10) || ${HASHSA}'-------------------------------------------' Advice ${HASHSA}FROM dba_advisor_findings f ${HASHSA},dba_advisor_objects o ${HASHSA},dba_advisor_executions e ${HASHSA}WHERE o.task_id = f.task_id ${HASHSA}AND o.object_id = f.object_id ${HASHSA}AND f.task_id = e.task_id ${HASHSA}AND e. execution_start > sysdate - 1 ${HASHSA}AND e.advisor_name = 'Segment Advisor' ${HASHSA}ORDER BY f.task_name; ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT TOP FRAGMENTED TABLES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^ ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT TOP FRAGMENTED TABLES ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 col "%RECLAIMABLE_SPACE" for 99 col owner for a30 col "%FRAGMENTED_SPACE" for a17 col LAST_ANALYZED for a13 select * from (select owner,table_name,to_char(LAST_ANALYZED, 'DD-MON-YYYY') LAST_ANALYZED, round(blocks * ${blksize}/1024/1024) "FULL_SIZE_MB", round(num_rows * avg_row_len/1024/1024) "ACTUAL_SIZE_MB", round(blocks * ${blksize}/1024/1024) - round(num_rows * avg_row_len/1024/1024) "FRAGMENTED_SPACE_MB", round(((round((blocks * ${blksize}/1024/1024)) - round((num_rows * avg_row_len/1024/1024))) / round((blocks * ${blksize}/1024/1024))) * 100)||'%' "%FRAGMENTED_SPACE" from dba_tables where blocks>10 -- Exclude SYS objects: and owner <> 'SYS' and round(blocks * ${blksize}/1024/1024) > 10 -- Fragmented Space must be > 30%: and ((round((blocks * ${blksize}/1024/1024)) - round((num_rows * avg_row_len/1024/1024))) / round((blocks * ${blksize}/1024/1024))) * 100 > 30 order by "FRAGMENTED_SPACE_MB" desc) where rownum<11; PROMPT Hint: The accuracy of the FRAGMENTED TABLES list depends on having a recent STATISTICS. ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT CURRENT OS / HARDWARE STATISTICS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT CURRENT OS / HARDWARE STATISTICS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ select stat_name,value from v\$osstat; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT RESOURCE LIMIT ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT RESOURCE LIMIT: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^ col INITIAL_ALLOCATION for a20 col LIMIT_VALUE for a20 select * from gv\$resource_limit order by RESOURCE_NAME; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT RECYCLEBIN OBJECTS# ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT RECYCLEBIN OBJECTS#: [Purging DBA_RECYCLEBIN can boost the performance of X$ tables] ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^ col "RECYCLED_OBJECTS#" for 999999999999999999 col "TOTAL_SIZE_MB" for 99999999999999 set feedback off select ${HASHHTML} case when count(*) > 1000 then '' || to_char(count(*)) || '' else to_char(count(*)) end as "RECYCLED_OBJECTS#", ${HASHNONHTML} count(*) "RECYCLED_OBJECTS#", ${HASHHTML} case when sum(space)*${blksize}/1024/1024 > 1024 then '' || to_char(sum(space)*${blksize}/1024/1024) || '' else to_char(sum(space)*${blksize}/1024/1024) end as "TOTAL_SIZE_MB" ${HASHNONHTML} sum(space)*${blksize}/1024/1024 "TOTAL_SIZE_MB" from dba_recyclebin group by 1; set feedback on ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT FLASHBACK RESTORE POINTS ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT FLASHBACK RESTORE POINTS: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^ col SCN for 999999999999999999 col time for a35 col RESTORE_POINT_TIME for a35 col name for a40 select NAME,SCN,TIME,STORAGE_SIZE/1024/1024/1024 STORAGE_SIZE_GB from v\$restore_point; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT HEALTH MONITOR ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT HEALTH MONITOR: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^ col DESCRIPTION for a80 col repair_script for a80 select name,type,status,description,repair_script from V\$HM_RECOMMENDATION where time_detected > sysdate -1; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Monitored INDEXES ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT Monitored INDEXES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^ set linesize ${SQLLINESIZE} pages 1000 col Index_NAME for a40 col TABLE_NAME for a40 select io.name Index_NAME, t.name TABLE_NAME,decode(bitand(i.flags, 65536),0,'NO','YES') Monitoring, decode(bitand(ou.flags, 1),0,'NO','YES') USED,ou.start_monitoring,ou.end_monitoring from sys.obj$ io,sys.obj$ t,sys.ind$ i,sys.object_usage ou where i.obj# = ou.obj# and io.obj# = ou.obj# and t.obj# = i.bo#; --PROMPT --PROMPT To stop monitoring USED indexes use this command: --prompt select 'ALTER INDEX RA.'||io.name||' NOMONITORING USAGE;' from sys.obj$ io,sys.obj$ t,sys.ind$ i,sys.object_usage ou where i.obj# = ou.obj# and io.obj# = ou.obj# and t.obj# = i.bo# --prompt and decode(bitand(i.flags, 65536),0,'NO','YES')='YES' and decode(bitand(ou.flags, 1),0,'NO','YES')='YES' order by 1 --prompt / ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT REDO LOG SWITCHES ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT REDO LOG SWITCHES: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^ set linesize ${SQLLINESIZE} col day for a11 SELECT to_char(first_time,'YYYY-MON-DD') day, to_char(sum(decode(to_char(first_time,'HH24'),'00',1,0)),'9999') "00", to_char(sum(decode(to_char(first_time,'HH24'),'01',1,0)),'9999') "01", to_char(sum(decode(to_char(first_time,'HH24'),'02',1,0)),'9999') "02", to_char(sum(decode(to_char(first_time,'HH24'),'03',1,0)),'9999') "03", to_char(sum(decode(to_char(first_time,'HH24'),'04',1,0)),'9999') "04", to_char(sum(decode(to_char(first_time,'HH24'),'05',1,0)),'9999') "05", to_char(sum(decode(to_char(first_time,'HH24'),'06',1,0)),'9999') "06", to_char(sum(decode(to_char(first_time,'HH24'),'07',1,0)),'9999') "07", to_char(sum(decode(to_char(first_time,'HH24'),'08',1,0)),'9999') "08", to_char(sum(decode(to_char(first_time,'HH24'),'09',1,0)),'9999') "09", to_char(sum(decode(to_char(first_time,'HH24'),'10',1,0)),'9999') "10", to_char(sum(decode(to_char(first_time,'HH24'),'11',1,0)),'9999') "11", to_char(sum(decode(to_char(first_time,'HH24'),'12',1,0)),'9999') "12", to_char(sum(decode(to_char(first_time,'HH24'),'13',1,0)),'9999') "13", to_char(sum(decode(to_char(first_time,'HH24'),'14',1,0)),'9999') "14", to_char(sum(decode(to_char(first_time,'HH24'),'15',1,0)),'9999') "15", to_char(sum(decode(to_char(first_time,'HH24'),'16',1,0)),'9999') "16", to_char(sum(decode(to_char(first_time,'HH24'),'17',1,0)),'9999') "17", to_char(sum(decode(to_char(first_time,'HH24'),'18',1,0)),'9999') "18", to_char(sum(decode(to_char(first_time,'HH24'),'19',1,0)),'9999') "19", to_char(sum(decode(to_char(first_time,'HH24'),'20',1,0)),'9999') "20", to_char(sum(decode(to_char(first_time,'HH24'),'21',1,0)),'9999') "21", to_char(sum(decode(to_char(first_time,'HH24'),'22',1,0)),'9999') "22", to_char(sum(decode(to_char(first_time,'HH24'),'23',1,0)),'9999') "23" from v\$log_history where first_time > sysdate-1 GROUP by to_char(first_time,'YYYY-MON-DD') order by 1 asc; ${HASHHTML} PROMPT
${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Modified Parameters Since The Instance Startup ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} PROMPT ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} PROMPT Modified Parameters Since The Instance Startup: ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ col name for a45 col VALUE for a80 col DEPRECATED for a10 select NAME,VALUE,ISDEFAULT "DEFAULT",ISDEPRECATED "DEPRECATED" from v\$parameter where ISMODIFIED = 'SYSTEM_MOD' order by 1; ${HASHHTML} PROMPT
${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} ${HASHCRD}PROMPT

${HASHHTML} ${HASHCRD}PROMPT Cred Backup ${HASHHTML} ${HASHCRD}PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} ${HASHCRD}PROMPT ${HASHNONHTML} ${HASHCRD}PROMPT ^^^^^^^^^^^^ ${HASHNONHTML} ${HASHCRD}PROMPT Cred Backup: ${HASHNONHTML} ${HASHCRD}PROMPT ^^^^^^^^^^^^ ${HASHCRD}col name for a35 ${HASHCRD}col HASH for a35 ${HASHCRD}col CREATION_DATE for a20 ${HASHCRD}col PASSWORD_LAST_CHANGED for a30 ${HASHCRD}col "CREATE_DATE||PASS_LAST_CHANGE" for a60 ${HASHNONHTML} ${HASHCRD}select name,PASSWORD HASH,CTIME ||' || '||PTIME "CREATE_DATE||PASS_LAST_CHANGE" from user\$ where PASSWORD is not null order by 1; ${HASHHTML} ${HASHCRD}select name,PASSWORD HASH,CTIME "CREATION_DATE",PTIME "PASSWORD_LAST_CHANGED" from user\$ where PASSWORD is not null order by 1; spool off exit; EOF ) fi # ################################################# # Reporting New Created Objects in the last 24Hours: # ################################################# NEWOBJCONTRAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off echo off; select count(*) from dba_objects where created > sysdate-1 and owner <> 'SYS'; exit; EOF ) NEWOBJCONT=`echo ${NEWOBJCONTRAW} | awk '{print $NF}'` if [ ${NEWOBJCONT} -ge ${NEWOBJCONTTHRESHOLD} ] then VALNEWOBJCONT=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} pages 1000 -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF spool ${DB_HEALTHCHK_RPT} app ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT New Created objects [Last 24H] ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt New Created objects [Last 24H] ... ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt col owner for a30 col object_name for a30 col object_type for a19 col created for a20 select object_type,owner,object_name,to_char(created, 'DD-Mon-YYYY HH24:MI:SS') CREATED from dba_objects where created > sysdate-1 and owner <> 'SYS' order by owner,object_type; spool off exit; EOF ) fi # ############################################### # Reporting Modified Objects in the last 24Hours: # ############################################### MODOBJCONTRAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off echo off; select count(*) from dba_objects where LAST_DDL_TIME > sysdate-1 and owner <> 'SYS'; exit; EOF ) MODOBJCONT=`echo ${MODOBJCONTRAW} | awk '{print $NF}'` if [ ${MODOBJCONT} -ge ${MODOBJCONTTHRESHOLD} ] then VALMODOBJCONT=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} pages 1000 -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF spool ${DB_HEALTHCHK_RPT} app ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Modified objects in the Last 24H ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt Modified objects in the Last 24H ... ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt col owner for a30 col object_name for a30 col object_type for a19 col LAST_DDL_TIME for a20 select object_type,owner,object_name,to_char(LAST_DDL_TIME, 'DD-Mon-YYYY HH24:MI:SS') LAST_DDL_TIME from dba_objects where LAST_DDL_TIME > sysdate-1 and owner <> 'SYS' order by owner,object_type; spool off exit; EOF ) fi # ############################################### # Checking AUDIT RECORDS ON THE DATABASE: # ############################################### # Check if Checking Audit Records is ENABLED: case ${CHKAUDITRECORDS} in Y|y|YES|Yes|yes|ON|On|on) VAL70=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set pages 0 feedback off echo off; SELECT (SELECT COUNT(*) FROM dba_audit_trail where ACTION_NAME not like 'LOGO%' and ACTION_NAME not in ('SELECT','SET ROLE') and timestamp > SYSDATE-1) + (SELECT COUNT(*) FROM DBA_AUDIT_SESSION WHERE timestamp > SYSDATE-1 and returncode = 1017) + (SELECT COUNT(*) FROM dba_fga_audit_trail WHERE timestamp > SYSDATE-1) + (SELECT COUNT(*) FROM dba_objects where created > sysdate-1 and owner <> 'SYS') AUD_REC_COUNT FROM dual; exit; EOF ) VAL80=`echo ${VAL70} | awk '{print $NF}'` if [ ${VAL80} -ge ${AUDITRECOTHRESHOLD} ] then VAL90=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" << EOF set linesize ${SQLLINESIZE} pages 1000 -- Enable HTML color format: ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF spool ${LOG_DIR}/audit_records.log SET TIMING ON col OS_USERNAME for a20 col EXTENDED_TIMESTAMP for a36 col OWNER for a25 col OBJ_NAME for a25 col OS_USERNAME for a20 col USERNAME for a25 col USERHOST for a35 col ACTION_NAME for a25 col ACTION_OWNER_OBJECT for a55 col TERMINAL for a30 col ACTION_NAME for a20 col TIMESTAMP for a21 ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Failed Login Attempts in the last 24Hours ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} prompt ${HASHNONHTML} prompt ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt Failed Login Attempts in the last 24Hours ... ${HASHNONHTML} prompt ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt select to_char (EXTENDED_TIMESTAMP,'DD-MON-YYYY HH24:MI:SS') TIMESTAMP,OS_USERNAME,USERNAME,TERMINAL,USERHOST,ACTION_NAME from DBA_AUDIT_SESSION where timestamp > (sysdate -1) and returncode = 1017 order by 1; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Audit records in the last 24Hours AUD$ ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} prompt ${HASHNONHTML} prompt ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt Audit records in the last 24Hours AUD$... ${HASHNONHTML} prompt ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt select extended_timestamp,OS_USERNAME,USERNAME,USERHOST,ACTION_NAME||' '||OWNER||' . '||OBJ_NAME ACTION_OWNER_OBJECT from dba_audit_trail where timestamp > SYSDATE-1 and ACTION_NAME not like 'LOGO%' and ACTION_NAME not in ('SELECT','SET ROLE') -- and USERNAME not in ('CRS_ADMIN','DBSNMP') -- and OS_USERNAME not in ('workflow') -- and OBJ_NAME not like '%TMP_%' -- and OBJ_NAME not like 'WRKDETA%' -- and OBJ_NAME not in ('PBCATTBL','SETUP','WRKIB','REMWORK') order by EXTENDED_TIMESTAMP; ${HASHHTML} SET PAGES 0 ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHHTML} PROMPT

${HASHHTML} PROMPT Fine Grained Auditing Data ${HASHHTML} PROMPT


${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHHTML} set pages 1000 ${HASHNONHTML} prompt ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt Fine Grained Auditing Data ... ${HASHNONHTML} PROMPT ^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHNONHTML} prompt col sql_text for a70 col time for a36 col USERHOST for a21 col db_user for a15 select to_char(timestamp,'DD-MM-YYYY HH24:MI:SS') as time,db_user,userhost,sql_text,SQL_BIND from dba_fga_audit_trail where timestamp > SYSDATE-1 -- and policy_name='PAYROLL_TABLE' order by EXTENDED_TIMESTAMP; ${HASHDORM} ${HASHHTML} SET PAGES 0 ${HASHDORM} ${HASHHTML} SET MARKUP HTML OFF SPOOL OFF ${HASHDORM} ${HASHHTML} PROMPT

${HASHDORM} ${HASHHTML} PROMPT Dormant Accounts: [Accounts that did not login in the last ${DORMANT_INACTIVE_DAYS} days] ${HASHDORM} ${HASHHTML} PROMPT


${HASHDORM} ${HASHHTML} SET WRAP OFF ECHO OFF FEEDBACK OFF MARKUP HTML ON SPOOL ON HEAD ' ' TABLE "border='2' bordercolor='#E67E22'" ENTMAP OFF ${HASHDORM} ${HASHHTML} set pages 1000 ${HASHDORM} ${HASHNONHTML} prompt ${HASHDORM} ${HASHNONHTML} prompt ${HASHDORM} ${HASHNONHTML} prompt ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHDORM} ${HASHNONHTML} prompt Dormant Accounts: [Accounts that did not login in the last ${DORMANT_INACTIVE_DAYS} days] ... ${HASHDORM} ${HASHNONHTML} prompt ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ${HASHDORM} ${HASHNONHTML} prompt ${HASHDORM} select userid,max(ntimestamp#) LAST_LOGIN_DATE from aud$ where ntimestamp# < (sysdate - ${DORMANT_INACTIVE_DAYS}) group by userid order by LAST_LOGIN_DATE; spool off exit; EOF ) cat ${LOG_DIR}/audit_records.log >> ${DB_HEALTHCHK_RPT} fi ;; esac # Remove odd lines from the report: sed -i 's/^rows will be truncated//g' ${DB_HEALTHCHK_RPT} export LOGFILE=${DB_HEALTHCHK_RPT} export MSGSUBJECT="HEALTH CHECK REPORT: For Database [${DB_NAME_UPPER}] on Server [${SRV_NAME}]" echo ${MSGSUBJECT} ${MAILEXEC} "${MSGSUBJECT}" ${MAIL_LIST} < ${LOGFILE} ( echo "To: ${EMAIL};" echo "MIME-Version: 1.0" echo "Content-Type: text/html;" echo "Subject: ${MSGSUBJECT}" cat ${LOGFILE} ) | ${SENDMAIL} echo "HEALTH CHECK REPORT FOR DATABASE [${DB_NAME_UPPER}] WAS SAVED TO: ${DB_HEALTHCHK_RPT}" done echo "" # ############################# # De-Neutralize login.sql file: [Bug Fix] # ############################# # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ${USR_ORA_HOME}/login.sql_NeutralizedBy${SCRIPT_NAME} ${USR_ORA_HOME}/login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/datafiles.sh 0000740 0152073 0152061 00000015217 13775601525 014754 0 ustar oracle oinstall ################################################### # Script to show the size of all datafile. # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-12-11 # # # # # # # # ################################################### ############# # Description: ############# echo echo "===================================================" echo "This script Shows the DATAFILES Size on a database." echo "===================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. ############################# # Listing Available Databases: ############################# # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib ########################################## # Exit if the user is not the Oracle Owner: ########################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi ####################### # Checking Datafiles: ####################### $ORACLE_HOME/bin/sqlplus -S '/ as sysdba' <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/lock_user.sh 0000740 0152073 0152061 00000020020 13775601710 014766 0 ustar oracle oinstall # ################################################# # Script to unlock locked users # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-12-11 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # 16-09-14 Removed User Confirmation. # # # ################################################# SCRIPT_NAME="lock_user" # ########### # Description: # ########### echo echo "=================================" echo "This script LOCKS database users." echo "=================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|grep -v ASM|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|grep -v ASM|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|grep -v ASM|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ############################# # SQLPLUS: Lock An Oracle User: # ############################# # Variables echo echo "Please enter the USERID:" echo "=======================" while read USERNAME2 do VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('$USERNAME2'); EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` case ${VAL22} in # If the provided value match an exist username in the DB: 1) ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT USERNAME,ACCOUNT_STATUS FROM DBA_USERS WHERE USERNAME=upper('$USERNAME2'); PROMPT PROMPT Locking user [${USERNAME2}] ... PROMPT EOF VAL1=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF ALTER user $USERNAME2 ACCOUNT LOCK; EOF ) VAL2=`echo $VAL1| grep "User altered"` if [ -z "${VAL2}" ] then echo "Failed to lock User \"${USERNAME2}\" !" echo exit else echo echo User ${USERNAME2} locked Successfully. echo fi; break;; # If no value provided or the value doesn't match any user in the DB try to search for matching: *) echo; echo "INFO: USER [${USERNAME2}] IS NOT EXIST ON DATABASE [$ORACLE_SID] !" echo; echo "Searching ..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set linesize 143 set pagesize 1000 set feedback off set trim on set echo off col USERNAME for a30 col account_status for a23 select username,account_status,profile,LOCK_DATE,EXPIRY_DATE from dba_users where username like upper ('%$USERNAME2%'); EOF echo; echo "Please Enter the FULL USERID:" echo "=============================" ;; esac done # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/kill_long_running_queries.sh 0000740 0152073 0152061 00000025233 13775602246 020267 0 ustar oracle oinstall # ####################################################################### # Kill queries running for more than N hours based on specific criteria. # ####################################################################### VER="[1.0]" # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 11-01-18 # # # # # # # # # # ####################################################################### # ##################### # Environment Variables: [ORACLE_SID must be set by the user in case multiple instances running] # ##################### export ORACLE_SID= export SCRIPT_NAME="kill_long_running_queries" export SRV_NAME=`uname -n` #export LNXVER=`cat /etc/redhat-release | grep -o '[0-9]'|head -1` export LOGFILE=/tmp/${SCRIPT_NAME}.log export TERMINATOR_SCRIPT=/tmp/KILL_LONG_QUERIES.sql # Email Recipients: # ################ MAIL_LIST="youremail@yourcompany.com" export MAIL_LIST # ####################################### # SCRIPT OPTIONS: # ####################################### # ################# # KILLING Criteria: # ################# # Module Name: [Put "," between each module name and keep each module name between single quote] # e.g. export MODULE_NAME="'SQL Developer','Toad'" export MODULE_NAME="'SQL Developer'" # Duration [In hours and its fraction] when exceeded the query will get killed: # e.g. To kill the queries that exceed 3 hours and 30 minutes export DURATION="3.5" export DURATION="2.5" # Report Only Semaphore: [The script will NOT KILL any query if it set to Y but will report them to the user] # Y to report long sessions by email without killing them. # N to Kill long sessions and report them after killing to the user. [Default] export REPORT_ONLY="N" case ${REPORT_ONLY} in Y|y|yes|Yes|YES) export HASH_SCRIPT="--";export REPORT_ONLY_MESSAGE="PROMPT REPORT_ONLY Semaphore is set to Y, No Killing will happen";; *) export HASH_SCRIPT="";export REPORT_ONLY_MESSAGE="";; esac # #################################################################### # Check if ORACLE_SID & MAIL_LIST variables is already set by the user: # #################################################################### export EXL_DB="\-MGMTDB|ASM|APX" # Instances to not be considered when running the script INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) case ${ORACLE_SID} in "") # Exit if No DBs are running: if [ ${INS_COUNT} -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB make it the default ORACLE_SID: if [ ${INS_COUNT} -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to set the ORACLE_SID manually: elif [ ${INS_COUNT} -gt 1 ] then echo echo echo "*****" echo "ERROR! You have to manually set ORACLE_SID to one of the following instances in the 'Environment Variables' Section!" echo "*****" ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" echo echo "Script Terminated !" echo exit fi ;; esac # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ########### # SCRIPT BODY: # ########### # Script Description: echo "" echo "This Script Kills the sessions running a query for more than ${DURATION} hours and connecting from ${MODULE_NAME} ..." sleep 1 # Flush the logfile: cat /dev/null > ${LOGFILE} # CHECKING RUNNING SESSIONS: SESSIONS_COUNT_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 60*60*${DURATION} and status = 'ACTIVE' ; exit; EOF ) SESSIONS_COUNT=`echo ${SESSIONS_COUNT_RAW}|perl -lpe'$_ = reverse' |awk '{print $1}'|perl -lpe'$_ = reverse'|cut -f1 -d '.'` # KILLING LONG RUNNING SESSIONS IF EXIST: # ###################################### if [ ${SESSIONS_COUNT} -gt 0 ] then echo "Found ${SESSIONS_COUNT} Candidate sessions to be killed!" KILL_SESSION_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 60*60*${DURATION} and status = 'ACTIVE' ; spool off -- Kill SQL Script creation: set pages 0 feedback off echo off spool ${TERMINATOR_SCRIPT} select 'ALTER SYSTEM DISCONNECT SESSION '''||sid||','||serial#||''' IMMEDIATE;' from V\$SESSION where MODULE in (${MODULE_NAME}) and last_call_et > 60*60*${DURATION} and status = 'ACTIVE' ; spool off -- Run the Terminator Script to kill the sessions: set pages 1000 feedback on echo on spool ${LOGFILE} APPEND PROMPT PROMPT Running The Terminator Script: PROMPT ***************************** ${REPORT_ONLY_MESSAGE} ${HASH_SCRIPT}START ${TERMINATOR_SCRIPT} spool off exit; EOF ) sleep 10 CURRENT_LONG_SESS_RAW=$(${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < 60*60*${DURATION} and status = 'ACTIVE' ; spool off exit; EOF ) # EMAIL Notification with the killed session: case ${MAIL_LIST} in "youremail@yourcompany.com");; *) /bin/mail -s "Info: Long Running QUERY KILLED on [${ORACLE_SID}]" ${MAIL_LIST} < ${LOGFILE};; esac else echo "" echo "Hooray! No Candidate Sessions were found based on the Killing Criteria." echo "" fi # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". DBA_BUNDLE6/.HA_SERVICES_STATUS.sh 0000740 0152073 0152061 00000000736 14115055307 015762 0 ustar oracle oinstall /u01/app/grid/product/12.2.0/grid/bin/crsctl status res |grep -v "^$"|awk -F "=" 'BEGIN {print " "} {printf("%s",NR%4 ? $2"|" : $2"\n")}'|sed -e 's/ *, /,/g' -e 's/, /,/g'|awk -F "|" 'BEGIN { printf "%-50s%-50s\n","Resource Name","STATUS";printf "%-50s%-50s\n", "-------------------------------------","----------------------"; }{ split ($3,trg,",") split ($4,st,",")}{for (i in trg) {printf "%-50s%-50s\n",$1,st[i]}}'|egrep -v "ora.proxy_advm|ora.asmgroup|ora.diskmon|ora.ons" DBA_BUNDLE6/user_details.sh 0000740 0152073 0152061 00000026621 13775601601 015477 0 ustar oracle oinstall ################################################### # This script show the user details (Creation Stmt) # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 24-09-11 # # # # # # Modified: 31-12-13 # Customized the script to run on # various environments. # 19-02-14 # Added USER's OBJECT COUNT. # 16-09-14 Add Search Feature. ################################################### # ########### # Description: # ########### echo echo "========================================================" echo "This script generates the CREATION STATEMENT for a USER." echo "========================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ######################################## # Exit if the user is not the Oracle Owner: # ######################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # ################################################################ # SQLPLUS: Get the creation statement of a USER plus extra details: # ################################################################ # Variables echo echo Please enter the Username: echo "=========================" while read USERNAME do case ${USERNAME} in "")echo echo "Enter the Username:" echo "==================";; public|PUBLIC|Public) SPOOL_FILE="${USR_ORA_HOME}"/"${USERNAME}"_creation_stmt.log ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 lines 200 set echo off heading off feedback off spool '$SPOOL_FILE' select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE||';' from dba_role_privs where grantee= 'PUBLIC' UNION select 'GRANT '||PRIVILEGE||' TO '||GRANTEE||';' from dba_sys_privs where grantee= 'PUBLIC' UNION select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||';' from DBA_TAB_PRIVS where GRANTEE='PUBLIC' and OWNER not in ('SYS','SYSTEM','WMSYS','XDB','DBSNMP','OLAPSYS','ORDSYS'); spool off EOF if [ -f "${SPOOL_FILE}" ] then echo;echo "The Creation Statement has been spooled in: ${SPOOL_FILE}" echo fi exit;break ;; *) VAL11=$(${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF SELECT COUNT(*) FROM DBA_USERS WHERE USERNAME=upper('$USERNAME'); EOF ) VAL22=`echo $VAL11| awk '{print $NF}'` case ${VAL22} in 0) echo;echo "INFO: USER [${USERNAME}] IS NOT EXIST ON DATABASE [$ORACLE_SID] !" echo; echo "Searching..."; sleep 1 ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pagesize 1000 lines 200 set feedback off set trim on set echo off col USERNAME for a30 col account_status for a23 select username,account_status,profile from dba_users where username like upper ('%$USERNAME%'); EOF echo; echo "Please Enter the FULL USERID:";echo "=============================" ;; *) break;; esac esac done SPOOL_FILE="${USR_ORA_HOME}"/"${USERNAME}"_creation_stmt.log ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set pages 0 lines 200 set echo off heading off feedback off spool '$SPOOL_FILE' SELECT 'CREATE USER ' || u.username ||' IDENTIFIED ' ||' BY VALUES ''' || c.password || ''' DEFAULT TABLESPACE ' || u.default_tablespace ||' TEMPORARY TABLESPACE ' || u.temporary_tablespace ||' PROFILE ' || u.profile || case when account_status= 'OPEN' then ';' else ' Account LOCK;' end "--Creation Statement" FROM dba_users u,user$ c where u.username=c.name and u.username=upper('$USERNAME') UNION select 'GRANT '||GRANTED_ROLE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted Roles" from dba_role_privs where grantee= upper('$USERNAME') UNION select 'GRANT '||PRIVILEGE||' TO '||GRANTEE|| case when ADMIN_OPTION='YES' then ' WITH ADMIN OPTION;' else ';' end "Granted System Privileges" from dba_sys_privs where grantee= upper('$USERNAME') UNION select 'GRANT '||PRIVILEGE||' ON '||OWNER||'.'||TABLE_NAME||' TO '||GRANTEE||case when GRANTABLE='YES' then ' WITH GRANT OPTION;' else ';' end "Granted Object Privileges" from DBA_TAB_PRIVS where GRANTEE=upper('$USERNAME'); spool off set heading on pages 1000 col USERNAME for a25 col PASSWORD for a25 col account_status for a23 col PROFILE for a15 col DEFAULT_TABLESPACE for a20 col TEMPORARY_TABLESPACE for a20 PROMPT SELECT A.USERNAME,B.PASSWORD,A.ACCOUNT_STATUS,A.PROFILE,A.DEFAULT_TABLESPACE,A.TEMPORARY_TABLESPACE FROM DBA_USERS A, USER$ B WHERE A.USER_ID=B.USER# AND USERNAME=UPPER('$USERNAME'); PROMPT PROMPT USER's OBJECT COUNT: PROMPT -------------------- select USERNAME, count(decode(o.TYPE#, 2,o.OBJ#,'')) Tables, count(decode(o.TYPE#, 1,o.OBJ#,'')) Indexes, count(decode(o.TYPE#, 5,o.OBJ#,'')) Syns, count(decode(o.TYPE#, 4,o.OBJ#,'')) Views, count(decode(o.TYPE#, 6,o.OBJ#,'')) Seqs, count(decode(o.TYPE#, 7,o.OBJ#,'')) Procs, count(decode(o.TYPE#, 8,o.OBJ#,'')) Funcs, count(decode(o.TYPE#, 9,o.OBJ#,'')) Pkgs, count(decode(o.TYPE#,12,o.OBJ#,'')) Trigs, count(decode(o.TYPE#,10,o.OBJ#,'')) Deps from obj$ o, dba_users u where u.USER_ID = o.OWNER# (+) and u.USERNAME=upper('$USERNAME') group by USERNAME order by USERNAME; set heading off PROMPT select 'SCHEMA SIZE: '||ceil(sum(bytes)/1024/1024)||' MB' from dba_segments where owner=UPPER('$USERNAME') group by owner; PROMPT ------------ PROMPT select 'Number of Invalid Objects: '||count(*) from dba_objects where STATUS = 'INVALID' and owner=upper('$USERNAME'); PROMPT -------------------------- PROMPT select 'Number of Connected Sessions: ' || count(*) from gv\$session where username=upper('$USERNAME'); PROMPT ----------------------------- EOF if [ -f "${SPOOL_FILE}" ] then echo;echo "The Creation Statement has been spooled in: ${SPOOL_FILE}" echo fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: mahmmoudadel@hotmail.com # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/failed_logins.sh 0000740 0152073 0152061 00000017152 13775601664 015623 0 ustar oracle oinstall ################################################### # This script retrieves the FAILED LOGIN ATTEMPTS. # To be run by ORACLE user # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 25-02-2013 # # # # # # ################################################### ############# # Description: ############# echo echo "=====================================================================" echo "This script retrieve the FAILED LOGIN ATTEMPTS in the last n of days." echo "=====================================================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. ############################# # Listing Available Instances: ############################# # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the Instance You Want To Run this script against:[Enter the number]" echo "-------------------------------------------------------" select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib ########################################## # Exit if the user is not the Oracle Owner: ########################################## CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi ########################### # SQLPLUS Section: ########################### # PROMPT FOR VARIABLES: ###################### echo "How many days back you want to retrieve FAILED LOGIN ATTEMPTS to the Database? [Default 1]" echo "-----------------------------------------------------------------------------" while read NUM_DAYS do case $NUM_DAYS in # NO VALUE PROVIDED: "") NUM_DAYS=1;echo;echo "Retreiving FAILED LOGIN ATTEMPTS data in the last 24 Hours ... [Please Wait]";break ;; # A NON NUMERIC VALUE PROVIDED: *[!0-9]*) echo "Please enter a Valid NUMERIC Value:" ;; *) echo;echo "Retreiving the FAILED LOGIN ATTEMPTS in the last [${NUM_DAYS}] Days ... [Please Wait]";break ;; esac done ############################ # Execution of SQL Statement: ############################ ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" < (sysdate -$NUM_DAYS) order by 1; EOF ############### # END OF SCRIPT ############### # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/COLD_BACKUP.sh 0000740 0152073 0152061 00000037143 13775601642 014570 0 ustar oracle oinstall # ################################################################################################## # Database COLD Backup Script. # [Ver 1.6] # # # # Author: Mahmmoud ADEL # # # # ### # Created: 22-12-13 # # # # # # # Modified: 16-05-14 Increased linesize to avoid line breaking. # # # ################################################################################################## # ########### # Description: # ########### echo echo "===============================================" echo "This script Takes a COLD BACKUP for a database." echo "===============================================" echo sleep 1 # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep -i "^${ORA_USER}:" /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' ${ORATAB} | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi fi # ATTEMPT3: If ORACLE_HOME is in /etc/oratab, use dbhome command: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`dbhome "${ORACLE_SID}"` export ORACLE_HOME fi # ATTEMPT4: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME fi # ATTEMPT5: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' ${USR_ORA_HOME}/.bash_profile ${USR_ORA_HOME}/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME fi # ATTEMPT6: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then if [ -x /usr/bin/locate ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME fi fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # ############################################# # Exit if the executer is not the Oracle Owner: # ############################################# CURR_USER=`whoami` if [ ${ORA_USER} != ${CURR_USER} ]; then echo "" echo "You're Running This Sctipt with User: \"${CURR_USER}\" !!!" echo "Please Run This Script With The Right OS User: \"${ORA_USER}\"" echo "Script Terminated!" exit fi # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ################################ # Creating Backup & Restore Script: # ################################ echo echo "Enter the Backup location: [Full Path]" echo "-------------------------" while read LOC1 do EXTEN=${ORACLE_SID}_`date '+%F'` LOC2=${LOC1}/COLDBACKUP_${EXTEN} /bin/mkdir -p ${LOC2} if [ ! -d "${LOC2}" ]; then echo "Provided Backup Location is NOT Exist/Writable !" echo echo "Please Provide a VALID Backup Location:" echo "---------------------------------------" else echo sleep 1 echo "Backup Location Validated." echo break fi done BKPSCRIPT=${LOC2}/Cold_Backup.sh RSTSCRIPT=${LOC2}/Restore_Cold_Backup.sh BKPSCRIPTLOG=${LOC2}/Cold_Backup.log RSTSCRIPTLOG=${LOC2}/Restore_Cold_Backup.log # Creating the Cold Backup script: echo echo "Creating Cold Backup and Cold Restore Scripts ..." sleep 1 cd ${LOC2} ${ORACLE_HOME}/bin/sqlplus -S "/ as sysdba" <. # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: # http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html DBA_BUNDLE6/schedule_rman_image_copy_bkp.sh 0000740 0152073 0152061 00000014113 13526474761 020657 0 ustar oracle oinstall # ############################################################################################## # Script to be used on crontab to schedule an RMAN Image/Copy Backup VER="[1.2]" # ############################################################################################## # # # # # Author: Mahmmoud ADEL # # # # ### # Created: 01-10-17 # # # # # # # Modified: 02-10-17 # 10-03-19 Add the option of deleting old CONTROLFILE AUTOBACKUP files. # # # ############################################################################################## # VARIABLES Section: [Must be Modified for each Env] # ################# # INSTANCE Name: [Replace ${ORACLE_SID} with your instance SID] export ORACLE_SID=${ORACLE_SID} # ORACLE_HOME Location: [Replace ${ORACLE_HOME} with the right ORACLE_HOME path] export ORACLE_HOME=${ORACLE_HOME} # Backup Location: [Replace /backup/rmancopy with the right backup location path] export BACKUPLOC=/backup/rmancopy # Backup LOG location: export RMANLOG=${BACKUPLOC}/rmancopy.log # Perform Maintenance based on below Backup & Archive Retention: [Y|N] [Default DISABLED] MAINTENANCEFLAG=N # Backup Retention "In Days": [Backups older than this retention will be deleted] export BKP_RETENTION=7 # Archives Deletion "In Days": [Archivelogs older than this retention will be deleted] export ARCH_RETENTION=7 # CONTROLFILE AUTOBACKUP Retention "In Days": [AUTOBACKUP of CONTROLFILE older than this retention will be deleted] CTRL_AUTOBKP_RETENTION=7 # Show the full DATE and TIME details in the backup log: export NLS_DATE_FORMAT='DD-Mon-YYYY HH24:MI:SS' export ORACLE_SID export ORACLE_HOME export BACKUPLOC export COMPRESSION export BKP_RETENTION export ARCH_RETENTION export RMANLOG export NLS_DATE_FORMAT export MAINTENANCEFLAG # Check the selected MAINTENANCE option: case ${MAINTENANCEFLAG} in Y|y|YES|Yes|yes|ON|on) HASH_MAINT="" export HASH_MAINT ;; *) HASH_MAINT="#" export COMPRESSED_BKP ;; esac # Append the date to the backup log for each script execution: echo "----------------------------" >> ${RMANLOG} date >> ${RMANLOG} echo "----------------------------" >> ${RMANLOG} # ################### # RMAN SCRIPT Section: # ################### ${ORACLE_HOME}/bin/rman target / msglog=${RMANLOG} < ${LOGFILE} fi fi # ####################################### # Excluded INSTANCES: # ####################################### # Here you can mention the instances the script will IGNORE and will NOT run against: # Use pipe "|" as a separator between each instance name. # e.g. Excluding: -MGMTDB, ASM instances: EXL_DB="\-MGMTDB|ASM|APX" #Excluded INSTANCES [Will not get reported offline]. # ############################## # SCRIPT ENGINE STARTS FROM HERE ............................................ # ############################## # ########################### # Listing Available Databases: # ########################### # Count Instance Numbers: INS_COUNT=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|wc -l ) # Exit if No DBs are running: if [ $INS_COUNT -eq 0 ] then echo No Database Running ! exit fi # If there is ONLY one DB set it as default without prompt for selection: if [ $INS_COUNT -eq 1 ] then export ORACLE_SID=$( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) # If there is more than one DB ASK the user to select: elif [ $INS_COUNT -gt 1 ] then echo echo "Select the ORACLE_SID:[Enter the number]" echo --------------------- select DB_ID in $( ps -ef|grep pmon|grep -v grep|egrep -v ${EXL_DB}|awk '{print $NF}'|sed -e 's/ora_pmon_//g'|grep -v sed|grep -v "s///g" ) do integ='^[1-9]+$' if ! [[ ${REPLY} =~ ${integ} ]] || [ ${REPLY} -gt ${INS_COUNT} ] then echo echo "Error: Not a valid number!" echo echo "Enter a valid NUMBER from the displayed list !: i.e. Enter a number from [1 to ${INS_COUNT}]" echo "-----------------------------------------------" else export ORACLE_SID=$DB_ID echo printf "`echo "Selected Instance: ["` `echo -e "\033[33;5m${DB_ID}\033[0m"` `echo "]"`\n" echo break fi done fi # Exit if the user selected a Non Listed Number: if [ -z "${ORACLE_SID}" ] then echo "You've Entered An INVALID ORACLE_SID" exit fi # ######################### # Getting ORACLE_HOME # ######################### ORA_USER=`ps -ef|grep ${ORACLE_SID}|grep pmon|grep -v grep|egrep -v ${EXL_DB}|grep -v "\-MGMTDB"|awk '{print $1}'|tail -1` USR_ORA_HOME=`grep ${ORA_USER} /etc/passwd| cut -f6 -d ':'|tail -1` # SETTING ORATAB: if [ -f /etc/oratab ] then ORATAB=/etc/oratab export ORATAB ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab export ORATAB fi # ATTEMPT1: Get ORACLE_HOME using pwdx command: export PGREP=`which pgrep` export PWDX=`which pwdx` if [[ -x ${PGREP} ]] && [[ -x ${PWDX} ]] then PMON_PID=`pgrep -lf _pmon_${ORACLE_SID}|awk '{print $1}'` export PMON_PID ORACLE_HOME=`pwdx ${PMON_PID}|awk '{print $NF}'|sed -e 's/\/dbs//g'` export ORACLE_HOME fi #echo "ORACLE_HOME from PWDX is ${ORACLE_HOME}" # ATTEMPT2: If ORACLE_HOME not found get it from oratab file: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ## If OS is Linux: if [ -f /etc/oratab ] then ORATAB=/etc/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME ## If OS is Solaris: elif [ -f /var/opt/oracle/oratab ] then ORATAB=/var/opt/oracle/oratab ORACLE_HOME=`grep -v '^\#' $ORATAB | grep -v '^$'| grep -i "^${ORACLE_SID}:" | perl -lpe'$_ = reverse' | cut -f3 | perl -lpe'$_ = reverse' |cut -f2 -d':'` export ORACLE_HOME fi #echo "ORACLE_HOME from oratab is ${ORACLE_HOME}" fi # ATTEMPT3: If ORACLE_HOME is still not found, search for the environment variable: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`env|grep -i ORACLE_HOME|sed -e 's/ORACLE_HOME=//g'` export ORACLE_HOME #echo "ORACLE_HOME from environment is ${ORACLE_HOME}" fi # ATTEMPT4: If ORACLE_HOME is not found in the environment search user's profile: [Less accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`grep -h 'ORACLE_HOME=\/' $USR_ORA_HOME/.bash_profile $USR_ORA_HOME/.*profile | perl -lpe'$_ = reverse' |cut -f1 -d'=' | perl -lpe'$_ = reverse'|tail -1` export ORACLE_HOME #echo "ORACLE_HOME from User Profile is ${ORACLE_HOME}" fi # ATTEMPT5: If ORACLE_HOME is still not found, search for orapipe: [Least accurate] if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then ORACLE_HOME=`locate -i orapipe|head -1|sed -e 's/\/bin\/orapipe//g'` export ORACLE_HOME #echo "ORACLE_HOME from orapipe search is ${ORACLE_HOME}" fi # TERMINATE: If all above attempts failed to get ORACLE_HOME location, EXIT the script: if [ ! -f ${ORACLE_HOME}/bin/sqlplus ] then echo "Please export ORACLE_HOME variable in your .bash_profile file under oracle user home directory in order to get this script to run properly" echo "e.g." echo "export ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_1" exit fi export LD_LIBRARY_PATH=${ORACLE_HOME}/lib # Neutralize login.sql file: # ######################### # Existance of login.sql file under current working directory eliminates many functions during the execution of this script: if [ -f ./login.sql ] then mv ./login.sql ./login.sql_NeutralizedBy${SCRIPT_NAME} fi # ################################### # SQLPLUS: Getting All Sessions Info: # ################################### ${ORACLE_HOME}/bin/sqlplus -s '/ as sysdba' << EOF set feedback off set pages 0 spool ${LOGFILE} APPEND prompt select 'Timestamp: '||to_char(sysdate, 'DD-Mon-YYYY HH24:MI:SS') from dual; prompt =================================== prompt Current sessions in the Database... prompt =================================== prompt set feedback off linesize 220 pages 1000 col inst for 99 col module for a27 col event for a28 col MACHINE for a27 col "ST|WAITD|ACT_SINC|LOG_T" for a45 col "INST|USER|SID,SERIAL#" for a30 col "INS|USER|SID,SER|MACHIN|MODUL" for a72 select substr(s.INST_ID||'|'||s.USERNAME||'|'||s.sid||','||s.serial#||'|'||substr(s.MACHINE,1,25)||' | '||substr(s.MODULE,1,25),1,72)"INS|USER|SID,SER|MACHIN|MODUL" --select s.INST_ID||'|'||s.USERNAME||' | '||s.sid||','||s.serial# "INST|USER|SID,SERIAL#" --,substr(s.MODULE,1,27)"MODULE" --,substr(s.MACHINE,1,27)"MACHINE" ,substr(s.status||'|'||round(w.WAIT_TIME_MICRO/1000000)||'|'||LAST_CALL_ET||'|'||to_char(LOGON_TIME,'ddMon HH24:MI'),1,45) "ST|WAITD|ACT_SINC|LOG_T" ,substr(w.event,1,28)"EVENT" --,s.PREV_SQL_ID ,s.SQL_ID CURR_SQL_ID from gv\$session s, gv\$session_wait w where s.USERNAME is not null and s.sid=w.sid order by "ST|WAITD|ACT_SINC|LOG_T" desc, "INS|USER|SID,SER|MACHIN|MODUL"; --order by "ST|WA_ST|WAITD|ACT_SINC|LOG_T" desc, "INST|USER|SID,SERIAL#"; set pages 1000 col MACHINE for a70 col MODULE for a70 PROMPT PROMPT SESSIONS Distribution: PROMPT ---------------------- PROMPT PER MODULE: select INST_ID,MODULE,count(*) "TOTAL_SESSIONS" from gv\$session group by INST_ID,module order by INST_ID,count(*) desc,MODULE; PROMPT PROMPT PER MACHINE: select INST_ID,MACHINE,count(*) "TOTAL_SESSIONS" from gv\$session group by INST_ID,MACHINE order by INST_ID,count(*) desc,MACHINE; PROMPT set pages 0 select 'ACTIVE SESSIONS: '||count(*) from gv\$session where USERNAME is not null and status='ACTIVE'; select 'INACTIVE SESSIONS: '||count(*) from gv\$session where USERNAME is not null and status='INACTIVE'; select 'BACKGROUND SESSIONS: '||count(*) from gv\$session where USERNAME is null; PROMPT -------------------- ------ select 'TOTAL SESSIONS: '||count(*) from gv\$session; PROMPT EOF # De-Neutralize login.sql file: # ############################ # If login.sql was renamed during the execution of the script revert it back to its original name: if [ -f ./login.sql_NeutralizedBy${SCRIPT_NAME} ] then mv ./login.sql_NeutralizedBy${SCRIPT_NAME} ./login.sql fi # ############# # END OF SCRIPT # ############# # REPORT BUGS to: . # DISCLAIMER: THIS SCRIPT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY. IT IS PROVIDED "AS IS". # DOWNLOAD THE LATEST VERSION OF DATABASE ADMINISTRATION BUNDLE FROM: http://dba-tips.blogspot.com/2014/02/oracle-database-administration-scripts.html