一、接口测试命令

api接口文档:https://github.com/goharbor/harbor/blob/release-1.7.0/docs/swagger.yaml

登录接口测试

curl  --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/users/current"

1)查看所属项目的信息。根据项目 id 查找

备注:{project_id} 为项目 id
curl -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/projects/{project_id}"

curl  -u  "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/projects/1"

项目id的查看方式:https://192.168.44.10/harbor/projects/1/repositories

实际操作中

[root@harbar-master ~]# curl  -u  "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/projects/1"
curl: (51) Unable to communicate securely with peer: requested domain name does not match the server's certificate.
[root@harbar-master ~]# curl --insecure  -u  "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/projects/1"
{
  "project_id": 1,
  "owner_id": 1,
  "name": "library",
  "creation_time": "2019-11-24T14:58:43.684818Z",
  "update_time": "2019-11-24T14:58:43.684818Z",
  "deleted": false,
  "owner_name": "",
  "togglable": true,
  "current_user_role_id": 1,
  "repo_count": 1,
  "chart_count": 0,
  "metadata": {
    "public": "true"
  }
}[root@harbar-master ~]# 

 --insecure  忽略不安全的证书

2)查找出所有的项目

[root@harbar-master ~]# curl --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/projects"
[
  {
    "project_id": 1,
    "owner_id": 1,
    "name": "library",
    "creation_time": "2019-11-24T14:58:43.684818Z",
    "update_time": "2019-11-24T14:58:43.684818Z",
    "deleted": false,
    "owner_name": "",
    "togglable": true,
    "current_user_role_id": 1,
    "repo_count": 1,
    "chart_count": 0,
    "metadata": {
      "public": "true"
    }
  },
  {
    "project_id": 2,
    "owner_id": 1,
    "name": "codo",
    "creation_time": "2019-11-28T16:30:19Z",
    "update_time": "2019-11-28T16:30:19Z",
    "deleted": false,
    "owner_name": "",
    "togglable": true,
    "current_user_role_id": 1,
    "repo_count": 0,
    "chart_count": 0,
    "metadata": {
      "public": "false"
    }
  }
][root@harbar-master ~]# 

3)搜索 某个应用的 信息

[root@harbar-master ~]# curl --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/search?q=myapp"
{
  "project": [],
  "repository": [
    {
      "project_id": 1,
      "project_name": "library",
      "project_public": true,
      "pull_count": 2,
      "repository_name": "library/myapp",
      "tags_count": 1
    }
  ],
  "Chart": null
}[root@harbar-master ~]# 

4)查询应用某个项目下的应用

curl --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/repositories?project_id={project_id}"

实际操作过程

[root@harbar-master ~]# curl --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/repositories?project_id=1"
[
  {
    "id": 1,
    "name": "library/myapp",
    "project_id": 1,
    "description": "",
    "pull_count": 2,
    "star_count": 0,
    "tags_count": 1,
    "labels": [],
    "creation_time": "2019-11-24T15:16:09.311411Z",
    "update_time": "2019-11-24T15:26:07.408234Z"
  }
][root@harbar-master ~]# 

或者

[root@harbar-master ~]# curl --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/repositories?project_id=1&q=library%2Fmyapp"[
  {
    "id": 1,
    "name": "library/myapp",
    "project_id": 1,
    "description": "test",
    "pull_count": 2,
    "star_count": 0,
    "tags_count": 1,
    "labels": [],
    "creation_time": "2019-11-24T15:16:09.311411Z",
    "update_time": "2019-11-28T17:36:41.753116Z"
  }
][root@harbar-master ~]# 

5)根据项目和应用搜索应用的tag名

curl --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/repositories/{repo_name}/tags"

实际操作

