编写Python 自动化安装openGauss 数据库方法和代码 (2)

不断调试,更新,你若有兴趣一起参与

#!/usr/bin/env python3

import os

import subprocess

import platform

import re

import socket

1、检查操作系统版本

def check_system_version():

try:

with open('/etc/os-release', 'r') as f:

for line in f:

if line.startswith('ID='):

id_value = line.strip().split('=')[1].strip('"')

elif line.startswith('VERSION_ID='):

version_id_value = line.strip().split('=')[1].strip('"')

if id_value == 'openEuler' and version_id_value == '22.03':

print("This system is openEuler 22.03.")

else:

print("This system is not openEuler 22.03.")

exit(1)

except Exception as e:

print(f"An error occurred: {e}")

exit(1)

2、检查是否存在当前系统对应的系统ISO文件

def get_filename_from_os_info():

os_release_path = "/etc/os-release"

if os.path.exists(os_release_path):

with open(os_release_path, "r") as f:

for line in f:

if line.startswith("NAME="):

name = line.split("=")[1].strip().replace('"', '')

elif line.startswith("VERSION="):

version = line.split("=")[1].strip().replace('"', '')

把( )替换成 - 号

version = version.replace('(', '-').replace(')', '')

去除版本号中的空格

version = version.replace(' ', '')

else:

return None

uname_output = subprocess.check_output(["uname", "-m"]).decode().strip()

return f"{name}-{version}-{uname_output}-DVD.ISO"

def check_iso_exists():

iso_filename = get_filename_from_os_info()

iso_path = os.path.join("/mnt/iso", iso_filename)

if os.path.exists(iso_path):

print(f"你已上传文件,在/mnt/iso目录下存在操作系统ISO文件:{iso_filename} 。")

else:

print(f"请检查,在/mnt/iso目录下不存在操作系统ISO文件:{iso_filename}。")

exit(1)

def create_cdrom_dir():

cdrom_path = "/mnt/cdrom"

if not os.path.exists(cdrom_path):

os.makedirs(cdrom_path)

def mount_iso():

iso_path = f"/mnt/iso/openEuler-{version}-{platform.machine()}-dvd.iso"

cdrom_path = "/mnt/cdrom"

try:

subprocess.run(["mount", "-o", "loop", iso_path, cdrom_path], check=True)

except subprocess.CalledProcessError:

print("挂载ISO文件失败。程序终止。")

exit(1)

def setup_yum_source():

with open("/etc/yum.repos.d/cdrom.repo", "w") as f:

f.write("""[cdrom]

name=cdrom

baseurl=file:///mnt/cdrom/

enabled=1

gpgcheck=0

""")

subprocess.run(["yum", "clean", "all"], check=True)

def install_jdk():

subprocess.run(["yum", "install", "java-1.8.0-openjdk"], check=True)

jdk_version = subprocess.run(["java", "-version"], capture_output=True, text=True).stdout

if "1.8." not in jdk_version:

print("JDK版本不正确,应为1.8.xx。程序终止。")

exit(1)

def install_python3():

subprocess.run(["yum", "install", "python39"], check=True)

python_version = subprocess.run(["python3", "--version"], capture_output=True, text=True).stdout.strip()

if "3.9." not in python_version:

print("Python3版本不正确,应为3.9.x。程序终止。")

exit(1)

def check_gauss_files():

if not os.path.exists("/opt/openGauss-5.0.0-x86_64.tar.gz"):

print("Gauss数据库文件不存在,应为/opt/openGauss-5.0.0-x86_64.tar.gz。程序终止。")

exit(1)

def set_hostname():

default_hostname = "ogserver"

new_hostname = input(f"请将主机名改为{default_hostname},确认吗? (y/n): ").strip().lower()

if new_hostname != 'y' and not new_hostname:

new_hostname = input("请输入正确的主机名: ").strip()

subprocess.run(["hostnamectl", "set-hostname", new_hostname], check=True)

def check_ip_and_mac():

