I am trying to create an ssh connection and do some things on the remote server from within the script.
However the terminal prompts me for a password, then opens the connection in the terminal window instead of the script. The commands don't get executed until I exit the connection.
How can I ssh from within a bash script?
If you want the password prompt to go away then use key based authentication (described here).
To run commands remotely over ssh you have to give them as an argument to ssh, like the following:
root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:
#!/usr/bin/expect -f spawn ssh user@hostname expect "password:" sleep 1 send "<your password>\r" command1 command2 commandN