Total Pageviews

Saturday, August 22, 2026

Update Java using python script.

 #!/usr/bin/env python3
import csv
import os
import sys
import paramiko
from datetime import datetime

# ============================================================
# CONFIGURATION
# ============================================================
CSV_FILE = "jdk_servers.csv"
JDK_TAR = "/home/oracle/Desktop/jdk-8u501-linux-x64.tar.gz"
SSH_USER = "oracle"
SSH_PORT = 22
LOG_FILE = "jdk_upgrade.log"

# ============================================================
# Logging
# ============================================================
def log(message):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    msg = f"[{timestamp}] {message}"
    print(msg)
    with open(LOG_FILE, "a") as f:
        f.write(msg + "\n")

# ============================================================
# Execute remote command
# ============================================================
def execute(ssh, command):
    log(f"COMMAND: {command}")
    stdin, stdout, stderr = ssh.exec_command(command)
    output = stdout.read().decode().strip()
    error = stderr.read().decode().strip()
    exit_code = stdout.channel.recv_exit_status()
    if output:
        log(output)
    if error:
        log(error)
    return exit_code, output, error

# ============================================================
# Upgrade JDK
# ============================================================
def upgrade_jdk(server, jdk_path):
    log("")
    log("=" * 70)
    log(f"Starting JDK upgrade on {server}")
    log(f"JDK Path: {jdk_path}")
    log("=" * 70)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(
        paramiko.AutoAddPolicy()
    )
    try:
        log(f"Connecting to {server}...")
        ssh.connect(
            hostname=server,
            port=SSH_PORT,
            username=SSH_USER,
            timeout=30
        )
        log("SSH connection successful.")
        # ----------------------------------------------------
        # Check JDK tar
        # ----------------------------------------------------
        exit_code, _, _ = execute(
            ssh,
            f"test -f {JDK_TAR}"
        )
        if exit_code != 0:
            return (
                "FAILED",
                "",
                "",
                "JDK tar file not found"
            )
        # ----------------------------------------------------
        # Check existing JDK
        # ----------------------------------------------------
        exit_code, old_version, _ = execute(
            ssh,
            f"{jdk_path}/bin/java -version"
        )
        if exit_code != 0:
            old_version = "UNKNOWN"
            log(
                "WARNING: Unable to determine current JDK version."
            )
        # ----------------------------------------------------
        # Timestamp
        # ----------------------------------------------------
        timestamp = datetime.now().strftime(
            "%Y%m%d_%H%M%S"
        )
        backup_path = (
            f"{jdk_path}_backup_{timestamp}"
        )
        temp_path = (
            f"{jdk_path}_new_{timestamp}"
        )
        # ----------------------------------------------------
        # Check whether JDK directory exists
        # ----------------------------------------------------
        exit_code, _, _ = execute(
            ssh,
            f"test -d {jdk_path}"
        )
        if exit_code != 0:
            return (
                "FAILED",
                old_version,
                "",
                f"JDK path does not exist: {jdk_path}"
            )
        # ----------------------------------------------------
        # Capture ownership
        # ----------------------------------------------------
        exit_code, ownership, _ = execute(
            ssh,
            f"stat -c '%U:%G' {jdk_path}"
        )
        if exit_code != 0:
            return (
                "FAILED",
                old_version,
                "",
                "Unable to determine JDK ownership"
            )
        log(f"JDK ownership: {ownership}")
        # ----------------------------------------------------
        # Backup current JDK
        # ----------------------------------------------------
        log("Creating JDK backup...")
        exit_code, _, _ = execute(
            ssh,
            f"mv {jdk_path} {backup_path}"
        )
        if exit_code != 0:
            return (
                "FAILED",
                old_version,
                "",
                "Unable to backup existing JDK"
            )
        log(
            f"Backup created: {backup_path}"
        )
        # ----------------------------------------------------
        # Create temporary directory
        # ----------------------------------------------------
        execute(
            ssh,
            f"mkdir -p {temp_path}"
        )
        # ----------------------------------------------------
        # Extract new JDK
        # ----------------------------------------------------
        log("Extracting new JDK...")
        exit_code, _, _ = execute(
            ssh,
            f"tar -xzf {JDK_TAR} "
            f"-C {temp_path} "
            f"--strip-components=1"
        )
        if exit_code != 0:
            log("JDK extraction failed.")
            # Rollback
            execute(
                ssh,
                f"rm -rf {temp_path}"
            )
            execute(
                ssh,
                f"mv {backup_path} {jdk_path}"
            )
            return (
                "ROLLED_BACK",
                old_version,
                "",
                "JDK extraction failed"
            )
        # ----------------------------------------------------
        # Set ownership
        # ----------------------------------------------------
        log(
            f"Setting ownership: {ownership}"
        )
        exit_code, _, _ = execute(
            ssh,
            f"chown -R {ownership} {temp_path}"
        )
        if exit_code != 0:
            log("Ownership update failed.")
            execute(
                ssh,
                f"rm -rf {temp_path}"
            )
            execute(
                ssh,
                f"mv {backup_path} {jdk_path}"
            )
            return (
                "ROLLED_BACK",
                old_version,
                "",
                "Unable to set ownership"
            )
        # ----------------------------------------------------
        # Activate new JDK
        # ----------------------------------------------------
        log("Activating new JDK...")
        exit_code, _, _ = execute(
            ssh,
            f"mv {temp_path} {jdk_path}"
        )
        if exit_code != 0:
            log("Unable to activate new JDK.")
            execute(
                ssh,
                f"rm -rf {temp_path}"
            )
            execute(
                ssh,
                f"mv {backup_path} {jdk_path}"
            )
            return (
                "ROLLED_BACK",
                old_version,
                "",
                "Unable to activate new JDK"
            )
        # ----------------------------------------------------
        # Verify
        # ----------------------------------------------------
        log("Verifying new JDK...")
        exit_code, new_version, _ = execute(
            ssh,
            f"{jdk_path}/bin/java -version"
        )
        if exit_code != 0:
            log(
                "New JDK verification failed."
            )
            # Rollback
            execute(
                ssh,
                f"rm -rf {jdk_path}"
            )
            execute(
                ssh,
                f"mv {backup_path} {jdk_path}"
            )
            return (
                "ROLLED_BACK",
                old_version,
                "",
                "Java verification failed"
            )
        # ----------------------------------------------------
        # SUCCESS
        # ----------------------------------------------------
        log(
            f"JDK upgrade successful on {server}"
        )
        return (
            "SUCCESS",
            old_version,
            new_version,
            f"Backup: {backup_path}"
        )
    except Exception as e:
        log(
            f"ERROR connecting/upgrading {server}: {e}"
        )
        return (
            "FAILED",
            "",
            "",
            str(e)
        )
    finally:
        ssh.close()

