hacktricks/network-services-pentesting/11211-memcache/memcache-commands.md
carlospolop 63bd9641c0 f
2023-06-05 20:33:24 +02:00

17 KiB

Comandos de Memcache

☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥

Hoja de trucos de comandos

De https://lzone.de/cheat-sheet/memcached****

Los comandos admitidos (los oficiales y algunos no oficiales) se documentan en el documento doc/protocol.txt.

Lamentablemente, la descripción de la sintaxis no es muy clara y un simple comando de ayuda que enumere los comandos existentes sería mucho mejor. Aquí hay una descripción general de los comandos que se pueden encontrar en la fuente (a partir del 19.08.2016):

Comando Descripción Ejemplo
get Lee un valor get mykey
set Establece una clave sin condiciones

set mykey <flags> <ttl> <size>

<p>Asegúrese de usar \r\n como saltos de línea al usar herramientas de CLI de Unix. Por ejemplo</p> printf "set mykey 0 60 4\r\ndata\r\n"

add Agrega una nueva clave add newkey 0 60 5
replace Sobrescribe una clave existente replace key 0 60 5
append Agrega datos a una clave existente append key 0 60 15
prepend Agrega datos al principio de una clave existente prepend key 0 60 15
incr Incrementa el valor de la clave numérica en la cantidad dada incr mykey 2
decr Decrementa el valor de la clave numérica en la cantidad dada decr mykey 5
delete Elimina una clave existente delete mykey
flush_all Invalida todos los elementos inmediatamente flush_all
flush_all Invalida todos los elementos en n segundos flush_all 900
stats Imprime estadísticas generales stats
Imprime estadísticas de memoria stats slabs
Imprime estadísticas de asignación de nivel superior stats malloc
Imprime información sobre elementos stats items
stats detail
stats sizes
Restablece los contadores de estadísticas stats reset
lru_crawler metadump Vuelca (la mayoría de) los metadatos de (todos) los elementos en la caché lru_crawler metadump all
version Imprime la versión del servidor. version
verbosity Aumenta el nivel de registro verbosity
quit Termina la sesión quit

Estadísticas de tráfico

Puede consultar las estadísticas de tráfico actuales utilizando el comando.

stats

Obtendrás una lista que muestra el número de conexiones, bytes de entrada/salida y mucho más.

Ejemplo de salida:

STAT pid 14868
STAT uptime 175931
STAT time 1220540125
STAT version 1.2.2
STAT pointer_size 32
STAT rusage_user 620.299700
STAT rusage_system 1545.703017
STAT curr_items 228
STAT total_items 779
STAT bytes 15525
STAT curr_connections 92
STAT total_connections 1740
STAT connection_structures 165
STAT cmd_get 7411
STAT cmd_set 28445156
STAT get_hits 5183
STAT get_misses 2228
STAT evictions 0
STAT bytes_read 2112768087
STAT bytes_written 1000038245
STAT limit_maxbytes 52428800
STAT threads 1
END

Estadísticas de Memoria

Puedes consultar las estadísticas actuales de memoria usando

stats slabs
# Memcache Commands

Memcache is a distributed memory caching system often used to speed up dynamic web applications by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.

## Basic Commands

### SET

The `SET` command is used to store a value in memcache. The syntax is as follows:

SET [noreply]\r\n \r\n


- `<key>`: The key under which to store the value.
- `<flags>`: An arbitrary 16-bit unsigned integer (written in decimal) that the server stores along with the data and sends back when the item is retrieved.
- `<exptime>`: The expiration time for the item, in seconds. If set to `0`, the item never expires.
- `<bytes>`: The number of bytes in the value.
- `[noreply]`: Optional parameter that tells the server not to send a response.

Example:

SET mykey 0 3600 5\r\nhello\r\n


This sets the value of `mykey` to `hello`, with no flags, an expiration time of 3600 seconds (1 hour), and a value length of 5 bytes.

### GET

The `GET` command is used to retrieve a value from memcache. The syntax is as follows:

GET \r\n


- `<key>`: The key of the value to retrieve.

Example:

GET mykey\r\n


This retrieves the value of `mykey`.

### DELETE

The `DELETE` command is used to delete a value from memcache. The syntax is as follows:

DELETE [noreply]\r\n


- `<key>`: The key of the value to delete.
- `[noreply]`: Optional parameter that tells the server not to send a response.

Example:

DELETE mykey\r\n


This deletes the value of `mykey`.

## Advanced Commands

### STATS

The `STATS` command is used to retrieve statistics about the memcache server. The syntax is as follows:

STATS [settings]\r\n


