I want to write a chroot wrapper in python. The script will be copying some files, setting up some other stuff and then executing chroot and should land me in a chroot shell.
The tricky part is that I w开发者_JS百科ant no python processes running after I am in the chroot.
In other words, python should do the setup work, call chroot and terminate itself, leaving me in a chroot shell. When I exit the chroot, I should be in a directory where I was when I invoked the python script.
Is this possible?
My first thought would be to use one of the os.exec*
functions. These will replace the Python process with the chroot
process (or whatever you decide to run with exec*
).
# ... do setup work
os.execl('/bin/chroot', '/bin/chroot', directory_name, shell_path)
(or something like that)
Alternatively, you can use a new thread for the popen command to avoid blocking the main code then pass the command results back.
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
精彩评论