在python中更改用户 [英] Changing user in python
问题描述
我正在写一个简单的脚本来重新启动hadoop slave。在脚本中,我必须以root用户身份进行一些初始更改。之后,我必须更改为用户hadoop并执行一组命令。我使用os.system来运行命令,但我怀疑它是否工作正常。例如:
uid = pwd.getpwnam('hadoop')[2]
os.setuid(uid)
os.system('whoami')
os.chdir('/ home / hadoop / hadoop /')
os.system('bin / hadoop-daemon.sh stop tasktracker')
再次,我必须以root身份执行一些命令,并再次成为用户hadoop并执行:
os.system('bin / hadoop-daemon.sh stop tasktracker')
我在这里有三个问题,
-
os.system是我可以用来发布linux命令的最佳命令吗?
-
我可以通过上面的命令从root用户更改为hadoop用户但我无法更改为root用户(我可以理解,如果他们允许这样做会存在安全问题,我想知道是否有可能做到这一点,至少通过传递密码)?
-
os.setuid()是否工作? whoami打印用户hadoop,但进程tasktracker不停止使用这些命令,但如果我手动执行相同的命令,它可以正常工作(手动尝试时,我使用su hadoop而不是setuid)。
感谢您的全力帮助。
- Sethu
您可以使用:
os.system('sudo -u hadoop bin / hadoop-daemon.sh停止tasktracker')
或者如果您没有sudo,但有su
os.system('su hadoop -cbin / hadoop-daemon.sh stop tasktracker')
I am writing a simple script which restarts a hadoop slave. In the script, I have to do some initial changes as a root user. After that I have to change to user "hadoop" and perform set of commands. I was using os.system to run commands but I doubt whether it works well. For example:
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 perform some commands as root after this and again become user "hadoop" and execute :
os.system('bin/hadoop-daemon.sh stop tasktracker')
I have three questions here ,
Is os.system is the best command that I can use to issue linux commands ?
I am able to change from root user to user hadoop by the commands above but I am not able to change to root user (I can understand there will be security issues if they permit this, I want to know is there any possibility to do that , atleast by passing password) ?
Does os.setuid() work ? whoami prints user hadoop but the process "tasktracker" is not stopped using those command, but if i perform the same commands manually it works fine (I use "su hadoop" instead of setuid while trying it out manually).
Thanks for all your help.
- Sethu
you could use:
os.system('sudo -u hadoop bin/hadoop-daemon.sh stop tasktracker')
or if you dont have sudo, but have su
os.system('su hadoop -c "bin/hadoop-daemon.sh stop tasktracker"')
这篇关于在python中更改用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!