準備工作
1. 下載 Redis 8 安裝包
# Redis 8.0.0 示例(請替換為實際版本)
http://download.redis.io/releases/redis-8.0.0.tar.gz
一、腳本內容:
#!/usr/bin/python
# -*- coding: UTF-8 -*-import os
import time
import shutil
import subprocessREDIS_VERSION = "redis-8.0.0"
REDIS_TAR = REDIS_VERSION + ".tar.gz" # 改為Python 2兼容的字符串拼接
INSTALL_DIR = "/usr/local/redis"
BACKUP_DIR = os.path.join(INSTALL_DIR, "backups")
BACKUP_SCRIPT = os.path.join(INSTALL_DIR, "backup_redis.sh")def run_command(cmd, error_msg):"""執行命令并檢查結果,失敗時拋出異常(Python 2兼容版本)"""ret = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)output, error = ret.communicate()if ret.returncode != 0:raise Exception("%s (code: %d)\nError output: %s" % (error_msg, ret.returncode, error))def install_dependencies():"""安裝依賴"""try:run_command("rpm -Uvh --force --nodeps ./gcc/*.rpm", "依賴安裝失敗,請檢查gcc RPM包是否存在")except Exception as e:print "\033[31m錯誤:%s\033[0m" % str(e)raisedef install_redis():"""安裝Redis"""try:# 解壓if not os.path.exists(REDIS_TAR):raise Exception("Redis安裝包 %s 不存在" % REDIS_TAR)run_command("tar -zxvf " + REDIS_TAR, "解壓Redis失敗")# 編譯安裝os.chdir(REDIS_VERSION)run_command("make MALLOC=libc", "編譯Redis失敗")os.chdir("src")run_command("make install", "安裝Redis失敗")# 創建安裝目錄if os.path.exists(INSTALL_DIR):shutil.rmtree(INSTALL_DIR)os.makedirs(INSTALL_DIR)# 復制文件run_command("cp -R ./* " + INSTALL_DIR, "復制文件失敗")run_command("cp ../redis.conf " + INSTALL_DIR + "/", "復制配置文件失敗")# 修改配置conf_path = os.path.join(INSTALL_DIR, "redis.conf")with open(conf_path, "r") as f:content = f.read()content = content.replace("daemonize no", "daemonize yes")content = content.replace("bind 127.0.0.1 -::1", "bind 0.0.0.0")content = content.replace("# requirepass foobared", "requirepass 123456")with open(conf_path, "w") as f:f.write(content)# 啟動Redisrun_command(INSTALL_DIR + "/redis-server " + INSTALL_DIR + "/redis.conf", "啟動Redis服務失敗")except Exception as e:print "\033[31m錯誤:%s\033[0m" % str(e)raisedef setup_backup():"""配置數據備份策略(Python 2兼容版本)"""try:# 創建備份目錄if not os.path.exists(BACKUP_DIR):os.makedirs(BACKUP_DIR)# 創建備份腳本backup_script = """#!/bin/bash
BACKUP_DIR="%s"
DATE=$(date +%%Y%%m%%d_%%H%%M%%S)
# 備份RDB文件
cp %s/dump.rdb "$BACKUP_DIR/dump_$DATE.rdb" 2>/dev/null || echo "無RDB文件可備份"
# 刪除7天前的備份
find "$BACKUP_DIR" -name 'dump_*.rdb' -mtime +7 -exec rm -f {} \\;
""" % (BACKUP_DIR, INSTALL_DIR)with open(BACKUP_SCRIPT, "w") as f:f.write(backup_script)os.chmod(BACKUP_SCRIPT, 0755)# 添加cron任務cron_job = "0 2 * * * root " + BACKUP_SCRIPT + "\n"with open("/etc/cron.d/redis_backup", "w") as f:f.write(cron_job)except Exception as e:print "\033[33m警告:備份配置失敗 - %s\033[0m" % str(e)def detect_service():"""檢測服務是否運行(Python 2兼容版本)"""try:time.sleep(3)result = subprocess.Popen("pgrep -f redis-server", shell=True, stdout=subprocess.PIPE)output = result.communicate()[0]return result.returncode == 0except:return Falsedef prompt_success():"""安裝成功提示(Python 2兼容版本)"""print """\033[5;32;40m 恭喜%s安裝成功! \033[0m使用前注意:Redis已啟動,端口:6379,綁定所有網卡,密碼:123456防火墻需放行6379端口,臨時關閉防火墻命令:systemctl stop firewalld安裝路徑:%s啟動命令:%s/redis-server %s/redis.conf配置文件:%s/redis.conf數據備份策略:每日凌晨2點自動備份RDB文件至:%s保留最近7天的備份,舊備份自動刪除備份腳本位置:%s""" % (REDIS_VERSION, INSTALL_DIR, INSTALL_DIR, INSTALL_DIR, INSTALL_DIR, BACKUP_DIR, BACKUP_SCRIPT)def prompt_fail():"""安裝失敗提示(Python 2兼容版本)"""print """\033[5;31;40m 安裝失敗,請檢查錯誤信息! \033[0m"""if __name__ == '__main__':try:install_dependencies()install_redis()setup_backup()if detect_service():prompt_success()else:print "\033[31m錯誤:Redis進程未檢測到,可能啟動失敗\033[0m"prompt_fail()except Exception as e:prompt_fail()
二、執行步驟
[root@myoracle redis8]# chmod +x redis8.py
[root@myoracle redis8]# ./redis8.py