我想在 python 中编写一个 chroot 包装器。该脚本将复制一些文件,设置一些其他内容,然后执行 chroot,并且应该让我进入 chroot shell。
棘手的部分是我不想在进入 chroot 后运行任何 python 进程。
换句话说,python 应该完成设置工作,调用 chroot 并自行终止,将我留在 chroot shell 中。当我退出 chroot 时,我应该在我调用 python 脚本时所在的目录中。
这可能吗?
我的第一个想法是使用其中一个os.exec*
功能。chroot
这些将用进程(或您决定运行的任何内容)替换 Python 进程exec*
。
# ... do setup work
os.execl('/bin/chroot', '/bin/chroot', directory_name, shell_path)
(或类似的东西)
或者,您可以为 popen 命令使用新线程以避免阻塞主代码,然后将命令结果传回。
import popen2
import time
result = '!'
running = False
class pinger(threading.Thread):
def __init__(self,num,who):
self.num = num
self.who = who
threading.Thread.__init__(self)
def run(self):
global result
cmd = "ping -n %s %s"%(self.num,self.who)
fin,fout = popen2.popen4(cmd)
while running:
result = fin.readline()
if not result:
break
fin.close()
if __name__ == "__main__":
running = True
ping = pinger(5,"127.0.0.1")
ping.start()
now = time.time()
end = now+300
old = result
while True:
if result != old:
print result.strip()
old = result
if time.time() > end:
print "Timeout"
running = False
break
if not result:
print "Finished"
break