0

I would like to enable safari driver in each session separately.

import os
os.system("sudo safaridriver --enable")

Previous code asks for password. My question is basically how to provide the asked password? I tried something like import subprocess

p = subprocess.Popen(["sudo safaridriver --enable"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(b"password\n")  # Assume that the password is indeed "password"
result = p.stdout.read()  # The program's output
print(result)

This code doesn't work. Throwing the following error:

sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper

So I'm not sure how to handle it. Additionally it would be great if the password would not be in clear text. But for start clear text is ok.

Thanks for any ideas

ps related text without useful answer here

Jürgen K.
  • 3,427
  • 9
  • 30
  • 66
  • maybe `sudo` not read from `stdin` for security reason. But error shows that you could use `-S` to read from `stdin` -- `sudo -S safaridriver --enable` – furas Feb 27 '22 at 01:16
  • Does this answer your question? [Using sudo with Python script](https://stackoverflow.com/questions/13045593/using-sudo-with-python-script) – miken32 Mar 17 '23 at 19:42

1 Answers1

1

It seems sudo doesn't read from stdin - probably for security reason.

But error shows that you could use option -S in sudo to read from stdin .

Documentation man sudo shows

-S, --stdin
            Write the prompt to the standard error and read the password 
            from the standard input instead of using the terminal device.

I don't have safaridriver so I tested on something simpler like ls

In bash in console works for me

echo password | sudo -S ls

or

sudo -S ls <<< password

And first method works for me in code

import subprocess

p = subprocess.Popen(["echo password | sudo -S ls"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

result = p.communicate()[0].decode()

print(result)

But version with <<< has problem because subprocess uses sh instead of bash.
But it works with executable='/bin/bash'

import subprocess

p = subprocess.Popen(["sudo -S ls <<< password"], executable='/bin/bash', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,)

result = p.communicate()[0].decode()

print(result)
furas
  • 134,197
  • 12
  • 106
  • 148