# ============================================================
# Main
# ============================================================
def main():
    if not os.path.isfile(CSV_FILE):
        print(
            f"ERROR: CSV file not found: {CSV_FILE}"
        )
        sys.exit(1)
    results = []
    with open(
        CSV_FILE,
        newline=""
    ) as csvfile:
        reader = csv.DictReader(csvfile)
        required_columns = {
            "server",
            "oracle_home"
        }
        if not required_columns.issubset(
            reader.fieldnames
        ):
            print(
                "ERROR: CSV must contain "
                "'server' and 'oracle_home' columns."
            )
            sys.exit(1)
        for row in reader:
            server = row["server"].strip()
            jdk_path = row["oracle_home"].strip()
            status, old_version, new_version, remarks = (
                upgrade_jdk(
                    server,
                    jdk_path
                )
            )
            results.append({
                "server": server,
                "jdk_path": jdk_path,
                "old_version": old_version,
                "new_version": new_version,
                "status": status,
                "remarks": remarks
            })
    # ========================================================
    # Write result CSV
    # ========================================================
    output_file = (
        f"jdk_upgrade_result_"
        f"{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
    )
    with open(
        output_file,
        "w",
        newline=""
    ) as csvfile:
        fieldnames = [
            "server",
            "jdk_path",
            "old_version",
            "new_version",
            "status",
            "remarks"
        ]
        writer = csv.DictWriter(
            csvfile,
            fieldnames=fieldnames
        )
        writer.writeheader()
        writer.writerows(results)
    print("")
    print("=" * 70)
    print("JDK UPGRADE COMPLETED")
    print("=" * 70)
    print(
        f"Result file: {output_file}"
    )

