#!/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()
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()
No comments:
Post a Comment