##### 遍历脚本
```
import redis
# Redis连接配置
redis_host = 'localhost'
redis_port = 6379
redis_db = 168
redis_password = '123' # 如果有密码取消注释
# 导出文件
output_file = 'redis_export_keys.txt'
# 多个前缀
prefix_list = ['bb_pu:u*', 'bb_pu:p*', 'bb_qu:u*', 'bb_qu:q*']
# 建立 Redis 连接
r = redis.StrictRedis(
host=redis_host,
port=redis_port,
db=redis_db,
password=redis_password, # 如有密码
decode_responses=True
)
# 开始导出
with open(output_file, 'w', encoding='utf-8') as f:
total_written = 0
for prefix in prefix_list:
print(f"🔍 开始扫描前缀:{prefix}")
cursor = 0
while True:
cursor, keys = r.scan(cursor=cursor, match=prefix, count=10)
for key in keys:
ttl = r.ttl(key)
if ttl == -1: # 不过期
f.write(key + '\n')
total_written += 1
if total_written % 10000 == 0:
print(f"已写入 {total_written} 个 key...")
if cursor == 0:
break
print(f"✅ 前缀 {prefix} 扫描完成")
print(f"\n🎉 导出完成,共写入 {total_written} 个不过期 key 到:{output_file}")
```
##### 删除key
```
# encoding: utf-8
import redis,sys
# 连接到 Redis
r = redis.Redis(host='xxxxxxx', port=6379, password="xxxxx", db=0)
# 传入外部变量: 文件名
del_fname=sys.argv[1]
# 读取文件
with open(del_fname, 'r') as file:
for line in file:
# 去除换行符
line = line.strip()
r.unlink(line)
# 关闭文件
file.close()
```