[root@harbar-master ~]# curl --insecure -u "admin:Harbor12345" -X GET -H "Content-Type: application/json" "https://192.168.44.10/api/repositories/library%2Fmyapp/tags"
[
  {
    "digest": "sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e",
    "name": "v1",
    "size": 6757253,
    "architecture": "amd64",
    "os": "linux",
    "docker_version": "17.03.2-ce",
    "author": "MageEdu \u003cmage@magedu.com\u003e",
    "created": "2018-03-02T03:39:41.482586301Z",
    "config": {
      "labels": {
        "annotation.io.kubernetes.container.hash": "5ddb7a8b",
        "annotation.io.kubernetes.container.ports": "[{\"name\":\"http\",\"containerPort\":80,\"protocol\":\"TCP\"}]",
        "annotation.io.kubernetes.container.restartCount": "0",
        "annotation.io.kubernetes.container.terminationMessagePath": "/dev/termination-log",
        "annotation.io.kubernetes.container.terminationMessagePolicy": "File",
        "annotation.io.kubernetes.pod.terminationGracePeriod": "30",
        "io.kubernetes.container.logpath": "/var/log/pods/f7b6ba81-1dc0-11e8-9267-000c29ab0f5b/myapp_0.log",
        "io.kubernetes.container.name": "myapp",
        "io.kubernetes.docker.type": "container",
        "io.kubernetes.pod.name": "deploy-myapp-79859f456c-29rqw",
        "io.kubernetes.pod.namespace": "default",
        "io.kubernetes.pod.uid": "f7b6ba81-1dc0-11e8-9267-000c29ab0f5b",
        "io.kubernetes.sandbox.id": "8e322f9ddffb50284081710a6aa77741563272de431416193450c8a65481033d",
        "maintainer": "NGINX Docker Maintainers \u003cdocker-maint@nginx.com\u003e"
      }
    },
    "signature": null,
    "labels": []
  }
][root@harbar-master ~]# 

二、脚本清理harbar镜像

#!/bin/bash
ENV=application
URL=https://192.168.1.101
USER=username
PASSWORD=password


project_id=`curl -s -u "$USER:$PASSWORD" -X GET -H "Content-Type: application/json" "$URL/api/projects?name=$ENV"|jq .[].project_id`
repo=`curl -s -u "$USER:$PASSWORD" -X GET -H "Content-Type: application/json" "$URL/api/repositories?project_id=$project_id"|jq -r .[].name|sed 's/\"//g'|awk -F '/' '{print $2}'`
echo "项目ID为$project_id"

for NAME in $repo
  do
    tags=`curl -s -u "$USER:$PASSWORD" -X GET -H "Content-Type: application/json" "$URL/api/repositories?project_id=$project_id&q=$ENV/$NAME"|jq .[].tags_count`
    echo "准备清理$NAME仓库"
    echo "$NAME仓库tag总数:$tags"
    if [ 20 -lt $tags ]
    then
      count_image=`expr $tags - 20`
      echo "$NAME仓库需清理$count_image个镜像"
      images_tag=`curl -s -u "$USER:$PASSWORD" -X GET -H "Content-Type: application/json" "$URL/api/repositories/$ENV/$NAME/tags"| jq .[].name |sed 's/\"//g'|sort -n | head -n $count_image`
      for i in $images_tag
      do
      echo "正在删除$NAME tag为$i的镜像"
      curl -s -u "$USER:$PASSWORD" -X DELETE -H "Content-Type: application/json" "$URL/api/repositories/$ENV/$NAME/tags/$i"
      done
      if [ $? -eq 0 ]
      then
      echo "本次共删除$count_image个镜像"
      echo "清理$NAME仓库完成!!!!!"
      fi
    fi
  done
View Code

三、python测试接口

import requests

class HarborClient(object):

    def __init__(self, url, username, password):
        self.username = username
        self.password = password
        self.url = url
        self.session = requests.Session()
        self.api = self.url + '/api'
        self.login()

    def login(self):
        login = '/login'
        login_url = self.url + login
        self.session.post(login_url, params={"principal": self.username, "password": self.password})

