Reputation: 123
I tried running the following script and it works fine but I am not getting the expected result:
import os,sys
os.system("mount /dev/sdb3 /mnt")
os.system("lsblk")
os.system("mount --bind /proc /mnt/proc")
os.system("mount --bind /home /mnt/home")
os.system("mount --bind /dev /mnt/dev")
os.system("mount --bind /sys /mnt/sys")
os.chroot("/mnt")
os.system("pwd")
os.system("lsblk")
This is because when I do pwd after os.chroot("/mnt"), I am not inside the "/mnt" directory. However, when I run the following code directly into Linux terminal with shell commands(without using a python script), I am getting my expected result.
Now my question is, why can't I go into the /mnt directory using os.chroot("/mnt"). How can I achieve this using os.chroot(using python script) ?
Upvotes: 0
Views: 3392
Reputation: 400512
Python's os.chroot
is a raw wrapper around the chroot(2)
system call. As stated in the system call documentation:
This call does not change the current working directory, so that after the call '.' can be outside the tree rooted at '/'. In particular, the superuser can escape from a "chroot jail" by doing:
mkdir foo; chroot foo; cd ..
This call does not close open file descriptors, and such file descriptors may allow access to files outside the chroot tree.
You need to explicitly change the current working directory yourself, e.g. os.chdir('/')
to move into the new root.
You're seeing different behavior than when running the commands from a shell because the chroot(1)
executable explicitly changes the current working directory to the new root (source).
Upvotes: 1
Reputation: 5315
The method chroot() changes the root directory of the current process to the given path.To use this method, you would need super user privilege.
Source: http://www.tutorialspoint.com/python/os_chroot.htm
Could it be the root-cause?
As a workaround, you could call os.system("cd /mnt; mycommand")
Upvotes: 0