Redis Shell脚本十六进制键

问题描述

创建了一个cron作业,该作业删除Redis中的特定键。

示例键:“ \ xac \ xed \ x00 \ x05t \ x00 \ x15test”

使用bash和redis-cli,似乎无法正确解析和删除具有十六进制值的键:

Code below:


 host=${1:-}
port=${2:-6379}
database=${3:-0}
pattern=${4:-"Test"}

cursor=-1
keys=""

echo "Starting to delete"
while [ $cursor -ne 0 ]; do
  if [ $cursor -eq -1 ]
  then
    cursor=0
  fi

  reply=`redis-cli -h $host -p $port SCAN $cursor MATCH $pattern`
  cursor=`expr "$reply" : '\([0-9]*[0-9 ]\)'`
  keys=${reply##[0-9]*[0-9 ]}
  echo "$keys"
  redis-cli -h $host -p $port DEL $keys
done

解决方法

切换客户端以删除密钥。编写了一个小的python脚本

#!/usr/bin/env python3

import redis

redis_host = "localhost"
redis_port = 6379
redis_password = ""


def hello_redis():
    """Example Hello Redis Program"""
    print("Start of script")
    # step 3: create the Redis Connection object
    try:
        r = redis.StrictRedis(host=redis_host,port=redis_port,password=redis_password)
 
        for key in r.scan_iter("*key*"):
            print(key)
            r.delete(key)    
   
    except Exception as e:
        print(e)

    print("Terminating script")
if __name__ == '__main__':
    hello_redis()