Skip to content

Instantly share code, notes, and snippets.

@thepatrick
Last active March 9, 2018 05:32
Show Gist options
  • Save thepatrick/b15adf40b0fe02c3266d3f824e57b317 to your computer and use it in GitHub Desktop.
Save thepatrick/b15adf40b0fe02c3266d3f824e57b317 to your computer and use it in GitHub Desktop.
Just want to run INFO against a redis server? Don't have redis-cli installed? Think installing it will take longer than writing a python script to run the same command? Don't care if INFO is longer than ~1018 characters? Then this is the python for you!
#!/usr/bin/python
# Thanks to https://gist.github.com/glynnbird/89ad23c2f5e218d067f0de76150598e0 for gen_redis_proto()
import sys
import socket
def gen_redis_proto(cmd):
# break the command by spaces to get the number of tokens
tokens = cmd.split(" ")
proto = "*" + str(len(tokens)) + "\r\n"
for token in tokens:
proto += "$" + str(len(token)) + "\r\n"
proto += token + "\r\n"
return proto
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((sys.argv[1], int(sys.argv[2])))
s.send(gen_redis_proto("INFO"))
data = s.recv(BUFFER_SIZE)
s.close()
# does this look like a redis response?
if len(data) < 1:
raise Exception("0 length response from redis server")
if data[0] != '$':
raise Exception("Unexpected redis response, does not start with $")
new_line = data.index("\n")
data_length = int(data[1:new_line])
if new_line + 1 + data_length > BUFFER_SIZE:
data_length = BUFFER_SIZE - 1 - new_line
data_response = data[new_line+1:new_line+1+data_length]
print data_response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment