【问题标题】:Using sudo su command with touch command to create file with other user permission使用 sudo su 命令和 touch 命令创建具有其他用户权限的文件
【发布时间】:2016-07-13 11:46:55
【问题描述】:

我想在 Python 脚本中运行具有特定用户权限的命令。

import os
os.subprocess("sudo su user; cd     <directory_path> ; touch test", shell=True)

这里的测试文件不是以我使用 sudo su 的用户的所有权创建的。

我也用 sudo -u 和 sudo -i 尝试了相同的命令,但没有成功。

【问题讨论】:

    标签: python shell sudo


    【解决方案1】:

    您正在使用调用sudo susudo -i 的方式生成一个新shell,而新shell 没有通过cd;touch

    你可能想要一些类似

    的东西
    sudo -u user touch <dir>/test
    

    (不过,如果目录不存在,其行为与您的预期代码略有不同)。

    【讨论】:

    • 要补充这个答案,如果您需要使用 sudo 执行多个命令(即cd &lt;directory_path&gt;; touch test),请参阅this question
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多