Python chroot and exit chroot

I know this has been written a few time online, but the last time I needed to read up on it, it took a little long to find the answer.

What I wanted to do was to chroot in to a new root, then exit that chroot via python .

Below we have my current working directory that is /root , take a look at what we have in the directory:

In [1]: import os

In [2]: os.system('pwd')
/root
Out[2]: 0

In [3]: os.system('ls -l /root')
total 12
drwxr-xr-x 3 root root 4096 Dec  5 15:47 filesystems
drwxr-xr-x 3 root root 4096 Dec  5 15:01 iso
drwxr-xr-x 3 root root 4096 Dec  5 15:14 squashfs
Out[3]: 0

I’m then going to keep track of my current root, this part is very important:

In [4]: real_root = os.open('/', os.O_RDONLY)

And change to a new root, I’m going to use a archlinux squashfs I had laying around:

In [5]: os.chroot('/root/squashfs/archlinux/')

In [6]: os.chdir('/root')

We are now in the new room, lets have a look around:

In [7]: os.system('pwd')
/root
Out[7]: 0

In [8]: os.system('ls -l /root/')
total 16
-rw-r--r-- 1 root root 7725 Dec  5 21:12 install.txt

And lets go ahead and back out of this chroot back up to the real root filesystem:

In [9]: os.fchdir(real_root)

In [10]: os.chroot('.')

In [11]: os.chdir('/root')

And lets verify our old data is in place:

In [12]: os.system('pwd')
/root
Out[12]: 0

In [13]: os.system('ls -l /root/')
total 12
drwxr-xr-x 3 root root 4096 Dec  5 15:47 filesystems
drwxr-xr-x 3 root root 4096 Dec  5 15:01 iso
drwxr-xr-x 3 root root 4096 Dec  5 15:14 squashfs