Skip to content

Instantly share code, notes, and snippets.

@RHAF05
Forked from josegonzalez/redis_migrate.py
Last active July 15, 2020 00:57
Show Gist options
  • Save RHAF05/620075bf176be4c270100678bc4681c6 to your computer and use it in GitHub Desktop.
Save RHAF05/620075bf176be4c270100678bc4681c6 to your computer and use it in GitHub Desktop.
A simple script to migrate all keys from one Redis to another
#!/usr/bin/env python
import argparse
import redis
def connect_redis(conn_dict):
conn = redis.StrictRedis(host=conn_dict['host'],
port=conn_dict['port'],
db=conn_dict['db'],
password=conn_dict['passw'])
return conn
def conn_string_type(string):
format = '<host>:<port>/<db>*<pass>'
try:
host, portdb = string.split(':')
port, db = portdb.split('/')
db, passw = db.split('*')
db = int(db)
except ValueError:
raise argparse.ArgumentTypeError('incorrect format, should be: %s' % format)
return {'host': host,
'port': port,
'db': db,
'passw': passw}
def migrate_redis(source, destination):
src = connect_redis(source)
dst = connect_redis(destination)
for key in src.keys('*'):
ttl = src.ttl(key)
# we handle TTL command returning -1 (no expire) or -2 (no key)
if ttl < 0:
ttl = 0
print "Dumping key: %s" % key
value = src.dump(key)
print "Restoring key: %s" % key
try:
value = value if value is not None else ''
dst.restore(key, ttl * 1000, value, replace=True)
except redis.exceptions.ResponseError:
print "Failed to restore key: %s" % key
pass
return
def run():
parser = argparse.ArgumentParser()
parser.add_argument('source', type=conn_string_type)
parser.add_argument('destination', type=conn_string_type)
options = parser.parse_args()
migrate_redis(options.source, options.destination)
if __name__ == '__main__':
run()
@RHAF05
Copy link
Author

RHAF05 commented Jul 13, 2020

using:

python migrate.py 'HostSource:portSource/DBSource*passSource' 'HostDesination:PortDestination/DBDestination*PassDestination'

Example:
python migrate.py '192.168.1.122:6379/0*123' '192.168.1.120:6379/0*'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment