1

I am attempting to execute sudo from a python script:

import os
command = 'id'
os.popen("sudo -S %s"%(command), 'w').write('password')

My server is configured to not allow non-TTY shells to execute sudo for security reasons, is there a workaround for this to execute the sudo command using python (without using su).

The above code outputs:

sudo: sorry, you must have a tty to run sudo
dd_doriz
  • 19
  • 1
  • possible duplicate of [https://stackoverflow.com/questions/38641224/python-subprocess-sudo-returns-error-error-sudo-sorry-you-must-have-a-tty/38641856#38641856](https://stackoverflow.com/questions/38641224/python-subprocess-sudo-returns-error-error-sudo-sorry-you-must-have-a-tty/38641856#38641856) ? – Nobody Apr 12 '20 at 01:38
  • None of those answers answer my question @ZyxokUnum – dd_doriz Apr 12 '20 at 01:53
  • @dd_doriz Did you try adding RETURN after password. It could be that the terminal is waiting for you submit the password? os.popen("sudo -S %s"%(command), 'w').write('password\r') – Thaer A Apr 12 '20 at 05:42
  • Does this answer your question? [Issuing commands to psuedo shells (pty)](https://stackoverflow.com/questions/21442360/issuing-commands-to-psuedo-shells-pty) – classicdude7 Apr 12 '20 at 14:51

1 Answers1

1

Based on this: https://stackoverflow.com/a/21444480/1216776 you should be able to do:

import os
import pty
command = 'id'

scmd ="sudo -S %s"%(command)

def reader(fd):
  return os.read(fd)

def writer(fd):
    yield 'password'
    yield ''

pty.spawn(scmd, reader, writer)
stark
  • 12,615
  • 3
  • 33
  • 50