ip_address = socket.gethostbyname(socket.gethostname())

confirm_ip = input(f"当前服务器联网IP地址为{ip_address},是否作为对外服务IP地址? (y/n): ").strip().lower()

if confirm_ip != 'y':

print("IP地址不正确,程序终止。")

exit(1)

hostname = socket.gethostname()

mac_address = subprocess.run(["ip", "-o", "-4", "addr", "list", f"{hostname}"], capture_output=True, text=True).stdout

mac_address = re.search(r'link/ether ([0-9a-fA-F:]+)', mac_address).group(1)

confirm_mac = input(f"当前IP的MAC地址为{mac_address},是否为安全设备备案的MAC地址? (y/n): ").strip().lower()

if confirm_mac != 'y':

print("MAC地址不正确,程序终止。")

exit(1)

def configure_hosts():

hostname = socket.gethostname()

ip_address = socket.gethostbyname(hostname)

hosts_path = "/etc/hosts"

with open(hosts_path, "r") as f:

hosts_content = f.readlines()

new_entry = f"{ip_address} {hostname}\n"

if new_entry not in hosts_content:

with open(hosts_path, "a") as f:

f.write(new_entry)

def disable_firewall_and_selinux():

services = ["firewalld"]

for service in services:

subprocess.run(["systemctl", "stop", service], check=True)

subprocess.run(["systemctl", "disable", service], check=True)

selinux_config = "/etc/selinux/config"

with open(selinux_config, "r") as f:

lines = f.readlines()

new_lines = []

for line in lines:

if line.startswith("SELINUX="):

line = "SELINUX=disabled\n"

new_lines.append(line)

with open(selinux_config, "w") as f:

f.writelines(new_lines)

try:

subprocess.run(["setenforce", "0"], check=True)

except subprocess.CalledProcessError:

print("设置SELinux为disabled失败。请手动检查。")

def disable_transparent_hugepage():

grub_config = "/etc/default/grub"

with open(grub_config, "r") as f:

lines = f.readlines()

new_lines = []

for line in lines:

if "transparent_hugepage" not in line:

new_lines.append(line)

elif "transparent_hugepage=never" not in line:

new_lines.append("transparent_hugepage=never\n")

with open(grub_config, "w") as f:

f.writelines(new_lines)

subprocess.run(["grub2-mkconfig", "-o", "/boot/grub2/grub.cfg"], check=True)

if name == "main":

check_system_version()

check_iso_exists()

create_cdrom_dir()

mount_iso()

setup_yum_source()

install_jdk()

install_python3()

check_gauss_files()

set_hostname()

check_ip_and_mac()

configure_hosts()

disable_firewall_and_selinux()

disable_transparent_hugepage()

print("openGauss 5.0.0 x86架构数据库安装前的准备工作已完成。")

未完,待续

相关推荐
种时光的人1 分钟前
2025蓝桥省赛c++B组第二场题解
开发语言·c++·算法
FAREWELL000759 分钟前
C#进阶学习(十三)C#中的预处理器指令
开发语言·学习·c#·预处理指令
xiaohanbao0914 分钟前
day6 python数据可视化
python·学习·信息可视化·pandas
my_realmy36 分钟前
SQL 查询进阶:WHERE 子句与连接查询详解
java·开发语言·数据库·sql
szial44 分钟前
如何在 Conda 环境中降级 Python 版本:详细指南
python·conda
oioihoii1 小时前
C++23 新特性:令声明顺序决定非静态类数据成员的布局 (P1847R4)
java·开发语言·c++23
captain_keating1 小时前
使用matplotlib绘制Raincloud图/云雨图/柱状图/小提琴图
python·matplotlib
leolee181 小时前
PyInstaller 打包pc
python
站大爷IP1 小时前
Python frozenset 集合详解:不可变集合的终极指南
python
一点.点1 小时前
李沐动手深度学习(pycharm中运行笔记)——05.线性代数
pytorch·笔记·python·深度学习·pycharm·动手深度学习