prescript.py 833 B

123456789101112131415161718192021222324252627282930
  1. import os
  2. import uuid
  3. import shutil
  4. def create_sandbox_and_execute(paths, closures):
  5. tmp_dir = os.path.join("/tmp", "sandbox-" + str(uuid.uuid4()))
  6. os.makedirs(tmp_dir, mode=0o755)
  7. try:
  8. for file_path in paths:
  9. target_path = os.path.join(tmp_dir, file_path)
  10. if os.path.isdir(file_path):
  11. os.makedirs(target_path, mode=0o755)
  12. else:
  13. os.makedirs(os.path.dirname(target_path), mode=0o755, exist_ok=True)
  14. shutil.copy(file_path, target_path)
  15. original_root = os.open("/", os.O_RDONLY)
  16. os.chroot(tmp_dir)
  17. os.chdir("/")
  18. try:
  19. closures()
  20. finally:
  21. os.fchdir(original_root)
  22. os.chroot(".")
  23. finally:
  24. shutil.rmtree(tmp_dir)
  25. print(123)