1

I have to open a terminal using sudo from python. Consider my password is pass and I need to run a command within script which is sudo critical-stack-intel pull.

I have following small piece of code:

import subprocess
import shlex

command = "sudo critical-stack-intel pull"
popen = subprocess.Popen(shlex.split(command),stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
popen.communicate("pass")
popen.wait()
# print help(p)

If i run the file as python myfile.py, it asks me for password within terminal. This is not what I desire. I want the python to handle the password I gave and run normally. How do I get this done?

EDIT

Using popen.communicate(pass + "\n") along with sudo -S did what i desired.

4
  • sudo opens the tty, it does not use stdin by default. Use sudo -S instead Commented Dec 1, 2015 at 10:16
  • Have a look at this: stackoverflow.com/questions/567542/… Commented Dec 1, 2015 at 10:16
  • I want to use subprocess.Popen not os.Popen. Commented Dec 1, 2015 at 10:23
  • The accepted answer there is not the best answer, unfortunately; but the question is a duplicate, and you'll find good answers there. Commented Dec 1, 2015 at 10:48

1 Answer 1

2

You can use the -S option of sudo to pass the password via stdin. Most likely, though, it's a better idea to allow sudo access to critical-stack-intel without password using /etc/sudoers.

Sign up to request clarification or add additional context in comments.

7 Comments

Fixing this in /etc/sudoers seems like the right approach. Check out command aliasses
I used -S in my command along with popen.communicate(pass) but its not ending the session.
@SarvagyaPant: IIRC communicate() does not close stdin. You need to send a newline character together with your password
@mrks can you update the answer suggesting to use pass + "\n" in my code.
Actually I was wrong: all streams are closed by communicate()
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.