-2

I want to run a command with a specific users permission in a Python script.

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

The test file here is not created with the ownership of the user I use with sudo su.

I also tried the same command with sudo -u and sudo -i but it didn't work.

NSU
  • 37
  • 1
  • 7

1 Answers1

2

You're spawning a new shell with the way you're calling sudo su or sudo -i, and the new shell isn't passed the cd;touch.

You probably want something along the lines of

sudo -u user touch <dir>/test

(which behaves slightly differently from your intended code if the directory doesn't exist, though).

Ulrich Schwarz
  • 7,598
  • 1
  • 36
  • 48
  • To add to this answer, if you need to execute more than one command with sudo (i.e. `cd ; touch test`), refer to [this question](http://stackoverflow.com/questions/5560442/how-to-run-two-commands-in-sudo). – Aran-Fey Jul 13 '16 at 11:55