down.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. # -*- coding: utf-8 -*-
  2. import subprocess
  3. from concurrent.futures import ThreadPoolExecutor
  4. def stop_and_remove_container(container_id):
  5. try:
  6. subprocess.run(['docker', 'stop', container_id], check=True)
  7. subprocess.run(['docker', 'rm', '-f', container_id], check=True)
  8. print(f"Container {container_id} has been stopped and removed.")
  9. except subprocess.CalledProcessError as e:
  10. print(f"Failed to stop and remove container {container_id}: {e}")
  11. def stop_and_remove_containers():
  12. # 使用 docker ps 命令获取所有运行的容器列表
  13. containers = subprocess.run(
  14. ['docker', 'ps', '-aq', '-f', 'name=clash-'],
  15. capture_output=True,
  16. text=True
  17. ).stdout.strip().split('\n')
  18. # 使用 ThreadPoolExecutor 来并行执行容器的停止和删除
  19. with ThreadPoolExecutor(max_workers=5) as executor:
  20. for container_id in containers:
  21. if container_id:
  22. executor.submit(stop_and_remove_container, container_id)
  23. print("All 'clash-' prefixed containers have been processed.")
  24. if __name__ == "__main__":
  25. stop_and_remove_containers()