pythonbashsudocdchroot

How to import a Python library from a Chroot jail?


Let's say I'm trying to execute some code from a library in a directory, let's call it /home/user/project. In Bash it would go like this:

cd /home/user/project
python -c "from MyLib import DoSth; var = DoSth(); print(var)"

Now my exact situation is a little more complicated. My Python code (including all the installed libraries) lies in a chroot jail. I'm trying to execute the code from outside the jail. I tried the following:

cd /home/user/project
sudo -- chroot $CHROOT_DIR python3 -c "from MyLib import DoSth; var = DoSth(); print(var)"

This prints:

ModuleNotFoundError: No module named 'MyLib'

This is because the current directory inside the jail is just / becuase the previous cd statement was not executed inside the jail. When I tried it like this:

sudo -- chroot $CHROOT_DIR cd /home/user/project; python3 -c "from MyLib import DoSth; var = DoSth(); print(var)"

I got this error instead:

chroot: failed to run command ‘cd’: No such file or directory

Is there a way to use the library without having to change directories inside the jail? Or at least help me find a way to change directories inside the jail.

EDIT:

What I'm trying to do is the exact opposite of the suggested question. I'm trying to execute the code (which is entirely inside the jail) from outside the jail. The code runs perfectly inside the jail, but not from the outside. /home/user/project is a directory inside the jail.


Solution

  • I managed to do this by running a script containing all the commands I need instead of running separate commands, since cd always fails to run on chroot (even though the directory is inside the jail). Here's the command:

    sudo -- chroot $CHROOT_DIR /bin/bash /home/user/myscript
    

    In myscript:

    cd /home/user/project
    python3 -c "from MyLib import DoSth; var = DoSth(); print(var)"