Skip to content

Instantly share code, notes, and snippets.

@shiplu
Last active December 9, 2016 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiplu/e8b95151e0f632306accb59ff58b5da2 to your computer and use it in GitHub Desktop.
Save shiplu/e8b95151e0f632306accb59ff58b5da2 to your computer and use it in GitHub Desktop.
Scan for keys with pattern using SCAN
"""
Scan for keys with a pattern in Redis. It uses SCAN command instead of KEYS.
KEYS is dangereros as it locks down the whole server. Hence the need for SCAN
Usage:
python scanpattern.py redis.myserver.com 'KEY-PATTERN-TO-SEARCH'
"""
import redis
import time
import sys
host = sys.argv[1]
pattern = sys.argv[2]
SPEED = 10
r = redis.StrictRedis(host=host)
cursor = 0
while True:
cursor, result = r.scan(cursor=cursor, match=pattern)
if result:
print >> sys.stderr, "Result found!"
print "\n".join(result)
break
if cursor == 0:
print >> sys.stderr, "All keys explored"
break
else:
print >> sys.stderr, "Trying new cursor = %s" % cursor
time.sleep(1/SPEED)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment