Showing posts with label Shell Script. Show all posts
Showing posts with label Shell Script. Show all posts

May 1, 2026

Shell Script to Automate Oracle 19c TDE Wallet & sqlnet.ora Backups

 

Recently, one of my junior colleague had a requirement to clone a production database. While doing so he faced the following error while opening the database

ORA-28374: typed master key not found in wallet
ORA-00704: bootstrap process failure

 

The Production database had TDE enabled  so it was obvious oracle will look for the wallet before opening the database.

Now this is a situation where no tricks or workaround would work unless the correct wallet(ewallet.p12 ) is provided.

Thankfully , we have been following a practice to keep our wallet backup as part of backup strategy. This is very critical in case TDE is enabled and should be adopted by DBA’s .

Sharing the shell script we are using  for taking wallet backup . This script also takes backup of sqlnet.ora which is also important.

#!/bin/bash

# ==============================================================================

# Script Name: wallet_backup.sh

# Description: Backs up Oracle TDE wallet files AND sqlnet.ora with retention.

# Run as:      oracle user

# ==============================================================================

 

# Load Oracle environment variables (CRITICAL FOR CRON JOBS)

. ~/.bash_profile

 

# --- Configuration Variables ---

# The active wallet location

WALLET_DIR="/opt/oracle/dcs/commonstore/wallets/prddb_dsmc19c/tde"

 

# Location of sqlnet.ora (Uses the standard ORACLE_HOME network path)

SQLNET_FILE="$ORACLE_HOME/network/admin/sqlnet.ora"

 

# The destination for the backups

BACKUP_DEST="/u01/backup/wallet_bkp"

 

# How many days to keep old backups

RETENTION_DAYS=30

 

# Generate a timestamp for the filenames (Format: YYYYMMDD_HHMMSS)

TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

LOG_FILE="${BACKUP_DEST}/wallet_backup_${TIMESTAMP}.log"

 

# --- Pre-flight Checks ---

# Ensure destination directory exists

mkdir -p "$BACKUP_DEST"

 

echo "==================================================" | tee -a "$LOG_FILE"

echo " Starting TDE Wallet & Config Backup at $(date)" | tee -a "$LOG_FILE"

echo " Destination: $BACKUP_DEST" | tee -a "$LOG_FILE"

echo "==================================================" | tee -a "$LOG_FILE"

 

# --- Backup Execution ---

echo "Copying files..." | tee -a "$LOG_FILE"

 

# 1. Backup ewallet.p12

if [ -f "${WALLET_DIR}/ewallet.p12" ]; then

    cp -p "${WALLET_DIR}/ewallet.p12" "${BACKUP_DEST}/ewallet_${TIMESTAMP}.p12"

    echo " -> SUCCESS: ewallet.p12 backed up." | tee -a "$LOG_FILE"

else

    echo " -> WARNING: ewallet.p12 NOT FOUND in $WALLET_DIR." | tee -a "$LOG_FILE"

fi

 

# 2. Backup cwallet.sso

if [ -f "${WALLET_DIR}/cwallet.sso" ]; then

    cp -p "${WALLET_DIR}/cwallet.sso" "${BACKUP_DEST}/cwallet_${TIMESTAMP}.sso"

    echo " -> SUCCESS: cwallet.sso backed up." | tee -a "$LOG_FILE"

else

    echo " -> WARNING: cwallet.sso NOT FOUND in $WALLET_DIR." | tee -a "$LOG_FILE"

fi

 

# 3. Backup sqlnet.ora

if [ -f "$SQLNET_FILE" ]; then

    cp -p "$SQLNET_FILE" "${BACKUP_DEST}/sqlnet_${TIMESTAMP}.ora"

    echo " -> SUCCESS: sqlnet.ora backed up." | tee -a "$LOG_FILE"

else

    echo " -> WARNING: sqlnet.ora NOT FOUND at $SQLNET_FILE." | tee -a "$LOG_FILE"

fi

 

# --- Housekeeping (Retention Policy) ---

echo "Cleaning up backups older than $RETENTION_DAYS days..." | tee -a "$LOG_FILE"

 

find "$BACKUP_DEST" -name "ewallet_*.p12" -type f -mtime +$RETENTION_DAYS -exec rm -f {} \;

find "$BACKUP_DEST" -name "cwallet_*.sso" -type f -mtime +$RETENTION_DAYS -exec rm -f {} \;

