python如何修改_在python中更改用户

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"')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值