在chroot环境中写文件

0 投票
2 回答
1440 浏览
提问于 2025-04-16 11:04

我正在尝试在一个叫做chroot的环境中写入文件。因为我不是管理员用户,所以我只能通过schroot命令与chroot进行交流。

目前我使用以下方法来写入数据。

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

但是我知道,如果文本中有一些特殊字符、引号等,这种方法可能会让我很头疼。那么,有没有更好的方法来把$text发送到chroot呢?我可能会通过一个Python脚本来使用上面的命令。有没有更简单的方法呢?

2 个回答

0

你可以用Python把$text写入一个文件(Python有权限写入),
然后把那个文件复制到file.txt里。

1

有点像小窍门,不过……

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)

好的,所以权限不允许你用除了 schroot 以外的任何方法进入,是吧?

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

撰写回答