编写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架构数据库安装前的准备工作已完成。")

未完,待续

相关推荐
cooldream2009几秒前
使用 uv 管理 Python 虚拟环境:现代 Python 开发的高效实践
python·uv·mcp
zhangfeng11338 分钟前
国家超算中心 系统自带模型 和pytorch 和cuda版本
人工智能·pytorch·python
m0_7381207215 分钟前
渗透测试基础——黑盒测试下的Web漏洞挖掘与利用解析(二)
服务器·前端·python·网络协议·安全·网络安全
basketball61620 分钟前
Go 语言从入门到进阶:5. 玩转Go函数
开发语言·后端·golang
玫幽倩23 分钟前
2025FIC取证决赛wp(手机取证)
python·智能手机·手机·电子取证·计算机取证·手机取证·fic
多彩电脑25 分钟前
Kivy如何自定义事件
开发语言·python
java_cj25 分钟前
LangChain初入门 - 简化LLM开发难度的利器
开发语言·python·langchain
sleven fung29 分钟前
llama-cpp-python 本地部署入门
开发语言·python·算法·llama
头歌实践平台30 分钟前
C++面向对象 - 运算符重载的应用
开发语言·c++·算法
福大大架构师每日一题31 分钟前
rust 1.96.0 更新:语言、编译器、Cargo、Rustdoc、兼容性全面升级,必看完整解读
android·开发语言·rust