Skip to content

Instantly share code, notes, and snippets.

@chriskk
Forked from bkimble/gist:1365005
Created July 24, 2012 08:55
Show Gist options
  • Save chriskk/3168935 to your computer and use it in GitHub Desktop.
Save chriskk/3168935 to your computer and use it in GitHub Desktop.
Command line tool to list memcache keys and to get the value of a specific key
#!/usr/bin/env ruby
require 'net/telnet'
require 'lib/trollop'
opts = Trollop::options do
banner <<-EOS
Command line tool to list memcache keys and to get the value of a specific key
Usage:
memcache [options]
where [options] are:
EOS
opt :get, "Get the value for a specific key", :type => :string
opt :host, "Set the Host", :default => "localhost", :type => :string
opt :list_keys, "List local memcached keys"
opt :port, "Set the port number", :default => 11211, :type => :integer
opt :timeout, "Set the timeout in seconds", :default => 3, :type => :integer
end
Trollop::die :timeout, "must be greater than 0" if opts[:timeout] == 0
localhost = Net::Telnet::new("Host" => opts[:host], "Port" => opts[:port], "Timeout" => opts[:timeout])
if opts[:get]
puts
puts "Value for key #{opts[:get]}: "
localhost.cmd("String" => "get #{opts[:get]}", "Match" => /^END/) { |c| puts c }
puts
end
if opts[:list_keys]
cache_dump_limit = 100
slab_ids = []
localhost.cmd("String" => "stats items", "Match" => /^END/) do |c|
matches = c.scan(/STAT items:(\d+):/)
slab_ids = matches.flatten.uniq
end
puts
puts "Expires At\t\t\t\tCache Key"
puts '-'* 80
slab_ids.each do |slab_id|
localhost.cmd("String" => "stats cachedump #{slab_id} #{cache_dump_limit}", "Match" =>
/^END/) do |c|
matches = c.scan(/^ITEM (.+?) \[(\d+) b; (\d+) s\]$/).each do |key_data|
(cache_key, bytes, expires_time) = key_data
humanized_expires_time = Time.at(expires_time.to_i).to_s
puts "[#{humanized_expires_time}]\t#{cache_key}"
end
end
end
puts
end
localhost.close
@alex-techligtenment
Copy link

Hey thanks!
This looks very interesting but got this err:

/bin/memcachekval:4:in `require': no such file to load -- lib/trollop (LoadError)
from /bin/memcachekval:4

and I dont know any ruby so it could be a silly error but still... if you can help with it will be great,

Cheers!

@reubent
Copy link

reubent commented Mar 14, 2013

You will need to install Trollop - http://trollop.rubyforge.org/

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