if __name__ == "__main__":
    main()

Update Java using python script (Python 2.6.6 compatible script)

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import csv
import tarfile
import shutil
import subprocess
from datetime import datetime

# ============================================================
# CONFIGURATION
# ============================================================
CSV_FILE = "/home/oracle/Desktop/jdk_servers.csv"
JDK_TAR = "/home/oracle/Desktop/jdk-8u501-linux-x64.tar.gz"
LOG_FILE = "/home/oracle/Desktop/jdk_upgrade.log"

# ============================================================
# Logging
# ============================================================
def log(message):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    msg = "[{0}] {1}".format(timestamp, message)
    print msg
    try:
        logfile = open(LOG_FILE, "a")
        logfile.write(msg + "\n")
        logfile.close()
    except Exception:
        pass

# ============================================================
# Execute local command
# ============================================================
def execute_command(command):
    log("Executing: {0}".format(command))
    process = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )
    output = process.communicate()[0]
    try:
        output = output.decode("utf-8")
    except Exception:
        pass
    output = output.strip()
    if output:
        log(output)
    return process.returncode, output

# ============================================================
# Check JDK tar file
# ============================================================
def check_jdk_tar():
    log("Checking JDK package...")
    if not os.path.isfile(JDK_TAR):
        log("ERROR: JDK package not found:")
        log(JDK_TAR)
        return False
    log("JDK package found: {0}".format(JDK_TAR))
    try:
        tar = tarfile.open(JDK_TAR, "r:gz")
        tar.close()
    except Exception as error:
        log(
            "ERROR: Invalid JDK tar file: {0}".format(error)
        )
        return False
    return True

# ============================================================
# Check current JDK
# ============================================================
def check_current_jdk(jdk_path):
    java_path = os.path.join(
        jdk_path,
        "bin",
        "java"
    )
    if not os.path.isfile(java_path):
        log(
            "ERROR: Java binary not found: {0}".format(
                java_path
            )
        )
        return False, "UNKNOWN"
    log("Current JDK version:")
    returncode, output = execute_command(
        "{0} -version".format(java_path)
    )
    if returncode != 0:
        return False, "UNKNOWN"
    return True, output

# ============================================================
# Get ownership
# ============================================================
def get_ownership(jdk_path):
    returncode, output = execute_command(
        "stat -c '%U:%G' '{0}'".format(jdk_path)
    )
    if returncode != 0:
        return None
    return output.strip()

# ============================================================
# Backup existing JDK
# ============================================================
def backup_jdk(jdk_path, backup_path):
    log("Backing up existing JDK...")
    if not os.path.isdir(jdk_path):
        log(
            "ERROR: JDK directory does not exist: {0}".format(
                jdk_path
            )
        )
        return False
    try:
        os.rename(
            jdk_path,
            backup_path
        )
        log(
            "JDK backup created: {0}".format(
                backup_path
            )
        )
        return True
    except Exception as error:
        log(
            "ERROR: Unable to backup JDK: {0}".format(
                error
            )
        )
        return False

