Pass commands as input to another command (su, ssh, sh, etc)
<p>I have a script where I need to start a command, then pass some additional commands <em>as commands</em> to that command.  I tried</p>

<pre><code>su
echo I should be root now:
who am I
exit
echo done.
</code></pre>

<p>... but it doesn't work: The <code>su</code> succeeds, but then the command prompt is just staring at me.  If I type <code>exit</code> at the prompt, the <code>echo</code> and <code>who am i</code> etc start executing!  And the <code>echo done.</code> doesn't get executed at all.</p>

<p>Similarly, I need for this to work over <code>ssh</code>:</p>

<pre><code>ssh remotehost
# this should run under my account on remotehost
su
## this should run as root on remotehost
whoami
exit
## back
exit
# back
</code></pre>

<p>How do I solve this?</p>

<blockquote>
  <p>I am looking for answers which solve this in a general fashion, and which are not specific to <code>su</code> or <code>ssh</code> in particular.  The intent is for this question to become a <a href="https://meta.stackoverflow.com/questions/291992/what-is-a-canonical-question-answer-and-what-is-their-purpose">canonical</a> for this particular pattern.</p>
</blockquote>