class HarborApi(HarborClient):
    def projects(self):
        '''  获取项目的详细信息,如下
        [{
        'project_id': 3,
        'owner_id': 1,
        'name': 'enos',
         ......
        'current_user_role_id': 0,
        'repo_count': 1,
        'chart_count': 0,
        }]
        :return:
        '''
        projects_url = self.api + "/projects"
        projects_info = self.session.get(projects_url).json()
        return projects_info

    def projects_id(self):
        projects_info = self.projects()
        project_id_list = []
        for projects in projects_info:
            project_id_list.append(projects['project_id'])
        print(project_id_list)
        return project_id_list

    def deployments(self):
        ''' 获取enos下面的所有项目信息
        [{
            'id': 2,
            'name': 'enos/myapp',
            'project_id': 3,
            'description': '',
            'pull_count': 80,
            'star_count': 0,
            'tags_count': 4,
            'labels': [],
            'creation_time': '2020-05-04T11:50:25.645659Z',
            'update_time': '2020-05-04T11:26:48.74488Z'
        }]
        :return:
        '''
        pro_id = 3
        repos_url = self.api + "/repositories"
        repos_res = self.session.get(repos_url, params={"project_id": pro_id})
        deployments_info = repos_res.json()
        return deployments_info

    def tags(self):
        deployments_info = self.deployments()
        deployment_names = []
        for deployment in deployments_info:
            deployment_names.append(deployment['name'])
        # 选择第一个作为测试
        tags_url = self.api + "/repositories" + '/'+ deployment_names[0] + "/tags"
        tags = self.session.get(tags_url).json()
        tags_sort = sorted(tags, key=lambda tags: tags["created"])  # 将 tag 按照创建时间进行排列
        del_tag = tags_sort[0:1][0]
        return del_tag,tags_url

    def delele_tag(self):
        '''
        :return:
        '''
        # curl  -u "admin:Harbor2018" -X DELETE "https://harbor-test1.eniot.io/api/repositories/enos/myapp/tags/v1"
        del_tag,tags_url = self.tags()
        del_tag_url = tags_url + "/" + del_tag['name']
        print(self.session)
        params = {
            'url': del_tag_url,
            'timeout': 30
        }
        del_res = self.session.delete(**params)
        print(del_res.json())

if __name__ == "__main__":
    harbor_url = "https://harbor-test1.eniot.io"
    username = "admin"
    password = "password"
    res = HarborApi(harbor_url,username, password)
    res.delele_tag()
View Code

1)过滤 tag比较多的项目且时间比较久的项目

import requests


class HarborClient(object):

    def __init__(self, url, username, password):
        self.username = username
        self.password = password
        self.url = url
        self.session = requests.Session()
        self.api = self.url + '/api'
        self.login()

    def login(self):
        login = '/login'
        login_url = self.url + login
        self.session.post(login_url, params={"principal": self.username, "password": self.password})

class HarborApi(HarborClient):
    def projects(self):
        projects_url = self.api + "/projects"
        projects_info = self.session.get(projects_url).json()
        return projects_info

    def projects_id(self):
        projects_info = self.projects()
        project_id_list = []
        for projects in projects_info:
            project_id_list.append(projects['project_id'])
        return project_id_list

    def deployments(self):
        projects_id_list = self.projects_id()
        max_app = []
        for pro_id in  projects_id_list:
            repos_url = self.api + "/repositories"
            # https://harbor-test1.eniot.io/api/repositories
            # https://harbor-test1.eniot.io/api/repositories/enos/myapp/tags/v1
            repos_res = self.session.get(repos_url, params={"project_id": pro_id})
            deployments_info = repos_res.json()
            app_list = []
            for app in deployments_info:
                if app['tags_count'] > 30:
                    print(app)
                    name = app['name']
                    tags_url = repos_url + "/" + name + "/tags/"
                    tags = self.session.get(tags_url).json()
                    tags_sort = sorted(tags, key=lambda tags: tags["created"])
                    last_time = tags_sort[0]["created"]
                    standards_time = '2019-12-30T17:00:00.000Z'
                    if last_time < standards_time:
                        print(name)
                        app_list.append(name)

if __name__ == "__main__":
    harbor_url = "https://harbor-test1.eniot.io"
    username = "admin"
    password = "password"
    res = HarborApi(harbor_url,username, password)
    res.deployments()

