当前位置: 首页 > news >正文

一个用Python编写的自动化安装openGauss数据库方法和代码(3)

这是一个用Python编写的在内网环境自动化安装openGauss5.0.0 数据库的方法和代码

这个 Python 脚本主要用于在特定环境下安装 openGauss5.0.0 x86_64 数据库。 首先,它会检查系统版本是否为 openEuler 22.03 系列版本。接着检查 ISO 文件是否存在并创建和挂载光盘目录,新建本地光盘 yum 源。还会检查 JDK 和 Python 版本是否符合要求,配置主机名、关闭防火墙和 SELinux、关闭 transparent_hugepage、设置 IPC 参数、调整内核参数并使其生效。然后创建用户和目录,设置用户密码和权限,修改资源限制,设置 core_pattern,安装依赖包,检查 openGauss 文件是否存在以及文件架构和完整性,解压数据库文件并生成集群配置文件。执行预安装脚本并给 omm 用户授权后,提示用户切换至 omm 用户进行数据库安装及后续的用户和数据库创建操作,最后提及数据库应用软件安装可参考软件配置说明书。整个过程涵盖了多个关键的系统配置和数据库安装步骤,确保 openGauss 数据库能够在满足特定条件的环境中顺利安装和使用。

运行的效果如下:

具代码如下:

import os
import re
import subprocess
import socket
import hashlib


def check_system_version():


    result = subprocess.run(['cat', '/etc/openEuler-release'], stdout=subprocess.PIPE)
    version = result.stdout.decode('utf-8').strip()
    print(f"\n\n1、当前版本是:{version}")
    if "openEuler" in version and "22.03" in version:
        print(f"系统版本符合安装要求。")
        return True
    else:
        print(f"系统版本不对,要求安装openEuler 22.03系列版本,程序终止。")
        return False

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_file():


    iso_filename = get_filename_from_os_info()
    iso_path = os.path.join("/mnt/iso", iso_filename)
    print(f"\n\n2、正在检查:{iso_path} 文件是否存在")
    if os.path.exists(iso_path):
        print(f"存在{iso_path} 此文件,通过检查。")
        return True
    else:
        print(f"不存在 {iso_filename} 此文件,程序终止。")
        return False  

def create_cdrom_directory():
    if not os.path.exists('/mnt/cdrom'):
        os.makedirs('/mnt/cdrom')
    print("\n\n3、 /mnt/cdrom 目录创建成功。")
    return True

def mount_iso_file():


    iso_filename = get_filename_from_os_info()
    iso_path = os.path.join("/mnt/iso", iso_filename)
    mount_path = '/mnt/cdrom'
    cmd = f"mount -o loop '{iso_path}' '{mount_path}'"
    result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output = result.stderr.decode('utf-8')
    print(f"\n\n4、正在执行 {cmd}挂载命令")
    print(f"\n {output}") 
    if "已经挂载" in output or "is already mounted" in output or "mount: /mnt/cdrom: WARNING: source write-protected, mounted read-only." in output:
        print("ISO 文件已经挂载成功,继续执行。")
        return True
    else:
        print(f"挂载 ISO 文件失败,错误信息:{output},程序终止。")
        return False


def create_yum_source():


    print("\n\n5、新建本地光盘 yum 源")
    repo_dir = '/etc/yum.repos.d'

    repo_files = [f for f in os.listdir(repo_dir) if f.endswith('.repo')]
    if not repo_files:
        raise FileNotFoundError("No.repo files found in /etc/yum.repos.d")

    # 处理第一个.repo 文件
    current_repo_file = os.path.join(repo_dir, repo_files[0])

    # 读取文件内容
    with open(current_repo_file, 'r') as f:
        content = f.read()

    # 使用正则表达式匹配 baseurl 和 gpgkey
    baseurl_match = re.search(r'baseurl=(.*)', content)
    gpgkey_match = re.search(r'gpgkey=(.*)', content)

    baseurl = baseurl_match.group(1).strip() if baseurl_match else None
    gpgkey = gpgkey_match.group(1).strip() if gpgkey_match else None

    if not baseurl or not gpgkey:
        raise ValueError("baseurl or gpgkey not found in the current.repo file")

    # 备份原文件
    backup_file = current_repo_file + '.bak'
    os.rename(current_repo_file, backup_file)

    # 定义新的内容
    new_content = [
        '[openEuler]\n',
        'name=openEuler\n',
        f'baseurl=file:///mnt/cdrom\n',
        'enabled=1\n',
        'gpgcheck=1\n',
        f'gpgkey=file:///mnt/cdrom/{os.path.basename(gpgkey)}'
    ]

    # 写入新文件
    new_repo_file = os.path.join(repo_dir, 'local.repo')
    with open(new_repo_file, 'w') as f:
        f.write('\n'.join(new_content))

    print(f"New repo file '{new_repo_file}' created successfully.")

    # 使 yum 源生效
    try:
        subprocess.run(['yum', 'clean', 'all'])
        subprocess.run(['yum', 'makecache'])
        return True
    except Exception as e:
        print(f"使 yum 源生效时出现错误:{e}")
        return False