# ============================================================
# Extract new JDK
# ============================================================
def extract_jdk(temp_path):
    log("Creating temporary directory:")
    log(temp_path)
    try:
        os.makedirs(temp_path)
    except Exception as error:
        log(
            "ERROR: Unable to create directory: {0}".format(
                error
            )
        )
        return False
    log("Extracting JDK...")
    try:
        tar = tarfile.open(
            JDK_TAR,
            "r:gz"
        )
        tar.extractall(
            temp_path
        )
        tar.close()
    except Exception as error:
        log(
            "ERROR: JDK extraction failed: {0}".format(
                error
            )
        )
        shutil.rmtree(
            temp_path,
            ignore_errors=True
        )
        return False
    # --------------------------------------------------------
    # Handle top-level directory inside tar
    # --------------------------------------------------------
    try:
        contents = os.listdir(
            temp_path
        )
        if len(contents) == 1:
            first_item = os.path.join(
                temp_path,
                contents[0]
            )
            if os.path.isdir(first_item):
                log(
                    "JDK archive contains top-level directory: {0}".format(
                        contents[0]
                    )
                )
                items = os.listdir(first_item)
                for item in items:
                    source = os.path.join(
                        first_item,
                        item
                    )
                    destination = os.path.join(
                        temp_path,
                        item
                    )
                    shutil.move(
                        source,
                        destination
                    )
                os.rmdir(
                    first_item
                )
    except Exception as error:
        log(
            "ERROR processing extracted JDK: {0}".format(
                error
            )
        )
        shutil.rmtree(
            temp_path,
            ignore_errors=True
        )
        return False
    return True

# ============================================================
# Verify extracted JDK BEFORE activation
# ============================================================
def verify_new_jdk(temp_path):
    java_path = os.path.join(
        temp_path,
        "bin",
        "java"
    )
    if not os.path.isfile(java_path):
        log(
            "ERROR: New Java binary not found."
        )
        return False, ""
    log("Checking NEW JDK before activation:")
    returncode, output = execute_command(
        "{0} -version".format(java_path)
    )
    if returncode != 0:
        log(
            "ERROR: New JDK Java execution failed."
        )
        return False, output
    # --------------------------------------------------------
    # Check that this is JDK 8u501
    # --------------------------------------------------------
    if "1.8.0_501" not in output:
        log(
            "WARNING: Expected JDK version 1.8.0_501."
        )
        log(
            "Actual version output:"
        )
        log(output)
        return False, output
    log(
        "New JDK version 1.8.0_501 verified."
    )
    return True, output

# ============================================================
# Set ownership
# ============================================================
def set_ownership(path, ownership):
    if not ownership:
        return True
    log(
        "Setting ownership {0} on {1}".format(
            ownership,
            path
        )
    )
    returncode, output = execute_command(
        "chown -R {0} '{1}'".format(
            ownership,
            path
        )
    )
    return returncode == 0

# ============================================================
# Activate JDK
# ============================================================
def activate_jdk(temp_path, jdk_path):
    log("Activating new JDK...")
    try:
        os.rename(
            temp_path,
            jdk_path
        )
    except Exception as error:
        log(
            "ERROR: Unable to activate new JDK: {0}".format(
                error
            )
        )
        return False
    log(
        "New JDK installed at: {0}".format(
            jdk_path
        )
    )
    return True

# ============================================================
# Rollback
# ============================================================
def rollback(
    jdk_path,
    backup_path,
    temp_path
):
    log("==============================================")
    log("STARTING ROLLBACK")
    log("==============================================")
    # Remove failed/new JDK
    if os.path.exists(jdk_path):
        failed_path = (
            jdk_path +
            "_failed_" +
            datetime.now().strftime(
                "%Y%m%d_%H%M%S"
            )
        )
        try:
            os.rename(
                jdk_path,
                failed_path
            )
            log(
                "Failed JDK moved to: {0}".format(
                    failed_path
                )
            )
        except Exception:
            shutil.rmtree(
                jdk_path,
                ignore_errors=True
            )
    # Remove temporary directory
    if os.path.exists(temp_path):
        shutil.rmtree(
            temp_path,
            ignore_errors=True
        )
    # Restore backup
    if os.path.exists(backup_path):
        try:
            os.rename(
                backup_path,
                jdk_path
            )
            log(
                "Old JDK restored successfully."
            )
        except Exception as error:
            log(
                "CRITICAL: Unable to restore backup: {0}".format(
                    error
                )
            )
            return False
    else:
        log(
            "CRITICAL: Backup JDK not found!"
        )
        return False
    return True

