Search code examples
pythonlinuxshellchroot

Writing files into chroot environment


I'm trying to write data to files in a chroot environment. Since I'm non-root user, they only way I can communicate with chroot is using schroot command.

Currently I'm using the following trick to write the data.

$ schroot -c chroot_session -r -d /tmp -- bash -c "echo \"$text\" > file.txt"

But I'm sure this will give me a lot of grief if text has some special characters, quotes etc. So whats a better way of sending $text to chroot. Most probably I'll be using the above command through a python script. Is there a simpler method?


Solution

  • Kinda hackish, but…

    c = ConfigParser.RawConfigParser()
    c.readfp(open(os.path.join('/var/lib/schroot/session', chroot_session), 'r'))
    chroot_basedir = c.get(chroot_session, 'mount-location')
    with open(os.path.join(chroot_basedir, '/tmp/file.txt'), 'w') as fp:
        fp.write(text)
    

    Okay, so privileges don't let you get in by any method other than schroot, huh?

    p = subprocess.Popen(['schroot', '-c', name, '-r', 'tee', '/tmp/file.txt'],
                         stdin=subprocess.PIPE,
                         stdout=open('/dev/null', 'w'),
                         stderr=sys.stderr)
    p.stdin.write(text)
    p.stdin.close()
    rc = p.wait()
    assert rc == 0