【问题标题】:python os.chroot : unexpected output after exiting chrootpython os.chroot:退出 chroot 后的意外输出
【发布时间】:2015-10-18 05:31:58
【问题描述】:

我有以下代码:

#! /usr/bin/python

import os
import subprocess

def run_subprocess(cmd):
    print 'Starting : {}'.format(cmd)
    p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    odata, edata = p.communicate()
    print 'Done : {}'.format(cmd)
    if odata:
        print 'Output : {}'.format(odata)
    if edata:
        print 'Error : {}'.format(edata)
    return odata

LS_CMD = 'ls'
run_subprocess(LS_CMD)  # output 1
x_cwd = os.getcwd()
root_fd =os.open('/', os.O_RDONLY)
os.chroot('/mnt/mnt_sda5')
os.chdir('/')
os.fchdir(root_fd)
os.close(root_fd)
os.chdir(x_cwd)
run_subprocess(LS_CMD)  # output 2
print os.getcwd()

我 chroot 进入另一个目录并返回到当前工作目录。

我期待 output1 和 output2 匹配。 output1 是我期望看到的。输出 2 为空。

你能解释一下原因吗?

谢谢

【问题讨论】:

    标签: python chroot


    【解决方案1】:

    在您的 os.chdir(x_cwd) 之前,您需要 os.chroot('.') 将根目录更改回您现在使用 fchdir 更改为的原始“/”路径。所以这些行变成:

    os.fchdir(root_fd)
    os.chroot('.')
    os.close(root_fd)
    

    这里有一些细节 - http://www.bpfh.net/simes/computing/chroot-break.html

    【讨论】:

    • 在python中我需要os.chroot('/mnt/mnt_sda5')之后的os.chdir('/')吗?它是在它之前还是在它之后。
    • 回答我自己的问题。在 python 中,我们需要它。如果我们没有 os.chdir('/),则 os.getcwd() 输出无法访问
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2016-12-22
    • 1970-01-01
    • 2013-10-31
    • 2021-11-28
    相关资源
    最近更新 更多