相关文章推荐
严肃的麻辣香锅  ·  Python ...·  2 月前    · 
英勇无比的领带  ·  python ...·  2 月前    · 
潇洒的雪糕  ·  python win ...·  2 年前    · 
活泼的黄花菜  ·  Newtonsoft.Json.Linq.J ...·  2 年前    · 

python指定用户执行命令

在 Python 中,可以使用 subprocess 模块执行 shell 命令。要指定执行命令的用户,可以使用 sudo 命令,并在 subprocess.run() 函数中传递 sudo 命令的参数,例如:

import subprocess
command = "ls -l"
result = subprocess.run(["sudo", "-u", "username", "bash", "-c", command], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout.decode())

这样,命令 ls -l 就会以 username 用户的身份执行。

  •