Created
May 15, 2024 11:32
-
-
Save projectoperations/a2eceb432d8b18a3c0d0710b40a245cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
def get_docker_containers(): | |
try: | |
# Run the docker ps command with the specified format | |
result = subprocess.run(['docker', 'ps', '--no-trunc', '--format', '{{.ID}}|{{.Image}}|{{.Command}}|{{.RunningFor}}|{{.Status}}|{{.Ports}}|{{.Names}}'], | |
stdout=subprocess.PIPE, text=True, check=True) | |
output = result.stdout | |
except subprocess.CalledProcessError as e: | |
print(f"Error executing command: {e}") | |
return [] | |
containers = [] | |
for line in output.splitlines(): | |
fields = line.split("|") | |
if len(fields) < 7: | |
continue # skip malformed lines | |
container = { | |
"ContainerID": fields[0], | |
"Image": fields[1], | |
"Command": fields[2], | |
"Created": fields[3], | |
"Status": fields[4], | |
"Ports": fields[5], | |
"Names": fields[6] | |
} | |
containers.append(container) | |
return containers | |
def main(): | |
containers = get_docker_containers() | |
if not containers: | |
print("No containers found or error occurred.") | |
return | |
for container in containers: | |
print(container) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment