Changing user in python

I am writing a simple script that restarts a slave. In the script, I have to make some initial changes as the root user. After that I have to go to the user "hadoop" and execute a set of commands. I used os.system to run the commands, but I doubt if this works well. For instance:

uid=pwd.getpwnam('hadoop')[2]
os.setuid(uid)
os.system('whoami')
os.chdir('/home/hadoop/hadoop/')
os.system('bin/hadoop-daemon.sh stop tasktracker')

Again I have to execute some commands as root after that and again become the user of “hadoop” and execute:

os.system('bin/hadoop-daemon.sh stop tasktracker')

I have three questions here,

  • Is os.system the best command I can use to issue Linux commands?

  • I can go from root to hadoop using the above commands, but I can’t change it to root (I can understand that there will be security problems if they resolve this, I want to know if there is an opportunity to do this, at least by passing the password)?

  • Does os.setuid () work? whoami prints the hadoop user, but the tasktracker process does not stop with this command, but if I execute the same commands manually, it works fine (I use su hadoop instead of setuid when trying manually).

Thank you for your help.

  • Sethu
+5
source share
4 answers

you can use:

os.system('sudo -u hadoop bin/hadoop-daemon.sh stop tasktracker')

or if you don't have sudo, but su

os.system('su hadoop -c "bin/hadoop-daemon.sh stop tasktracker"')
+6

"su" , os.setuid().

?

  • "su" , .
  • "su" , (, su -). , ulimit .conf.
+1

All Articles