How can I tell if I'm logged in to a private Docker registry from a script?

后端 未结 7 1248
粉色の甜心
粉色の甜心 2021-02-04 23:59

How can I tell whether or not I\'m logged in to a private Docker registry server from a script? In other words, has docker login some.registry.com been run success

7条回答
  •  轮回少年
    2021-02-05 00:46

    You can parse .docker/config.json and try to manually connect to each registry specified in the file. The file contains the registry address and encoded username and password so you can script this process. You can do that using a library like docker-registry-client.

    pip install docker-registry-client
    

    And then:

    import base64
    import docker_registry_client
    import json
    import os.path
    
    def get_authed_registries():
      result = []
      config_path = os.path.expanduser("~/.docker/config.json")
      if not os.path.isfile(config_path):
        print("No docker config")
        return []
    
      docker_config = json.load(open(config_path))
    
      for registry, auth in docker_config.get("auths", {}).items():
        username, password = base64.b64decode(auth["auth"]).decode("utf-8").split(":", 1)
        if not registry:
          registry = "https://index.docker.io/v1/"
        if not registry.startswith("http"):
          registry = "https://" + registry
        try:
          rc = docker_registry_client.DockerRegistryClient(registry, username=username, password=password)
          result.append(registry)
        except Exception, e:
          print(registry, "failed:", e)
    
      return result
    
    
    get_authed_registries()
    

    A few caveats:

    • This may fail if you're using a credential store.
    • Tested on Python 2.7. Might need small adjustments for Python 3.
    • This code works for authentication, but any further actions on the registry fail. You will need to strip away API version (/v1, /v2, etc.) from the host name for that.
    • The code assumes all registries are HTTPS (unless specified otherwise in config.json)
    • An even more correct version will probably strip away anything but the hostname and try both v1 and v2.

    That said, I was able to get a list of logged-in registries and it correctly ignored expired ECR login.

提交回复
热议问题