67.redis批量写入ip地址脚本

发布时间 2023-12-06 14:47:22作者: leiuk
#要使用Python脚本连接到Redis主机、选择数据库、并执行设置操作,你可以使用redis库。请确保在运行脚本之前安装了该库(可以通过运行pip install redis安装)。

import redis
import re

# Redis连接信息
redis_host = 'hostname'
redis_port = 6379
redis_password = 'passwd'
redis_db = 5  # 选择数据库5

# 读取文本文件中的IP地址
file_path = '1.txt'  # 替换为你的文件路径
ip_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b')

# 连接到Redis服务器
redis_client = redis.StrictRedis(
    host=redis_host, port=redis_port, password=redis_password, db=redis_db, decode_responses=True
)

# 选择数据库
redis_client.select(redis_db)

# 读取文本文件中的IP地址
with open(file_path, 'r') as file:
    content = file.read()
    ip_addresses = re.findall(ip_pattern, content)

# 执行SET命令将每个IP地址加入到Redis中
for ip_address in ip_addresses:
    key = f'whiteKey:{ip_address}'
    redis_client.set(key, 1)

print(f"成功将 {len(ip_addresses)} 个IP地址添加到Redis数据库5中,并设置对应的whiteKey。")

如果提示
ModuleNotFoundError: No module named 'redis'
请安装redis
pip install redis
pip3 install redis