- `[settings]`: Optional parameter that specifies which statistics to retrieve. If not specified, all statistics are returned.

Example:

STATS\r\n


This retrieves all statistics.

### FLUSH_ALL

The `FLUSH_ALL` command is used to delete all values from memcache. The syntax is as follows:

FLUSH_ALL [delay]\r\n


- `[delay]`: Optional parameter that specifies the number of seconds to wait before flushing the cache. If not specified, the cache is flushed immediately.

Example:

FLUSH_ALL\r\n


This immediately flushes the cache.

### INCR/DECR

The `INCR` and `DECR` commands are used to increment or decrement a numeric value in memcache. The syntax is as follows:

INCR [noreply]\r\n DECR [noreply]\r\n


- `<key>`: The key of the value to increment or decrement.
- `<value>`: The amount to increment or decrement the value by.
- `[noreply]`: Optional parameter that tells the server not to send a response.

Example:

SET mycounter 0 0 1\r\n0\r\n INCR mycounter 1\r\n


This sets the value of `mycounter` to `0`, then increments it by `1`.

### APPEND/PREPEND

The `APPEND` and `PREPEND` commands are used to append or prepend data to an existing value in memcache. The syntax is as follows:

APPEND [noreply]\r\n \r\n PREPEND [noreply]\r\n \r\n


- `<key>`: The key of the value to append or prepend to.
- `<flags>`: An arbitrary 16-bit unsigned integer (written in decimal) that the server stores along with the data and sends back when the item is retrieved.
- `<exptime>`: The expiration time for the item, in seconds. If set to `0`, the item never expires.
- `<bytes>`: The number of bytes in the value to append or prepend.
- `[noreply]`: Optional parameter that tells the server not to send a response.

Example:

SET mykey 0 0 5\r\nworld\r\n APPEND mykey 0 0 1\r\n!\r\n


This sets the value of `mykey` to `world`, then appends `!` to it.

### CAS

The `CAS` command is used to check and set a value in memcache. The syntax is as follows:

CAS <cas_unique> [noreply]\r\n \r\n


- `<key>`: The key of the value to check and set.
- `<flags>`: An arbitrary 16-bit unsigned integer (written in decimal) that the server stores along with the data and sends back when the item is retrieved.
- `<exptime>`: The expiration time for the item, in seconds. If set to `0`, the item never expires.
- `<bytes>`: The number of bytes in the value.
- `<cas_unique>`: A unique value that identifies the current state of the value. If the value has been modified since it was last retrieved, the `CAS` command fails.
- `[noreply]`: Optional parameter that tells the server not to send a response.

Example:

SET mykey 0 0 5\r\nhello\r\n gets mykey\r\n

returns: VALUE mykey 0 5 123456\r\nhello\r\n

cas mykey 0 0 5 123456\r\nworld\r\n


This sets the value of `mykey` to `hello`, retrieves it with the `gets` command (which returns the value and its unique identifier), then sets it to `world` using the `cas` command (which only succeeds if the unique identifier matches the current state of the value).

STAT 1:chunk_size 80 STAT 1:chunks_per_page 13107 STAT 1:total_pages 1 STAT 1:total_chunks 13107 STAT 1:used_chunks 13106 STAT 1:free_chunks 1 STAT 1:free_chunks_end 12886 STAT 2:chunk_size 100 STAT 2:chunks_per_page 10485 STAT 2:total_pages 1 STAT 2:total_chunks 10485 STAT 2:used_chunks 10484 STAT 2:free_chunks 1 STAT 2:free_chunks_end 10477 [...] STAT active_slabs 3 STAT total_malloced 3145436 END

Si no estás seguro de si tienes suficiente memoria para tu instancia de memcached, siempre debes estar atento a los contadores de "evictions" proporcionados por el comando "stats". Si tienes suficiente memoria para la instancia, el contador de "evictions" debería ser 0 o al menos no estar aumentando.

#### ¿Qué claves se utilizan? <a href="#which-keys-are-used" id="which-keys-are-used"></a>

No hay una función incorporada para determinar directamente el conjunto actual de claves. Sin embargo, puedes usar el

stats items

Comando para determinar cuántas claves existen. 

stats items

stats items STAT items:1:number 220 STAT items:1:age 83095 STAT items:2:number 7 STAT items:2:age 1405 [...] END

Esto al menos ayuda a ver si se están utilizando claves. Para volcar los nombres de las claves desde un script PHP que ya accede a memcache, se puede utilizar el código PHP de [100days.de](http://100days.de/serendipity/archives/55-Dumping-MemcacheD-Content-Keys-with-PHP.html).