Py学习  »  Python

如何在python子流程中由其他用户运行文件

sachin dubey • 6 年前 • 1445 次点击  

我正在创建一个python脚本,它调用一个shell脚本,并使用 Subprocess . 我的问题是我想让另一个用户运行这个shell脚本。我的代码如下

代码:

import subprocess
filename = '/mount/test.sh'
p = subprocess.Popen([filename],shell=True,stdout=subprocess.PIPE)
out, err = p.communicate()
print(out)

有人能告诉我如何用另一个用户运行我的shell脚本吗?

注:

只有子流程部分应该由另一个用户运行,而不是由主python脚本运行

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43696
 
1445 次点击  
文章 [ 1 ]  |  最新文章 6 年前
Rishi Bansal
Reply   •   1 楼
Rishi Bansal    6 年前

你可以尝试下面的解决方案

def change(user_uid, user_gid):
    def result():
        report_ids('starting demotion')
        os.setgid(user_gid)
        os.setuid(user_uid)
        report_ids('finished demotion')
    return result

def report_ids(msg):
    print 'uid, gid = %d, %d; %s' % (os.getuid(), os.getgid(), msg)


import subprocess
filename = '/mount/test.sh'
#mention UID and GID here
p = subprocess.Popen(filename, preexec_fn=change(1000, 1000))
result = p.wait()
print(result)

注意:我用check_输出代替popen。因为我不能测试,如果有打字或错误,请原谅。另外,检查p.communicate是否与check_输出一起工作。