def check_jdk_version():


    try:
        result = subprocess.run(['java', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = result.stderr.decode('utf-8')
        print(f"\n\n6、正在检查java版本,当前版本是:\n\n{output}")
        lines = output.split('\n')
        first_line = lines[0] if lines else ""
        if "openjdk version" in first_line and "1.8" in first_line:
            print("JDK 版本检查通过。")
            return True
        else:
            print(f"JDK 版本不对,应为包含 'openjdk version' 和 '1.8' 的版本,当前版本为:{first_line},程序终止。")
            return False
    except Exception as e:
        print(f"检查 JDK 版本时出现错误:{e}")
        return False

def check_python_version():


    try:
        result = subprocess.run(['python3', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = result.stdout.decode('utf-8')
        print(f"\n\n7、正在检查 python 版本,当前版本为:{output}")

        if "Python" in output and "3.9" in output:
            print("Python 版本检查通过。")
            return True
        else:
            print(f"Python 版本不对,应为包含 'Python' 和 '3.9' 的版本,当前版本为:{output},程序终止。")
            return False
    except Exception as e:
        print(f"检查 Python 版本时出现错误:{e}")
        return False


def configure_hostname():


    # 获取当前主机名
    hostname = socket.gethostname()
    print(f"\n\n8、正在修改和配置当前主机名为{hostname}的服务器")

    response = input("是否使用 'cgqyw_server' 作为主机名?(yes/no):")
    if response.lower() == "yes":
        new_hostname = "cgqyw_server"
    else:
        while True:
            new_hostname = input("请输入新的主机名:")
            confirmation = input(f"你输入的新主机名是 '{new_hostname}',请再次确认:")
            if new_hostname == confirmation:
                break
            else:
                print("两次输入不一致,请重新输入。")

    try:
        # 使用 subprocess 模块运行命令来修改主机名
        subprocess.run(['hostnamectl', 'set-hostname', new_hostname], check=True)
        # 更新当前主机名变量
        hostname = new_hostname
        print(f"主机名已修改为 {new_hostname}。")
    except subprocess.CalledProcessError as e:
        # 如果修改主机名的命令执行出错,打印错误信息并返回 False
        print(f"修改主机名时出现错误:{e}")
        return False

    # 通过当前主机名获取 IP 地址
    ip_address = socket.gethostbyname(hostname)

    # 检查 /etc/hosts 文件中是否已经存在'{ip_address} {hostname}'
    with open('/etc/hosts', 'r') as f:
        # 以只读方式打开 /etc/hosts 文件,将内容按行读取并存入 content 列表
        content = f.readlines()
    with open('/etc/hosts', 'w') as f:
        # 以写入方式打开 /etc/hosts 文件
        for line in content:
            # 如果当前行不包含特定的 IP 地址,则将该行重新写入文件,目的是删除包含该 IP 地址的旧行
            if ip_address not in line:
                f.write(line)

    # 如果更新后的 content 列表中有包含'{ip_address} {hostname}'的行
    if f"{ip_address} {hostname}" in content:
        print(f"'{ip_address} {hostname}' 已存在于 /etc/hosts 文件中,无需重复写入。")
        return True

    try:
        with open('/etc/hosts', 'a') as f:
            # 以追加模式打开文件,将'{ip_address} {hostname}'写入文件
            f.write(f"{ip_address} {hostname}\n")
        print(f"成功将 '{ip_address} {hostname}' 添加到 /etc/hosts 文件。")
        return True
    except Exception as e:
        # 如果写入文件时出现错误,打印错误信息并返回 False
        print(f"配置主机名到 /etc/hosts 文件时出现错误:{e}")
        return False

def close_firewall_and_selinux():


    try:
        print("\n\n9、关闭防火墙和设置 Selinux")

        # 停止防火墙
        firewall_stop_result = subprocess.run(['systemctl', 'stop', 'firewalld.service'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if firewall_stop_result.returncode == 0:
            print("防火墙已停止。")
        else:
            print(f"停止防火墙时出现错误:{firewall_stop_result.stderr.decode('utf-8')}")
            return False

        # 禁用防火墙
        firewall_disable_result = subprocess.run(['systemctl', 'disable', 'firewalld.service'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if firewall_disable_result.returncode == 0:
            print("防火墙已禁用。")
        else:
            print(f"禁用防火墙时出现错误:{firewall_disable_result.stderr.decode('utf-8')}")
            return False

        # 修改 SELinux 配置文件
        selinux_config_result = subprocess.run(['sed', '-i', 's/SELINUX=enforcing/SELINUX=disabled/', '/etc/selinux/config'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if selinux_config_result.returncode == 0:
            print("SELinux 已设置为 disabled。")
        else:
            print(f"修改 SELinux 配置文件时出现错误:{selinux_config_result.stderr.decode('utf-8')}")
            return False

        # 即时生效 SELinux 设置
        setenforce_result = subprocess.run(['setenforce', '0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if setenforce_result.returncode == 0:
            print("SELinux 即时生效设置完成。")
            return True
        else:
            print(f"即时生效 SELinux 设置时出现错误:{setenforce_result.stderr.decode('utf-8')}")
            return False

    except Exception as e:
        print(f"关闭防火墙和 SELinux 时出现错误:{e}")
        return False

def close_transparent_hugepage():


    print("\n\n10、关闭 transparent_hugepage")
    grub_config = '/etc/default/grub'
    try:
        with open(grub_config, 'r') as f:
            content = f.read()
        if 'transparent_hugepage=never' not in content:
            with open(grub_config, 'a') as f:
                f.write('transparent_hugepage=never\n')
            print("已向 /etc/default/grub 文件写入 transparent_hugepage=never。")
        result = subprocess.run(['grub2-mkconfig', '-o', '/boot/grub2/grub.cfg'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = result.stdout.decode('utf-8') if result.stdout else result.stderr.decode('utf-8')
        print(output)
        print("grub 配置更新完成、transparent_hugepage=never已写入/etc/default/grub文件中。")
        return True
    except Exception as e:
        print(f"关闭 transparent_hugepage 时出现错误:{e}")
        return False


def set_ipc_parameters():


    # 打印提示信息,表示正在进行 IPC 参数设置
    print("\n\n11、IPC 参数设置 ")
    # 定义两个文件路径,分别是 logind 的配置文件和服务文件路径
    logind_conf = '/etc/systemd/logind.conf'
    service_file = '/usr/lib/systemd/system/systemd-logind.service'

    # 定义一个内部函数,用于检查并写入参数到文件中
    def write_if_not_exists(file_path):
        # 如果文件存在
        if os.path.exists(file_path):
            # 以只读方式打开文件,读取内容
            with open(file_path, 'r') as f:
                content = f.read()
            # 如果文件内容中不包含'RemoveIPC=no'且不包含'#RemoveIPC=no'
            if 'RemoveIPC=no' not in content and '#RemoveIPC=no' not in content:
                # 以追加方式打开文件,写入'RemoveIPC=no'
                with open(file_path, 'a') as f:
                    f.write('RemoveIPC=no\n')
                # 打印提示信息,表示向特定文件写入了参数
                print(f"已向 {file_path} 文件写入 RemoveIPC=no。")
            elif '#RemoveIPC=no' in content:
                # 如果存在被注释的参数,将其修改为有效的参数
                new_content = content.replace('#RemoveIPC=no', 'RemoveIPC=no')
                with open(file_path, 'w') as f:
                    f.write(new_content)
                print(f"已在 {file_path} 文件中将注释的参数变为有效参数。")
        else:
            # 如果文件不存在,打印提示信息
            print(f"{file_path} 文件不存在。")

    # 遍历两个文件路径列表
    for file_path in [logind_conf, service_file]:
        # 对每个文件路径调用内部函数进行检查和写入操作
        write_if_not_exists(file_path)

    try:
        # 运行 systemctl daemon-reload 命令,重新加载 systemd 守护进程
        subprocess.run(['systemctl', 'daemon-reload'])
        print("systemd 守护进程重新加载。")
        # 运行 systemctl stop systemd-logind 命令,停止 systemd-logind 服务
        subprocess.run(['systemctl', 'stop', 'systemd-logind'])
        print("systemd-logind 已停止。")
        # 运行 systemctl start systemd-logind 命令,启动 systemd-logind 服务
        subprocess.run(['systemctl', 'start', 'systemd-logind'])
        print("systemd-logind 已启动。")
        # 如果所有操作都成功,返回 True
        return True
    except Exception as e:
        # 如果出现任何异常,打印错误信息并返回 False
        print(f"设置 IPC 参数时出现错误:{e}")
        return False


def adjust_kernel_parameters():


    print("\n\n12、内核参数调整")
    kernel_params = [
        'net.ipv4.tcp_max_tw_buckets=10000',
        'net.ipv4.tcp_tw_reuse = 1',
        'net.ipv4.tcp_keepalive_probes=9',
        'net.ipv4.tcp_keepalive_intvl=30',
        'net.ipv4.tcp_retries1 = 5',
        'net.ipv4.tcp_syn_retries = 5',
        'net.ipv4.tcp_synack_retries = 5',
        'net.ipv4.tcp_retries2 = 12',
        'net.ipv4.tcp_rmem = 8192 250000 16777216',
        'vm.overcommit_memory = 0',
        'net.ipv4.tcp_wmem = 8192 250000 16777216',
        'net.core.wmem_max = 21299200',
        'net.core.rmem_max = 21299200',
        'net.core.wmem_default = 21299200',
        'net.core.rmem_default = 21299200',
        'net.ipv4.tcp_syncookies = 1',
        'net.ipv4.tcp_sack = 1',
        'net.ipv4.tcp_timestamps = 1',
        'fs.aio-max-nr=1048576',
        'fs.file-max= 76724600',
        'kernel.sem = 4096 2048000 32 32768',
        'kernel.shmall = 1048576',
        'kernel.shmmax = 4294967296',
        'kernel.shmmni = 8192',
        'net.core.netdev_max_backlog = 65535',
        'net.core.somaxconn = 65535',
        'net.ipv4.tcp_fin_timeout = 60',
        'vm.swappiness = 0',
        'net.ipv4.ip_local_port_range = 26000 65535',
        'fs.nr_open = 20480000'
    ]
    sysctl_conf = '/etc/sysctl.conf'
    try:
        with open(sysctl_conf, 'r') as f:
            content = f.read()
        for param in kernel_params:
            if param not in content:
                with open(sysctl_conf, 'a') as f:
                    f.write(f'{param}\n')
                print(f"已向 /etc/sysctl.conf 文件写入 {param}。")
        return True
    except Exception as e:
        print(f"调整内核参数时出现错误:{e}")
        return False


def make_kernel_config_effective():


    try:
        subprocess.run(['sysctl', '-p'])
        print("\n\n13、已执行sysctl -p命令,内核配置已生效。")
        return True
    except Exception as e:
        print(f"\n\n13、使内核配置生效时出现错误:{e}")
        return False

def create_user_and_directory():


    print("\n\n14、创建用户和组")      
    try:
        if subprocess.run(['getent', 'group', 'dbgrp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0:
            group_info = subprocess.run(['getent', 'group', 'dbgrp'], stdout=subprocess.PIPE).stdout.decode('utf-8')
            group_id = group_info.split(':')[2]
            confirm = input(f"已存在 dbgrp 组,组 ID 为 {group_id}。是否终止程序执行(y/n):")
            if confirm.lower() == 'y':
                print("请参考以下步骤修改或删除 dbgrb 组:")
                print("修改组:groupmod -g <new_gid> dbgrp")
                print("删除组:groupdel dbgrp")
                return False
        subprocess.run(['groupadd', '-g', '1000', 'dbgrp'])
        print("dbgrp 组创建成功。")
        if subprocess.run(['getent', 'passwd', 'omm'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0:
            user_info = subprocess.run(['getent', 'passwd', 'omm'], stdout=subprocess.PIPE).stdout.decode('utf-8')
            user_id = user_info.split(':')[2]
            confirm = input(f"已存在 omm 用户,用户 ID 为 {user_id}。是否终止程序执行(y/n):")
            if confirm.lower() == 'y':
                print("请参考以下步骤修改或删除 omm 用户及家目录:")
                print("修改用户:usermod -u <new_uid> omm")
                print("删除用户及家目录:userdel -r omm")
                return False
        subprocess.run(['useradd', '-u', '1000', 'omm', '-g', 'dbgrp'])
        print("omm 用户创建成功。")
        return True
    except Exception as e:
        print(f"创建用户和目录时出现错误:{e}")
        return False

def set_omm_password():


    password = "Omm@1000"
    print("\n\n15、创建 omm 用户密码,创建目录和授权")
    try:
        subprocess.run(f'echo "{password}" | passwd omm --stdin', shell=True)
        print("omm 用户密码设置成功。")
        subprocess.run(['mkdir', '-p', '/data/{openGauss,backup,archive_wals,core_pattern}'])
        print("/data 下相关目录创建openGauss,backup,archive_wals,core_pattern成功。")
        subprocess.run(['chmod', '700', '/data/{openGauss,backup,archive_wals,core_pattern}'])
        print("/data 下相关目录权限设置openGauss,backup,archive_wals,core_pattern成功。")
        subprocess.run(['chown', '-R', 'omm:dbgrp', '/data/{openGauss,backup,archive_wals,core_pattern}'])
        print("/data 下相关目录所有者设置openGauss,backup,archive_wals,core_pattern成功。")
        subprocess.run(['mkdir', '-p', '/opt/openGauss'])
        print("/opt/openGauss 目录创建成功。")
        subprocess.run(['chown', 'omm:dbgrp', '-R', '/opt/openGauss/'])
        print("/opt/openGauss 目录所有者设置成功。")
        subprocess.run(['chmod', '755', '/opt/openGauss/'])
        print("/opt/openGauss 目录权限设置成功。")
        print(f"omm 用户密码为:{password},请记录此信息。")
        return True
    except Exception as e:
        print(f"设置 omm 用户密码和授权时出现错误:{e}")
        return False

def modify_resource_limits():


    limits_conf = '/etc/security/limits.conf'
    print(f"\n\n16、修改资源限制文件:{limits_conf}")
    try:
        with open(limits_conf, 'r') as f:
            content = f.read()
        limits = [
            'omm soft nproc unlimited',
            'omm hard nproc unlimited',
            'omm soft nofile 102400',
            'omm hard nofile 102400',
            'omm soft stack unlimited',
            'omm hard stack unlimited',
            'omm soft core unlimited',
            'omm hard core unlimited',
            'omm soft memlock unlimited'
        ]
        for limit in limits:
            if limit not in content:
                with open(limits_conf, 'a') as f:
                    f.write(f'{limit}\n')
                print(f"已向 /etc/security/limits.conf 文件写入 {limit}。")
            else:
                print(f"在/etc/security/limits.conf 文件已有 {limit}此限制。")
        return True
    except Exception as e:
        print(f"修改资源限制时出现错误:{e}")
        return False

def set_core_pattern():


    core_pattern_path = '/proc/sys/kernel/core_pattern'
    print(f"\n\n17、core_pattern 设置{core_pattern_path} ")
    try:
        with open(core_pattern_path, 'r') as f:
            current_pattern = f.read().strip()
        if current_pattern!= '/data/core_pattern/core-%e-%p-%t':
            subprocess.run(f'echo "/data/core_pattern/core-%e-%p-%t" > {core_pattern_path}', shell=True)
            print("已设置 core_pattern为:/data/core_pattern/core-%e-%p-%t")
        else:
            print("已配置 core_pattern为:/data/core_pattern/core-%e-%p-%t,无需修改")
        return True
    except Exception as e:
        print(f"设置 core_pattern 时出现错误:{e}")
        return False

def install_dependencies():


    print(f"\n\n18、安装依赖包:。")
    packages_group1 = ['zlib-devel', 'libaio', 'libuuid', 'readline-devel', 'krb5-libs']
    packages_group2 = ['libicu', 'libxslt', 'tcl', 'perl', 'openldap', 'pam', 'openssl-devel', 'libxml2', 'python3']
    print(f"{packages_group1}")
    print(f"{packages_group2}")
    try:
        # 安装第一组依赖包
        subprocess.run(['dnf', 'install', '-y'] + packages_group1)
        # 安装第二组依赖包
        subprocess.run(['dnf', 'install', '-y'] + packages_group2)

        failed_packages = []
        for package in packages_group1 + packages_group2:
            check_result = subprocess.run(['rpm', '-q', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if check_result.returncode!= 0:
                failed_packages.append(package)

        if failed_packages:
            print("安装失败的依赖包有:", ', '.join(failed_packages))
        else:
            print("依赖包安装成功。")
        return True

    except Exception as e:
        print(f"安装依赖包时出现错误:{e}")
        return False

def check_openGauss_file_in_directory():


    openGauss_path = '/opt/openGauss/openGauss-5.0.0-openEuler-64bit-all.tar.gz'
    print(f"\n\n19、正在检查{openGauss_path}文件是否存在?")  
    if not os.path.exists(openGauss_path):
        print(f"未找到{openGauss_path}文件,请先上传文件至/opt/openGauss/目录,程序终止。")
        return False
    print(f"通过检查{openGauss_path},文件存在。")
    return True


def check_sha256(file_path, expected_sha256):


    sha256_hash = hashlib.sha256()
    with open(file_path, "rb") as f:
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
    calculated_sha256 = sha256_hash.hexdigest()
    return calculated_sha256 == expected_sha256

def check_file_architecture():


    # 此处可添加检查文件架构和完整性的逻辑,目前假设总是通过检查
    print("\n\n20、文件架构和完整性检查通过。")
 
    file_path = "/opt/openGauss/openGauss-5.0.0-openEuler-64bit-all.tar.gz"
    expected_sha256 = "eba32db3b0fb70020b7d7da754d898994fbf5f3e8f5f94c35e2fb29898cdc1f4"

    is_valid = check_sha256(file_path, expected_sha256)
    if is_valid:
         print("该文件为openGauss-5.0.0-openEuler-64bit-all.tar.gz x86_64架构企业版文件。")
         print(f"与官方sha256值一致:{expected_sha256},通过校验。")
         return True
    else:
         print(f"未知{file_path}文件。")
         print(f"与官方sha256值不一致,sha256应为:{expected_sha256},校验不通过")         
         return False
 

def extract_files():


    print("\n\n21、解压数据库文件!\n\n")
    try:
        os.chdir('/opt/openGauss/')
        os.system('pwd')
        os.system('tar -zxf openGauss-5.0.0-openEuler-64bit-all.tar.gz')
        print(" openGauss-5.0.0-openEuler-64bit-all.tar.gz 文件解压成功。")
        os.system('tar -zxf openGauss-5.0.0-openEuler-64bit-om.tar.gz')
        print("\n openGauss-5.0.0-openEuler-64bit-om.tar.gz  文件解压成功。\n")
        return True
    except Exception as e:
        print(f"\n\nopenGauss-5.0.0-openEuler-64bit-all.tar.gz文件解压时出现错误:{e}\n\n")
        return False

def generate_cluster_config():


    hostname = socket.gethostname()
    ip_address = socket.gethostbyname(socket.gethostname())
    print(f"\n\n22、正在为ip地址为:{ip_address}主机名为:{hostname}生成集群配置文件")
    config_content = f"""<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
    <!-- openGauss整体信息 -->
    <CLUSTER>
        <!-- 数据库名称 -->
        <PARAM name="clusterName" value="openGauss"/>
        <!-- 数据库节点名称(hostname) -->
        <PARAM name="nodeNames" value="{hostname}"/>
        <!-- 数据库安装目录-->
        <PARAM name="gaussdbAppPath" value="/opt/openGauss/app"/>
        <!-- 日志目录-->
        <PARAM name="gaussdbLogPath" value="/var/log/omm" />
        <!-- 临时文件目录-->
        <PARAM name="tmpMppdbPath" value="/opt/openGauss/tmp"/>
        <!-- 数据库工具目录-->
        <PARAM name="gaussdbToolPath" value="/opt/openGauss/install/om"/>
        <!-- 数据库core文件目录-->
        <PARAM name="corePath" value="/opt/openGauss/corefile"/>
        <!-- 节点IP,与数据库节点名称列表一一对应 -->
        <PARAM name="backIp1s" value="{ip_address}"/>
    </CLUSTER>
    <!-- 每台服务器上的节点部署信息 -->
    <DEVICELIST>
        <!-- 节点1上的部署信息 -->
        <DEVICE sn="{hostname}">
            <!-- 节点1的主机名称 -->
            <PARAM name="name" value="{hostname}"/>
            <!-- 节点1所在的AZ及AZ优先级 -->
            <PARAM name="azName" value="AZ1"/>
            <PARAM name="azPriority" value="1"/>
            <!-- 节点1的IP,如果服务器只有一个网卡可用,将backIP1和sshIP1配置成同一个IP -->
            <PARAM name="backIp1" value="{ip_address}"/>
            <PARAM name="sshIp1" value="{ip_address}"/>
            <!--dbnode-->
            <PARAM name="dataNum" value="1"/>
            <PARAM name="dataPortBase" value="15400"/>
            <PARAM name="dataNode1" value="/data/openGauss"/>
            <PARAM name="dataNode1_syncNum" value="0"/>
        </DEVICE>
    </DEVICELIST>
</ROOT>"""
    config_file_path = '/home/omm/cluster_config.xml'
    if not os.path.exists('/home/omm'):
        os.makedirs('/home/omm')
    with open(config_file_path, 'w') as f:
        f.write(config_content)
    print(f"集群配置文件生成成功,路径为:{config_file_path}。\n")
    return True

def execute_preinstall_script():


    print("\n23、root 用户执行预安装脚本\n")
    choice = input("是否执行预安装脚本:./gs_preinstall -U omm -G dbgrp -X /home/omm/cluster_config.xml?(输入 yes 或 no)")
    if choice.lower() == 'yes':
        print("\n正在执行,请稍候……\n")
        print("出现该英文提示Are you sure you want to create the user[omm] (yes/no)? 输入 no 后回车")
        try:
            os.chdir('/opt/openGauss/script/')
            os.system('./gs_preinstall -U omm -G dbgrp -X /home/omm/cluster_config.xml')
            return True
        except Exception as e:
            print(f"给 root 用户执行预安装脚本时出现错误:{e}")
            return False
    else:
        print("用户取消执行预安装脚本。")
        return False


def grant_omm_permissions():


    print("\n24、root给 omm 用户授权:")
    try:
        subprocess.run(['chown', 'omm:dbgrp', '-R', '/opt/openGauss/'])
        print("给 omm 授权成功。\n\n")
        return True
    except Exception as e:
        print(f"给 omm 授权时出现错误:{e}\n\n")
        return False
# 下面为主程序
if __name__ == '__main__':
    if not check_system_version():
        exit(1)
    if not check_iso_file():
        exit(1)
 

完整程序,可通过下边链接下载代码

主程序

下载测试通过的代码:

https://download.csdn.net/download/cgqyw/89914032 


http://www.mrgr.cn/news/56511.html

相关文章:

  • OAK相机的标定流程更新与优化通知
  • 十一、【智能体】一键生成文章!秒懂!一篇搞定智能体工作流核心操作,轻松上手!效率飙升N倍!
  • pymobiledevice3使用介绍(安装、常用命令、访问iOS沙盒目录)
  • CROss PlatformS (CROPS) 与 Docker
  • 未来人工智能:技术、趋势与挑战
  • 【ArcGIS Pro实操第五期】全局及局部空间插值:GPI、LPI、IDW等
  • 六、Linux 服务器搭建专业指南
  • 人工智能技术的应用前景与生活工作变革
  • C++类和对象 - 下【匿名对象,友元,static成员】
  • 五、Shell 脚本编程:从基础至实用实例
  • ST7789读取ID错误新思路(以STC32G为例)
  • 架构师之路-学渣到学霸历程-28
  • Python程序设计 内置函数 日志模块
  • 数据类型的通用操作
  • Standard_Matrix
  • libaom-all-intra参数说明
  • 渗透测试实战—教育攻防演练中突破网络隔离
  • 【Vulnhub靶场】Kioptrix Level 5
  • python-docx -- 对比两个表格的行数据
  • JavaScript字符串的常用方法有哪些?
  • 第五部分 数组和String类
  • spring-boot(4)
  • 计算机组成原理一句话
  • 云原生后端开发之道
  • 【华为路由】OSPF多区域配置
  • c++日常积累