import subprocess
import sys
import osdef disable_selinux():"""禁用SELinux"""try:subprocess.run(["sed", "-i", "s/SELINUX=enforcing/SELINUX=disabled/g", "/etc/selinux/config"],check=True)print("SELinux已禁用")except subprocess.CalledProcessError as e:print(f"禁用SELinux失败: {e}",file=sys.stderr)sys.exit(1)def disable_firewall():"""禁用防火墙"""try:subprocess.run(["systemctl", "stop", "firewalld"],check=True)subprocess.run(["systemctl", "disable", "firewalld"],check=True)print("防火墙已禁用")except subprocess.CalledProcessError as e:print(f"禁用防火墙失败: {e}",file=sys.stderr)sys.exit(1)def install_mysql():"""安装MySQL数据库"""try:subprocess.run(["yum", "install", "-y", "epel-release"],check=True)subprocess.run(["yum", "install", "-y", "wget", "gcc", "libxml2", "libxml2-devel", "net-snmp", "net-snmp-devel", "libevent", "libevent-devel", "curl", "curl-devel", "java-devel", "yum-utils"],check=True)subprocess.run(["wget", "https://repo.mysql.com/mysql80-community-release-el7-3.noarch.rpm"],check=True)subprocess.run(["rpm", "-ivh", "mysql80-community-release-el7-3.noarch.rpm", "--nodeps", "--force"],check=True)subprocess.run(["yum", "clean", "all"],check=True)subprocess.run(["yum", "makecache"],check=True)subprocess.run(["yum", "install", "-y", "mysql-community-server", "--nogpgcheck"],check=True)subprocess.run(["systemctl", "start", "mysqld"],check=True)subprocess.run(["systemctl", "enable", "mysqld"],check=True) print("MySQL数据库安装完成")except subprocess.CalledProcessError as e:print(f"安装MySQL数据库失败: {e}",file=sys.stderr)sys.exit(1)def configure_mysql():"""配置MySQL数据库"""try:temp_password_output = subprocess.check_output(["grep", "temporary password", "/var/log/mysqld.log"]).decode()temp_password = temp_password_output.split("root@localhost:")[1].strip()print(f"MySQL数据库临时密码: {temp_password}")subprocess.run(["mysql", "-uroot", f"-p{temp_password}", "--connect-expired-password", "-e", "ALTER USER 'root'@'localhost' IDENTIFIED BY 'Admin@123456';"],check=True)print("MySQL数据库密码修改完成")subprocess.run(["mysql", "-uroot", "-pAdmin@123456", "-e", "use mysql;update user set Host='%' where User='root';flush privileges;"],check=True)print("MySQL远程访问配置完成")except subprocess.CalledProcessError as e:print(f"配置MySQL数据库失败: {e}",file=sys.stderr)sys.exit(1)if __name__ == "__main__":if os.geteuid() != 0:print("请使用root用户运行此脚本",file=sys.stderr)sys.exit(1)print("开始禁用SELinux和firewalld")disable_selinux()disable_firewall()print("开始安装MySQL")install_mysql()configure_mysql()print("MySQL安装和配置完成")
