【docker】命令行获取docker远程仓库镜像列表

命令行获取docker远程仓库镜像列表

获取思路

通过curl获取镜像tagjson串,解析后得到${image}:${tag}的格式

curl获取示例

1
2
# curl [:-s] ${API}/${image}/tags
curl https://registry.hub.docker.com/v1/repositories/nginx/tags

docker-search.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/bin/bash
API="https://registry.hub.docker.com/v1/repositories"
DEFAULT_NAME="nginx"
DEFAULT_TIMEOUT=3

function Usage(){
cat << HELP

Usage: docker-search NAME[:TAG]

docker-search list all tags for docker image on a remote registry.

Example:
docker-search (default nginx)
docker-search nginx
docker-search nginx:1.15.8
docker search nginx | docker-search
docker search nginx | docker-search :1.15.8
echo nginx | docker-search
echo nginx | docker-search :1.15.8
HELP
}

ARG=$1
if [[ "$ARG" =~ "-h" ]];then
Usage
exit 0
fi

function ParseJson(){
tr -d '[\[\]" ]' | tr '}' '\n' | awk -F: -v image=$1 '{if(NR!=NF && $3 != ""){printf("%s:%s\n",image,$3)}}'
}

function GetTags(){
image=$1
tag=$2
ret=`curl -s ${API}/${image}/tags`
tag_list=`echo $ret | ParseJson ${image}`
if [ -z "$tag" ];then
echo -e "$tag_list"
else
echo -e "$tag_list" | grep -w "$tag"
fi
}

if [ -z $ARG ] || [[ ${ARG:0:1} == ":" ]];then
if [ -x /usr/bin/timeout ];then
images=`timeout $DEFAULT_TIMEOUT` awk '{print $1}' | grep -v "NAME" || echo $DEFAULT_NAME
else
images=`awk '{print $1}' | grep -v "NAME"`
fi
else
images=`echo $ARG | awk -F: '{print $1}'`
fi
tag=`echo $ARG | awk -F: '{print $2}'`

for i in ${images}
do
tags=`GetTags $i $tag`
count=`echo $tags | wc -w`
if [[ $count -gt 0 ]];then
echo -e "IMAGE [$i:$tag]:"
echo -e "$tags"
echo
fi
done

使用

1
2
3
4
5
# 获取帮助
$ docker-search --help

# 查询ngnix
$ docker-search nginx