公开项目,不需要用户名和密码

import requests

class HarborApi():
    def __init__(self, url):
        self.url = url
        self.session = requests.Session()
        self.api = self.url + '/api'

    def projects(self):
        projects_url = self.api + "/projects"
        projects_info = self.session.get(projects_url).json()
        return projects_info

    def tags(self):
        tag_url =self.api + '/repositories/enos/chartmuseum-photon/tags'
        tag_info = self.session.get(tag_url).json()
        print(tag_info)

if __name__ == "__main__":
    harbor_url = "https://harbor-test.eniot.io"
    res = HarborApi(harbor_url)
    res.projects()
View Code

 私有项目,需要用户名和密码

import requests

class HarborClient(object):

    def __init__(self, harbor_url, username, password):
        self.username = username
        self.password = password
        self.harbor_url = harbor_url
        self.api = self.harbor_url + '/api'
        self.session = requests.Session()
        self.login()

    def login(self):
        header_dict = {
            'X-Xsrftoken': 'rTFr9tlBcFBOVsKBCuUO35C9kOZWkurP',
            'Cookie':'_xsrf=clRGcjl0bEJjRkJPVnNLQkN1VU8zNUM5a09aV2t1clA=|1606230190785756205|76eba21411faa69aad44f078f972ef49884183c3',
        }
        login_url = self.harbor_url + "/c/login"
        res = self.session.post(login_url,headers = header_dict,
                                params={"principal": self.username,
                                        "password": self.password})
        return res


class HarborApi(HarborClient):
    def if_login(self):
        res = self.login()
        print(res)
        if res.reason == "OK":
            return "success"
        else:
            return "failed"

    def projects(self):
        projects_url = self.api + "/projects"
        projects_info = self.session.get(projects_url).json()
        print(projects_info)
        return projects_info

if __name__ == "__main__":
    harbor_url = "https://harbor-test.eniot.io"
    username = "admin"
    password = "mypassword"
    res = HarborApi(harbor_url,username, password)
    res.if_login()
    res.projects()
View Code

 可选择是否通过登录来获取相关信息

import requests

class HarborPrivate():
    def __init__(self, harbor_url, username, password):
        self.username = username
        self.password = password
        self.harbor_url = harbor_url
        self.session = requests.Session()
        self.get_session()

    def get_session(self):
        header_dict = {
            'X-Xsrftoken': 'rTFr9tlBcFBOVsKBCuUO35C9kOZWkurP',
            'Cookie':'_xsrf=clRGcjl0bEJjRkJPVnNLQkN1VU8zNUM5a09aV2t1clA=|1606230190785756205|76eba21411faa69aad44f078f972ef49884183c3',
        }
        login_url = self.harbor_url + "/c/login"
        res = self.session.post(login_url,headers = header_dict,
                                params={"principal": self.username,
                                        "password": self.password})
        if res.reason == "OK":
            return self.session

class HarborPublic():
    def get_session(self):
        self.session = requests.Session()
        return self.session

class HarborApi():
    def __init__(self,url,session):
        self.url =url
        self.session = session
        self.api = self.url + '/api'

    def projects(self):
        projects_url = self.api + "/projects"
        projects_info = self.session.get(projects_url).json()
        for projects in projects_info:
            print(projects)
        return projects_info

if __name__ == "__main__":
    harbor_url = "https://harbor-test.eniot.io"
    project = {"project":False}
    if project["project"]:
        res = HarborApi(harbor_url,HarborPublic().get_session())
        res.projects()
    else:
        username = "admin"
        password = "Harbor2018"
        res = HarborApi(harbor_url,HarborPrivate(harbor_url,username, password).get_session())
        res.projects()
View Code

 

所有仓库

import requests
def harborapi():
    s = requests.session()
    s.auth = ('admin', '123456')
    r = s.get("https://harbor-test.com/api/v2.0/projects")
    print(r.text)

 

 

 

uploadchart = "/chartrepo/{repo}/charts"
posted on 2019-11-28 17:11  可口_可乐  阅读(770)  评论(0编辑  收藏  举报