# ============================================================
# Upgrade one JDK
# ============================================================
def upgrade_jdk(server, jdk_path):
    log("")
    log("==============================================")
    log(
        "Processing server: {0}".format(server)
    )
    log(
        "JDK path: {0}".format(jdk_path)
    )
    log("==============================================")
    # --------------------------------------------------------
    # Validate JDK
    # --------------------------------------------------------
    valid, old_version = check_current_jdk(
        jdk_path
    )
    if not valid:
        return (
            "FAILED",
            old_version,
            "",
            "Current JDK validation failed"
        )
    # --------------------------------------------------------
    # Get ownership
    # --------------------------------------------------------
    ownership = get_ownership(
        jdk_path
    )
    if ownership:
        log(
            "Current ownership: {0}".format(
                ownership
            )
        )
    # --------------------------------------------------------
    # Timestamp
    # --------------------------------------------------------
    timestamp = datetime.now().strftime(
        "%Y%m%d_%H%M%S"
    )
    backup_path = (
        jdk_path +
        "_backup_" +
        timestamp
    )
    temp_path = (
        jdk_path +
        "_new_" +
        timestamp
    )
    # --------------------------------------------------------
    # Backup
    # --------------------------------------------------------
    if not backup_jdk(
        jdk_path,
        backup_path
    ):
        return (
            "FAILED",
            old_version,
            "",
            "JDK backup failed"
        )
    # --------------------------------------------------------
    # Extract
    # --------------------------------------------------------
    if not extract_jdk(
        temp_path
    ):
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            "",
            "JDK extraction failed"
        )
    # --------------------------------------------------------
    # Set ownership
    # --------------------------------------------------------
    if ownership:
        if not set_ownership(
            temp_path,
            ownership
        ):
            rollback(
                jdk_path,
                backup_path,
                temp_path
            )
            return (
                "ROLLED_BACK",
                old_version,
                "",
                "Ownership update failed"
            )
    # --------------------------------------------------------
    # Verify BEFORE activation
    # --------------------------------------------------------
    valid, new_version = verify_new_jdk(
        temp_path
    )
    if not valid:
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            new_version,
            "New JDK verification failed"
        )
    # --------------------------------------------------------
    # Activate
    # --------------------------------------------------------
    if not activate_jdk(
        temp_path,
        jdk_path
    ):
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            new_version,
            "JDK activation failed"
        )
    # --------------------------------------------------------
    # Final verification
    # --------------------------------------------------------
    valid, final_version = check_current_jdk(
        jdk_path
    )
    if not valid:
        rollback(
            jdk_path,
            backup_path,
            temp_path
        )
        return (
            "ROLLED_BACK",
            old_version,
            final_version,
            "Final Java verification failed"
        )
    log("==============================================")
    log("JDK UPGRADE SUCCESSFUL")
    log("==============================================")
    log(
        "Old JDK backup: {0}".format(
            backup_path
        )
    )
    log(
        "New JDK: {0}".format(
            jdk_path
        )
    )
    return (
        "SUCCESS",
        old_version,
        final_version,
        "Backup: {0}".format(backup_path)
    )