find "$BACKUP_DEST" -name "sqlnet_*.ora" -type f -mtime +$RETENTION_DAYS -exec rm -f {} \;

find "$BACKUP_DEST" -name "wallet_backup_*.log" -type f -mtime +$RETENTION_DAYS -exec rm -f {} \;

 

echo "Cleanup complete." | tee -a "$LOG_FILE"

echo "Backup process finished at $(date)" | tee -a "$LOG_FILE"

echo "==================================================" | tee -a "$LOG_FILE"

 

 

Automate the script via cronjob

[oracle@prddb ~]$ crontab -e

0 1 * * * /u01/backup/scripts/wallet_backup.sh

 

 

 

February 2, 2025

Automating Oracle Forms 11g Compilation with a Shell Script

 

Automating Oracle Forms 11g Compilation with a Shell Script

In the world of Oracle applications, managing and compiling forms can be a time-consuming task, especially when dealing with a large number of forms. Fortunately, with the power of shell scripting in Linux, we can automate this process to save time and reduce errors. In this blog post, we will guide you through creating a shell script that compiles multiple Oracle Forms 11g or 12c in one go.

Why Automate Form Compilation?

Compiling Oracle Forms is essential for ensuring that your applications run smoothly. When changes are made to forms, they need to be recompiled to reflect those changes in the application. Manually compiling each form can be tedious and prone to human error, particularly when you have dozens or even hundreds of forms to process. By automating this task, you can:

  • Save Time: Compile multiple forms simultaneously without manual intervention.
  • Reduce Errors: Minimize the risk of missing a form or making mistakes during the compilation process.
  • Increase Efficiency: Focus on more critical tasks while the script handles the repetitive work.


Below is a shell script designed to compile all .fmb files in a specified directory for Oracle Forms 11g.


#!/bin/bash

. .bash_profile

 export FR_INST=/u01/app/oracle/product/fmw11g/asinst_1

 # Database credentials

USERNAME="scott"

PASSWORD="tiger"

DATABASE="prod"

 # Directory containing the forms

FORMS_DIR="/home/oracle/forms"

 

# Change to the forms directory

cd $FORMS_DIR || { echo "Directory not found: $FORMS_DIR"; exit 1; }

 

# Compile all forms

echo "Starting compilation of Oracle Forms..."

 

for form in *.fmb; do

    if [ -f "$form" ]; then

        echo "Compiling $form..."

        $FR_INST/bin/frmcmp_batch.sh Module_type=form Module="$form" userid="$USERNAME/$PASSWORD@$DATABASE"  batch=yes  compile_all=yes

       

        if [ $? -ne 0 ]; then

            echo "Error compiling $form"

        else

            echo "$form compiled successfully."

        fi

    fi

done

 

echo "Compilation process completed."

 

 

Instructions for Using the Script

  1. Modify Variables:
    • Update ORACLE_HOME, USERNAME, PASSWORD, DATABASE, and FORMS_DIR with your actual Oracle installation path and database credentials.
  2. Save the Script:
    • Save this script to a file, for example, compile_forms.sh.
  3. Make it Executable:

              chmod 777 compile_forms.sh

  1. Run the Script:
    • Execute the script in your terminal:

./compile_forms.sh

Key Components of the Script

  • Environment Variables: The script sets up necessary environment variables such as ORACLE_HOME and updates the PATH to include Oracle binaries.
  • Looping Through Forms: It uses a for loop to iterate through all .fmb files in the specified directory.
  • Error Handling: After each compilation attempt, it checks for errors and provides feedback on whether each form was compiled successfully or if there was an error.


July 22, 2024

Shell script to delete old archive logs in RAC databases

 Today, I will be sharing one handy shell script that can be used to delete old archive logs. Considering the archive logs are already backed up and not required for any recovery purpose. In the following example i will be deleting archive that are 5 days old.


vi archive_del.sh

#!/bin/bash

 

# Set the number of days

DAYS_OLD=5

 

# Function to delete archive logs older than specified days for a given ORACLE_SID

delete_old_archivelogs() {

  ORACLE_SID=$1

  export ORACLE_SID

 

  echo "Deleting archive logs older than $DAYS_OLD days for database $ORACLE_SID..."

 

  rman target / <<EOF

    CROSSCHECK ARCHIVELOG ALL;

    DELETE NOPROMPT ARCHIVELOG ALL COMPLETED BEFORE 'SYSDATE-$DAYS_OLD';

    EXIT;

EOF

 

  if [ $? -eq 0 ]; then

    echo "Archive logs older than $DAYS_OLD days deleted successfully for database $ORACLE_SID."

  else

    echo "Failed to delete archive logs for database $ORACLE_SID."

  fi

}

 

