Return from root to user using python os.system('kill') not working
<p>I need to run a command from my python script as a root user (just sudo wont work), so I use os.system('sudo su') and am able to get root access. But again I need to return back to user . I tried os.system('exit'), but it still doesnt come out of root login to user login. I have to manually enter exit in the terminal to get back to user login. Can someone help me on how to do this in python ?</p>

<pre><code>import os
import time
os.system('clear') #clear the terminal
os.system('sudo eject /dev/sr0')
time.sleep(2)
os.system('sudo modprobe option')
time.sleep(2)
os.system('sudo su')
time.sleep(5)
os.system('echo 2001 7d0e &gt; /sys/bus/usb-serial/drivers/option1/new_id')
time.sleep(2)
os.system('exit')
</code></pre>

<p>Your <code>echo</code> command doesn't work with <code>sudo</code> because the redirection to <code>&gt; /sys/bus/...</code> is made by your own user, and then given to <code>sudo echo</code>, but root is required to access the file in the 1st place.</p>

<p>Try using <code>sudo bash -c 'command &gt; redirect'</code> instead, which will acquire root permissions <em>before</em> attempting the redirect:</p>

<pre><code>def sudo(command):
  return os.system("sudo bash -c '{}'".format(command))

sudo('echo foo &gt; /sys/restricted/file')
</code></pre>

python root exit os.system