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?
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.