# Source the Oracle environment variables

source /usr/local/bin/oraenv

 

# Get the list of running Oracle database instances (ORACLE_SID) excluding ASM

ORACLE_INSTANCES=$(ps -ef | grep pmon | grep -v grep | grep -v asm | awk '{print $9}' | cut -d'_' -f3)

 

# Loop through each instance and delete old archive logs

for SID in $ORACLE_INSTANCES; do

  delete_old_archivelogs $SID

done


Schedule the above script in crontab as per your requirement.

December 29, 2023

How to extract user DDL and all privileges of a user in oracle

We often require to extract information such as User DDL and all privileges granted including roles, system and object privileges, tablespace quota etc. Using the following method we can extract it easily.

Create a .sql file and paste the following code inside.

Note:- While executing this sql make sure to enter the username in UPPERCASE.

vi info.sql

-- Connect to target database and execute with a user that has DBA privileges

 

-- Example for user "CRPDTA" - Make sure to put the username in uppercase.

 

SET LONGCHUNKSIZE 20000 PAGESIZE 0 FEEDBACK OFF VERIFY OFF TRIMPOOL ON

COLUMN Extracted_DDL FORMAT A1000

 

EXEC DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'PRETTY', TRUE);

EXEC DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', TRUE);

 

UNDEFINE User_in_Uppercase;

 

SET LINESIZE 1000

SET LONG 2000000000

 

SELECT

    (CASE

        WHEN (

            (SELECT COUNT(*)

             FROM DBA_USERS

             WHERE USERNAME = '&&User_in_Uppercase' AND PROFILE <> 'DEFAULT') > 0

        ) THEN

            CHR(10) || ' -- Note: Profile' || (SELECT DBMS_METADATA.GET_DDL('PROFILE', U.PROFILE) AS DDL

                                               FROM DBA_USERS U

                                               WHERE U.USERNAME = '&User_in_Uppercase')

        ELSE

            TO_CLOB(CHR(10) || ' -- Note: Default profile, no need to create!')

    END)

FROM DUAL

UNION ALL

SELECT

    (CASE

        WHEN (

            (SELECT COUNT(*)

             FROM DBA_USERS

             WHERE USERNAME = '&User_in_Uppercase') > 0

        ) THEN

            ' -- Note: Create user statement' || DBMS_METADATA.GET_DDL('USER', '&User_in_Uppercase')

        ELSE

            TO_CLOB(CHR(10) || ' -- Note: User not found!')

    END) Extracted_DDL

FROM DUAL

UNION ALL

SELECT

    (CASE

        WHEN (

            (SELECT COUNT(*)

             FROM DBA_TS_QUOTAS

             WHERE USERNAME = '&User_in_Uppercase') > 0

        ) THEN

            ' -- Note: TBS quota' || DBMS_METADATA.GET_GRANTED_DDL('TABLESPACE_QUOTA', '&User_in_Uppercase')

        ELSE

            TO_CLOB(CHR(10) || ' -- Note: No TS Quotas found!')

    END)

FROM DUAL

UNION ALL

SELECT

    (CASE

        WHEN (

            (SELECT COUNT(*)

             FROM DBA_ROLE_PRIVS

             WHERE GRANTEE = '&User_in_Uppercase') > 0

        ) THEN

            ' -- Note: Roles' || DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT', '&User_in_Uppercase')

        ELSE

            TO_CLOB(CHR(10) || ' -- Note: No granted Roles found!')

    END)

FROM DUAL

UNION ALL

SELECT

    (CASE

        WHEN (

            (SELECT COUNT(*)

             FROM V$PWFILE_USERS

             WHERE USERNAME = '&User_in_Uppercase' AND SYSDBA = 'TRUE') > 0

        ) THEN

            ' -- Note: sysdba' || CHR(10) || TO_CLOB(' GRANT SYSDBA TO ' || '"' || '&User_in_Uppercase' || '"' || ';')

        ELSE

            TO_CLOB(CHR(10) || ' -- Note: No sysdba administrative Privilege found!')

    END)

FROM DUAL

UNION ALL

