pythonsudoos.systemsurclone

Run sh file as root in python file


i´m trying to run an .sh file from my python skript to manually start a synch process with clone.

is there an easy way?

I tryed:

os.system('sudo su')
os.system('cd /home/pi/Desktop/webcam')
os.system('./clone.sh')

but after the first comand nothing happens.

Thanks


Solution

  • Each system() call forks off a child process and then waits for it to finish. The child does stuff and then exits. Your initial su changed UID to zero in the child, and then it exited, so the zero UID was lost with death of the child. The cd then changed CWD in the child, and when it exits, again we find there's no effect on the parent and no effect on subsequent commands. By the time you run the clone script, it's running with wrong UID and wrong CWD.

    You want this:

    os.chdir('/home/pi/Desktop/webcam')
    os.system('sudo ./clone.sh')
    

    (Or perhaps sudo bash clone.sh, if there's no #! shebang.)

    EDIT

    Feel free to limit the CWD change to just the child, if desired.

    folder = '/home/pi/Desktop/webcam'
    os.system(f'sudo bash -c "cd {folder} && ./clone.sh"')