pythonlinux-namespaces

How to create a process in a new Linux namespace


I am trying to create a child process with Python under a new Linux namespace. But checking the subprocess documentation it does not seem as though Python actually has an API to do so. The closest thing I found is the unshare method in the os module (here). But that seems to require these steps:

  1. Create a child process in the same namespace as the current parent
  2. Run unshare isolate the child process
  3. Run the command(s) we wanted in the child process

That's not quite the same as creating an isolated process to start with. Is there indeed no simple API in Python for this?

As an example, here is the analogous code in Go:

cmd := exec.Command(...)
cmd.SysProcAttr = &syscall.SysProcAttr {
    Cloneflags: syscall.CLONE_NEWUTS
}
cmd.Run()

The question is how to achieve the same with Python.


Solution

  • There is no other nice Python API for this. os.unshare() and os.setns() are currently the only APIs for manipulating namespaces (since Python 3.12). The feature request also mentions this:

    As for now, changing to a different namespace is really messy, one must use ctypes, and call libc functions to do so. I think implementing setns and unshare functions will make working with namespaces in Python much easier

    You could of course manually issue a clone syscall with CLONE_NEWxxx flags either through ctypes (loading the C library), but that would be pretty messy and definitely unsafe as it wouldn't take into account things like internal interpreter locks etc.