SELECT

    (CASE

        WHEN (

            (SELECT COUNT(*)

             FROM DBA_SYS_PRIVS

             WHERE GRANTEE = '&User_in_Uppercase') > 0

        ) THEN

            ' -- Note: System Privileges' || DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT', '&User_in_Uppercase')

        ELSE

            TO_CLOB(CHR(10) || ' -- Note: No System Privileges found!')

    END)

FROM DUAL

UNION ALL

SELECT

    (CASE

        WHEN (

            (SELECT COUNT(*)

             FROM DBA_TAB_PRIVS

             WHERE GRANTEE = '&User_in_Uppercase') > 0

        ) THEN

            ' -- Note: Object Privileges' || DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT', '&User_in_Uppercase')

        ELSE

            TO_CLOB(CHR(10) || ' -- Note: No Object Privileges found!')

    END)

FROM DUAL

/

 

Output:-

Login into database and run the sql we created above.. We used username as “PY920”

sqlplus / as sysdba

SQL> @info.sql

Enter value for user_in_uppercase: PY920

 

 -- Note: Profile

   CREATE PROFILE "UNLIM_LOG"

    LIMIT

         COMPOSITE_LIMIT UNLIMITED

         SESSIONS_PER_USER UNLIMITED

         CPU_PER_SESSION UNLIMITED

         CPU_PER_CALL UNLIMITED

         LOGICAL_READS_PER_SESSION UNLIMITED

         LOGICAL_READS_PER_CALL UNLIMITED

         IDLE_TIME UNLIMITED

         CONNECT_TIME UNLIMITED

         PRIVATE_SGA UNLIMITED

         FAILED_LOGIN_ATTEMPTS UNLIMITED

         PASSWORD_LIFE_TIME UNLIMITED

         PASSWORD_REUSE_TIME UNLIMITED

         PASSWORD_REUSE_MAX UNLIMITED

         PASSWORD_VERIFY_FUNCTION DEFAULT

         PASSWORD_LOCK_TIME UNLIMITED

         PASSWORD_GRACE_TIME UNLIMITED

         INACTIVE_ACCOUNT_TIME DEFAULT

         PASSWORD_ROLLOVER_TIME DEFAULT ;

 

 -- Note: Create user statement

   CREATE USER "PY920" IDENTIFIED BY VALUES 'S:E927BDEC46440F4264941D55A483B1C07A522B852D94203349093C5B2F2D;T:5FC638A2DA78087F85E7BABF9EA95404BD400DC6923181FE420BC91A8A11C6CD4B5D95103E1FB27E01981266C7B3F43C9AE5851EE4AFFC7BDC6066E63598D80C51295AC44FAD0651B66B72A4C2E0E639'

      DEFAULT TABLESPACE "PY920T"

      TEMPORARY TABLESPACE "TEMP2"

      PROFILE "UNLIM_LOG";

 ALTER USER "PY920" LOCAL TEMPORARY TABLESPACE "TEMP2";

 

 -- Note: TBS quota

  DECLARE

  TEMP_COUNT NUMBER;

  SQLSTR VARCHAR2(200);

BEGIN

  SQLSTR := 'ALTER USER "PY920" QUOTA UNLIMITED ON "PY920I"';

  EXECUTE IMMEDIATE SQLSTR;

EXCEPTION

  WHEN OTHERS THEN

    IF SQLCODE = -30041 THEN

      SQLSTR := 'SELECT COUNT(*) FROM USER_TABLESPACES

              WHERE TABLESPACE_NAME = ''PY920I'' AND CONTENTS = ''TEMPORARY''';

      EXECUTE IMMEDIATE SQLSTR INTO TEMP_COUNT;

      IF TEMP_COUNT = 1 THEN RETURN;

      ELSE RAISE;

      END IF;

    ELSE

      RAISE;

    END IF;

END;

/

  DECLARE

  TEMP_COUNT NUMBER;

  SQLSTR VARCHAR2(200);

BEGIN

  SQLSTR := 'ALTER USER "PY920" QUOTA UNLIMITED ON "PY920T"';

  EXECUTE IMMEDIATE SQLSTR;

EXCEPTION

  WHEN OTHERS THEN

    IF SQLCODE = -30041 THEN

      SQLSTR := 'SELECT COUNT(*) FROM USER_TABLESPACES

              WHERE TABLESPACE_NAME = ''PY920T'' AND CONTENTS = ''TEMPORARY''';

      EXECUTE IMMEDIATE SQLSTR INTO TEMP_COUNT;

      IF TEMP_COUNT = 1 THEN RETURN;

      ELSE RAISE;

      END IF;

    ELSE

      RAISE;

    END IF;

