准备工作
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 subprocess
REDIS_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)
raise
def 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)
# 启动Redis
run_command(INSTALL_DIR + "/redis-server " + INSTALL_DIR + "/redis.conf", "启动Redis服务失败")
except Exception as e:
print "\033[31m错误:%s\033[0m" % str(e)
raise
def 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 == 0
except:
return False
def 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