0

I am attempting to execute sudo -S id within a TTY shell using pty.spawn() in python 2.7.

import os
import pty
command = 'id'

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

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

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

pty.spawn(scmd, reader, writer)

when I execute the above code the python interpreter outputs the following error:

OSError: [Errno 13] Permission denied

My code is based on this answer: Issuing commands to psuedo shells (pty)

Even when the password is correct I receive the above error, how do I fix this code so that it executes sudo and prints the output of the id command to stdout?

haito
  • 3
  • 3

1 Answers1

0

You seem to need to provide the command as an array, and using a generator writer does not seem to work, and you need a newline in the password, so try:

def writer(fd):
    return 'password\n'

os.close(0)
pty.spawn(scmd.split(' '), reader, writer)

Using os.close(0) stops the program from putting stdin into raw mode.

meuh
  • 11,500
  • 2
  • 29
  • 45
  • Receiving this error: Password for to change to user=(root) Password incorrect. Sorry, try Again – haito Apr 13 '20 at 17:01
  • I cannot help with that. Note that sudo is asking for your password, not root's password. – meuh Apr 13 '20 at 17:04