Skip to content

Instantly share code, notes, and snippets.

@nilium
Last active January 3, 2019 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilium/bd9274f1726f562961c03813c3dd7258 to your computer and use it in GitHub Desktop.
Save nilium/bd9274f1726f562961c03813c3dd7258 to your computer and use it in GitHub Desktop.
Script to display docker containers with exposed / bound ports in dzen2
#!/usr/bin/env bash
# Usage: docker-ports [format] <dzen2-args...>
#
# Displays open docker ports using dzen2.
#
# Example:
#
# $ docker-ports -fn 'PragmataPro-9' -dock
format_ports() {
docker container ls -aq | while read id; do
docker container inspect "$id"
done | jq 2>/dev/null -scr '
def fg($color): "^fg(\($color))";
def fg: "^fg()";
def p($x): "^p(\(if $x > 0 then "+\($x)" else "\($x)" end))";
add |
map(
select(
((.NetworkSettings.Ports // {}) | keys != []) or
(.HostConfig.PublishAllPorts and .Config.ExposedPorts != {})
) |
[
fg(if .State.Status != "running" then "#ff6644" else "#44ff88" end),
.Name[1:], fg, ": ",
(
(.NetworkSettings.Ports | to_entries | map(
select(.value != null) |
(.key | split("/") | last) as $proto |
(.key | split("/") | first) as $port |
[
"\(fg("#88aaff"))\($proto)\(fg):",
"\(fg("#ffcc44"))\($port)\(fg)->",
(.value | map([
fg("#ffcc44"),
(if .HostIp == "0.0.0.0" then "*" else .HostIp end),
":", .HostPort,
fg
] | join("")) | join (","))
] | join("")
)) as $hostPorts |
(
(.NetworkSettings.Ports | to_entries | map(select(.value != null).key)) as $hostPortNames |
.Config.ExposedPorts | keys | map(
select(. as $name | $hostPortNames | all(. != $name)) |
split("/") |
last as $proto |
first as $port |
"\(fg("#88aaff"))\($proto)\(fg):\(fg("#ffcc44"))\($port)\(fg)"
)
) as $exposedPorts |
($hostPorts + $exposedPorts) |
sort | join("; ")
),
fg
] | join("")
) | sort | join(p(20))' || echo
}
if [ "$1" == format ]; then
format_ports
exit $?
fi
while :; do
"$0" format
sleep 1 || break
done | dzen2 "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment