Skip to content

Instantly share code, notes, and snippets.

@epifanio
Created April 22, 2024 06:19
Show Gist options
  • Save epifanio/9f7111a00382c87020fd408b7ab926cf to your computer and use it in GitHub Desktop.
Save epifanio/9f7111a00382c87020fd408b7ab926cf to your computer and use it in GitHub Desktop.
import subprocess
import sys
# Check if the correct number of arguments is provided
if len(sys.argv) != 2:
print("Usage: python script.py <keyword>")
sys.exit(1)
# Get the keyword from the command line
keyword = sys.argv[1]
try:
# Run the "docker ps" command and capture its output
result = subprocess.run("docker ps", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
# Check if the command executed successfully
if result.returncode == 0:
# Split the output into lines
output_lines = result.stdout.splitlines()
# Skip the header line (the first line) which contains column names
if len(output_lines) > 1:
header = output_lines[0]
container_lines = output_lines[1:]
# Initialize a variable to track if a matching container is found
matching_container_found = False
# Process the container lines and filter based on the keyword
for line in container_lines:
if keyword in line:
# Split each line into columns
columns = line.split()
# Get the container ID
container_id = columns[0]
# Execute a Bash shell inside the matching container
subprocess.run(f"docker exec -it {container_id} bash", shell=True)
# Set the flag to indicate a matching container was found
matching_container_found = True
break # Exit the loop after opening the Bash shell
if not matching_container_found:
print("No matching container found.")
else:
print("No running containers found.")
else:
# Handle the case where the command returns a non-zero exit code
print(f"Command failed with exit code {result.returncode}")
print(f"stderr: {result.stderr}")
except subprocess.CalledProcessError as e:
# Handle the case where the command could not be executed
print(f"Command execution failed: {e}")
except Exception as e:
# Handle other exceptions
print(f"An error occurred: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment