If you are ok with doing this in Python, pexpect has an example that does almost exactly what you are asking for:
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before # Print the result of the ls command.
child.interact() # Give control of the child to the user.
To do this with ssh instead of ftp, you'd want code similar to the following (the example files in pexpect have much more details and info, but here are the basics):
import pexpect
child = pexpect.spawn ('ssh root@marlboro')
child.expect ('Password:')
child.sendline ('password')
child.expect ('prompt# ')
child.sendline ('cd /tmp')
child.expect ('prompt# ')
child.sendline ('ls -altr | tail')
child.expect ('prompt# ')
print child.before, child.after # Print the result of the ls command.
child.interact() # Give control of the child to the user.
Don't get me wrong, I LOVE expect (especially autoexpect), but python is just soooo much easier for me to grok.