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

devtools/2024/10/24 17:36:45/

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

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

未完,待续


http://www.ppmy.cn/devtools/128476.html

相关文章

npm install node-sass安装失败

需求:搭建前端开发环境时,npm install报错,错误提示安装node_modules时,node-sass依赖包安装失败,网上找了好久解决方法,大家提示采用淘宝源等方式安装,都失败了了,尝试了很久终于找…

AWS账号的费用结构与使用指南

亚马逊网络服务(AWS)是全球领先的云计算平台,提供各种服务,包括计算、存储、数据库、人工智能等。对于许多新用户来说,在创建AWS账号时,常常会有一个疑问:AWS账号需要费用吗?我们九河…

Maven 的使用:在 IDEA 中配置 Maven 的超详细步骤

一、概述 记录时间 [2024-10-20] Maven 用来管理 Java 项目中的依赖。 为什么要进行 Maven 配置呢?IDEA 默认选择内置的 Maven 仓库,但是不好用。 本文所讲述的 Maven 配置可以说是超详细的! 从下载 Maven 这个东西开始,修改它…

【数据结构】栈和队列经典题目

目录 1.有效的括号【链接】 代码实现 2.用队列实现栈【链接】 代码实现 3.用栈实现队列 ​编辑 代码实现 4.循环队列(数组实现)【链接】 代码实现 1.有效的括号【链接】 题目描述: 给定一个只包括 (,),{&…

Ubuntu18.04:no module named ‘apt_pkg‘(python3.6升级为3.7要注意的事情)

这里写目录标题 没生效的尝试有用的解决附:升级方法 一直提示没有名叫apt_pkg的模块(no module named ‘apt_pkg’) 是python没装好?还是python没指向python3? 没生效的尝试 有用的解决 下面这个目录里,文件名带有36m的改为37m的…

mysql查询id不在列表中的记录

推荐学习文档 golang应用级os框架,欢迎stargolang应用级os框架使用案例,欢迎star案例:基于golang开发的一款超有个性的旅游计划app经历golang实战大纲golang优秀开发常用开源库汇总想学习更多golang知识,这里有免费的golang学习笔…

Ruby 从入门到精通:学习之旅与资源推荐

一、引言 在编程语言的广阔世界中,Ruby 以其简洁、优雅和强大的特性脱颖而出。它是一种动态、面向对象的脚本语言,具有丰富的表达能力和灵活性,适用于各种应用场景,从 Web 开发到自动化脚本,从数据处理到游戏开发。本…

记录一个vue比较奇怪的bug,在父组件使用定时器会影响子组件的深度监听属性

需求:在大屏项目的页面有个时间需要用到定时器,结果影响子组件的参数 实现:将定时器抽成一个单独的组件 描述:定时器没有单独抽出来的时候,professionalECharts组件接受的参数schoolId一直在变(通过watch发…