END;

/

 

 -- Note: Roles

   GRANT "JDEUSER" TO "PY920";

   GRANT "JDE_ROLE" TO "PY920";

 

 

 -- Note: No sysdba administrative Privilege found!

 

 

 -- Note: No System Privileges found!

 

 

 -- Note: No Object Privileges found!

 

SQL>

 


April 24, 2023

Shell script to convert physical standby database into snapshot standby and vice versa

 

Today I will show a scenario where a customer had a requirement to refresh their snapshot standby database. The setup was 1 primary database and 2 physical standby databases among which one standby database was always kept in physical standby mode but the other one was used by the developer and a daily refresh was the requirement.

Since they wanted to convert snapshot standby into physical standby for sync and later convert it back to snapshot standby I prepared two shell script to perform the entire activity.

 

·       Shell script to convert physical standby database into snapshot standby database

#!/bin/bash


 # Set environment variables

export ORACLE_HOME=/u01/oracle/19.3.0

export ORACLE_SID=PROD

export PATH=$ORACLE_HOME/bin:$PATH

 

# Define database names

PRIMARY_DB_NAME=PROD

STANDBY_DB_NAME=SBDB

 

# Define log file path

rm $LOG_FILE

LOG_FILE=/u01/snapshot_convert_logfile.log

 

# Define maximum number of retries

MAX_RETRIES=2

 

# Function to log messages to log file

log() {

  echo "$(date +'%Y-%m-%d %H:%M:%S') $1" >> $LOG_FILE

}

 

# Function to perform conversion

perform_conversion() {

  log "Performing conversion of $STANDBY_DB_NAME to snapshot standby..."

  dgmgrl <<EOF

  connect /

  convert database $STANDBY_DB_NAME to snapshot standby;

EOF

} >> $LOG_FILE

# Retry loop

retries=0

while [ $retries -lt $MAX_RETRIES ]; do

  perform_conversion

  if grep -q "ORA-" $LOG_FILE; then

    log "Error occurred during conversion. Retrying..."

    ((retries++))

    sleep 5

  else

    log "Conversion completed successfully. Standby database is now a snapshot standby."

    break

  fi

done

 

# Check for maximum retries

if [ $retries -eq $MAX_RETRIES ]; then

  log "Maximum retries reached. Conversion failed. Please check the log for details."

fi

 

 

·       Shell script to convert snapshot standby database into physical standby database

#!/bin/bash

 

# Set environment variables

export ORACLE_HOME=/u01/oracle/19.3.0

export ORACLE_SID=PROD

export PATH=$ORACLE_HOME/bin:$PATH

 

# Define database names

PRIMARY_DB_NAME=PROD

STANDBY_DB_NAME=SBDB

 

# Define log file path

rm $LOG_FILE

LOG_FILE=/u01/physical_convert_logfile.log

 

# Define maximum number of retries

MAX_RETRIES=2

 

# Function to log messages to log file

log() {

  echo "$(date +'%Y-%m-%d %H:%M:%S') $1" >> $LOG_FILE

}

 

# Function to perform conversion

perform_conversion() {

  log "Performing conversion of $STANDBY_DB_NAME to physical standby..."

dgmgrl sys/Prodpassword@prod<<EOF

convert database $STANDBY_DB_NAME to physical standby;

EOF

} >> $LOG_FILE

# Retry loop

retries=0

while [ $retries -lt $MAX_RETRIES ]; do

  perform_conversion

  if grep -q "ORA-" $LOG_FILE; then

    log "Error occurred during conversion. Retrying..."

    ((retries++))

    sleep 5

  else

    log "Conversion completed successfully. Standby database is now a physical standby."

    break

  fi

done

 

# Check for maximum retries

if [ $retries -eq $MAX_RETRIES ]; then

  log "Maximum retries reached. Conversion failed. Please check the log for details."

fi

 

Once the snapshot standby is converted to physical standby, give it time to synchronize with primary database.

Oracle Database 26ai Installation Using RPM on Oracle Linux 9 (OEL 9) – Step-by-Step Guide

  In this post I will describe the installation of Oracle Database 26ai 64-bit on Oracle Linux 9 (OL8) 64-bit. The installation requires a m...