# ============================================================
# Main
# ============================================================
def main():
    log("==============================================")
    log("Oracle JDK 8u501 Upgrade")
    log("Python 2.6.6 Compatible Script")
    log("==============================================")
    # --------------------------------------------------------
    # Check CSV
    # --------------------------------------------------------
    if not os.path.isfile(CSV_FILE):
        log(
            "ERROR: CSV file not found: {0}".format(
                CSV_FILE
            )
        )
        sys.exit(1)
    # --------------------------------------------------------
    # Check JDK package
    # --------------------------------------------------------
    if not check_jdk_tar():
        sys.exit(1)
    results = []
    # --------------------------------------------------------
    # Read CSV
    # --------------------------------------------------------
    csvfile = open(
        CSV_FILE,
        "r"
    )
    reader = csv.DictReader(
        csvfile
    )
    for row in reader:
        server = row["server"].strip()
        jdk_path = row["oracle_home"].strip()
        status, old_version, new_version, remarks = (
            upgrade_jdk(
                server,
                jdk_path
            )
        )
        results.append({
            "server": server,
            "jdk_path": jdk_path,
            "old_version": old_version,
            "new_version": new_version,
            "status": status,
            "remarks": remarks
        })
    csvfile.close()
    # --------------------------------------------------------
    # Result CSV
    # --------------------------------------------------------
    result_file = (
        "/home/oracle/Desktop/"
        "jdk_upgrade_result_" +
        datetime.now().strftime(
            "%Y%m%d_%H%M%S"
        ) +
        ".csv"
    )
    outfile = open(
        result_file,
        "wb"
    )
    fieldnames = [
        "server",
        "jdk_path",
        "old_version",
        "new_version",
        "status",
        "remarks"
    ]
    writer = csv.DictWriter(
        outfile,
        fieldnames=fieldnames
    )
    writer.writeheader()
    for result in results:
        writer.writerow(
            result
        )
    outfile.close()
    log("")
    log("==============================================")
    log("JDK UPGRADE PROCESS COMPLETED")
    log("==============================================")
    log(
        "Result CSV: {0}".format(
            result_file
        )
    )

if __name__ == "__main__":
    main()

Sunday, August 9, 2026

AI-Powered Email Triage and Priority Classification Agent

## AI-Powered Email Triage and Priority Classification Agent


### Problem Statement


We spend significant time reading and sorting large volumes of emails every day. Important or urgent emails can easily get buried among routine notifications, FYI emails, reports, and low-priority communications. Additionally we also have important OEM alerts notification. We can classifiy these alerts notification based on its importance.


This manual email-triage process is repetitive, time-consuming, and can result in delayed responses to critical communications and alert notification.


### Proposed Solution


Implement an **AI-powered Email Triage Agent** that automatically analyzes incoming emails and categorizes them based on business priority:


* 🔴 **Critical** – Immediate attention required

* 🟠 **Important** – Action required within a defined timeframe

* 🟡 **FYI** – Information that may be useful

* ⚪ **Ignore/Low Priority** – Notifications or emails requiring no action


The AI agent would also generate a short summary of each important email and identify the **required action, deadline, sender, and key information**.


### Example


Instead of manually reviewing 2000+ emails, the user could receive:


**🔴 Critical – 3 emails**


* Production database issue – Action required immediately

* Security vulnerability – Remediation required by Friday

* Management escalation – Response required today


**🟠 Important – 12 emails**


* Pending approvals

* Project updates

* Team requests


**🟡 FYI – 45 emails**


* Automated reports

* Status notifications

* General communications


### Expected Benefits


* Reduce time spent manually reviewing emails

* Improve visibility of critical communications

* Reduce the risk of missing important requests

* Automatically identify required actions and deadlines

* Improve employee productivity

* Allow employees to focus on higher-value activities



### Success Metrics


The effectiveness of the solution could be measured through:


* Reduction in time spent on email triage

* Number of critical emails/alerts correctly identified

* Reduction in missed/overdue email actions

* Employee adoption and satisfaction

* Percentage of emails automatically classified


### Business Value

This solution can reduce repetitive administrative work and help employees focus more on **decision-making, problem-solving, and business-critical activities** rather than manually managing email volume.