Skip to content

Instantly share code, notes, and snippets.

@Red5d
Last active March 14, 2018 03:12
Show Gist options
  • Save Red5d/be83b626f1c8cfac7985 to your computer and use it in GitHub Desktop.
Save Red5d/be83b626f1c8cfac7985 to your computer and use it in GitHub Desktop.
Python version of the "docker ps" command that rearranges the output to fit on a smaller terminal window a little better.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from docker import Client
import sys
reload(sys)
sys.setdefaultencoding('utf8')
c = Client(base_url='unix://var/run/docker.sock')
try:
if sys.argv[1] == "-a":
ps = c.containers(False, True)
else:
ps = c.containers()
except:
ps = c.containers()
row = [['NAME', 'IMAGE', 'STATUS', '', '']]
for item in ps:
container = []
container.append(item['Names'][0].split('/')[1]+" ")
container.append(item['Image']+" ")
container.append(item['Status']+" ")
portList = ""
for ports in item['Ports']:
try:
if len(portList) == 0:
portList = portList + str(ports['PublicPort'])+":"+str(ports['PrivatePort'])+"/"+str(ports['Type'])
else:
portList = portList + ","+str(ports['PublicPort'])+":"+str(ports['PrivatePort'])+"/"+str(ports['Type'])
except:
try:
if len(portList) == 0:
portList = portList + ":"+str(ports['PublicPort'])+"/"+str(ports['Type'])
else:
portList = portList + ",:"+str(ports['PublicPort'])+"/"+str(ports['Type'])
except:
try:
if len(portList) == 0:
portList = portList + ":"+str(ports['PrivatePort'])+"/"+str(ports['Type'])
else:
portList = portList + ",:"+str(ports['PrivatePort'])+"/"+str(ports['Type'])
except:
portList = " "
if portList != " " or "" :
container.append("\n\t\t\t└─ "+portList)
container.append("\n\t\t\t└─ "+item['Command']+"\n")
row.append(container)
widths = [max(map(len, col)) for col in zip(*row)]
for line in row:
print "".join((val.ljust(width) for val, width in zip(line, widths)))
@smd1000
Copy link

smd1000 commented Mar 14, 2018

This is a really handy script. Especially when combined with something like boto3 if looking to get docker status from a range AWS hosts.

One suggestion to make this script backwards-compatible with the newest docker api (2.0+) is to use docker.APIClient instead of Client.

import docker
.....

c = docker.APIClient()

Thanks for writing this up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment