1.创建脚本
vi scan_get_all_keys.sh
#!/bin/bash
redisbase='/usr/local/bin'
##定义使用说明
usage(){
echo -e " 33[31m脚本功能: 33[0m"
echo -e " 用于扫描redis实例中所有的key"
echo -e " "
echo -e " 33[31m示例如下: 33[0m"
echo -e " sh scan_get_all_keys.sh redis_node_6577 6577 0 1000 'match *MP001_1'"
echo -e " "
echo -e " 33[31m注意事项: 33[0m"
echo -e " 1. 只能用于redis 2.8及以上版本,因为只有这些版本支持scan命令"
echo -e " 2. 第三个参数表示每次scan的key个数,不要超过300"
}
##参数判断
if [ "$1"x = x ] || ([ -n "$1" ] && [ "$2"x = x ] )
then
usage
exit
fi
i=0
host=$1
port=$2
db=$3
num=$4
#matchpattern为需要模糊匹配的表达式参数
matchpattern=$5
tmp_file=${host}_${port}_tmp.txt
result_file=${host}_${port}.txt
rm -rf ${result_file} >> /dev/null
touch ${result_file} >> /dev/null
if [ 1 ]
then
${redisbase}/redis-cli -h $host -p $port -n ${db} scan ${i} ${matchpattern} count $num > ${tmp_file}
i=`head -1 ${tmp_file}`
counts_tmp=`cat ${tmp_file}|wc -l`
counts=$(( $counts_tmp - 1 ))
tail -${counts} ${tmp_file} >> ${result_file}
fi
while [ $i -ne 0 ]
do
${redisbase}/redis-cli -h $host -p $port -n ${db} scan ${i} ${matchpattern} count $num > ${tmp_file}
i=`head -1 ${tmp_file}`
counts_tmp=`cat ${tmp_file}|wc -l`
counts=$(( $counts_tmp - 1 ))
tail -${counts} ${tmp_file} >> ${result_file}
done
rm -rf $tmp_file
sed '/^$/d' ${result_file} > final_${result_file}
2.执行脚本
---放在空目录下执行
sudo sh scan_get_all_keys.sh 10.1.1.1 6379 8 300 'match plus-gat:REQ_IP_LIMITED_*'
redis IP:10.1.1.1
端口:6379
库序列号:8
keys 个数:300
like 扫描:'match like 那部分*'