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.

Mahadeva
  • 1,584
  • 4
  • 23
  • 56

1 Answers1

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.

mrks
  • 8,033
  • 1
  • 33
  • 62
  • 1
    Fixing this in `/etc/sudoers` seems like the right approach. Check out [command aliasses](https://help.ubuntu.com/community/Sudoers#Command_Aliases) – Joost Dec 01 '15 at 10:26
  • I used `-S` in my command along with `popen.communicate(pass)` but its not ending the session. – Mahadeva Dec 01 '15 at 10:29
  • @SarvagyaPant: IIRC `communicate()` does not close stdin. You need to send a newline character together with your password – Andrea Corbellini Dec 01 '15 at 10:50
  • @mrks can you update the answer suggesting to use `pass + "\n"` in my code. – Mahadeva Dec 01 '15 at 10:53
  • Actually I was wrong: all streams are closed by `communicate()` – Andrea Corbellini Dec 01 '15 at 10:56
  • @SarvagyaPant: You can suggest edits to answers yourself :) – mrks Dec 01 '15 at 10:59
  • @sarvagyaPant, I was trying same code, but I want to also print stdout output, but that gives error as I/O operation on closed file, looks like after stdin to pass password to closes pipe import subprocess pass="123" popen = subprocess.Popen(["sudo", "-S", "dmesg", ],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) popen.communicate(pass+"\n") popen.wait() print popen.communicate() – Aashutosh jha Jul 07 '17 at 14:35