0

I'm trying to run commands after running su - username I tried to use:

subprocess.run(['su', '-', str(username)]) #username is var
subprocess.run(['touch', 'test.txt'])

or

run_su = 'su - '+ str(username) #username is var
os.system(run_su)

or

subprocess.call(['su', '-', str(username)]) #username is var
subprocess.call(['touch', 'test.txt'])

or

p1 = subprocess.Popen(['su', '-', str(username)], shell=True, stdout=subprocess.PIPE) #username is var
p2 = subprocess.Popen(['touch', 'test.txt'], stdin=p1.stdout, stdout=subprocess.PIPE)

nothing seems to work for me.

can you suggest a way to do that?

7
  • What exactly does not work? Both the first and second variant work here, didn't test the rest. Obviously the touch command will not be executed until the shell you start with su is terminated, and it will not be executed by the su process. You need to pass the command to be executed to su. Why not use a sehllscript? Commented May 4, 2021 at 5:48
  • Probably the easiest thing is to throw the sequence of commands into a temporary file and run that file with sudo. Subprocesses in Python are run in separate shells (and, depending on how you invoke them, may not even involve a shell directly) Commented May 4, 2021 at 5:48
  • @JanChristophTerasa I don't get the test.txt file on the username directory like I'm doing it on shell. I don't see the test.txt file anywhere. Commented May 4, 2021 at 5:51
  • @Barak The text file will appear after the su command terminates, since it tries to open a new shell. It will either terminate by closing that shell, or by typing a wrong password. Commented May 4, 2021 at 5:53
  • @Barak there's another way to go about this if you want to create a file that is owned by a specific user. You can just create the file directly and chown the file to the desired user. Commented May 4, 2021 at 5:58

1 Answer 1

2

managed to do this with creating a var

demo = "su -l username -c 'command as string'"
os.system(str(demo))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.