Use -S
man sudo
:
-S, --stdin
Write the prompt to the standard error and read the password from the standard input instead of
using the terminal device. The password must be followed by a newline character.
so you can use:
echo <myPassword> | sudo -S su <someuser>
Edit: This above did not work on a testing Ubuntu. It seems like the second command "su " is to fast after prompting password query.
I did a workaround to wait a second so the echoed password could be filled in, and then second sudo should be able, to run sudo su - foobar
:
echo "password" | sudo -S sleep 1 && sudo su - foobar