using su inside of a shell script

Have you considered a password-less sudo instead?


Instead of su, use sudo with the NOPASSWD set in sudoers for appropriate command(s). You'll want to make the allowed command set as limited as possible. Having it call run a script for the root commands may be the cleanest way and by far easiest to make secure if you are unfamiliar with sudoer file syntax. For commands/scripts that require the full environment to be loaded, sudo su - -c command works although may be overkill.


What you're describing might be possible with expect.


You can pass a command as an argument to SSH to just run that command on the server, and then exit:

ssh user@host "command to run"

This also works for a list of multiple commands:

ssh user@host "command1; command2; command3"

Or alternatively:

ssh user@host "
        command1
        command2
        command3
"

As other users have pointed out before me, running su on the server will launch a new shell instead of executing subsequent commands in the script as root. What you need to do, is to use either sudo or su -c, and force TTY allocation to SSH with the -t switch (required if you need to enter root password):

ssh -t user@host 'su - -c "command"'
ssh -t user@host 'sudo command'

To sum it all up, one way of accomplishing what you want to do, would be:

#!/bin/bash
ssh -t [email protected] "
        sudo some_command
        sudo service server_instance stop
        sudo some_other_command
"

Since sudo typically remembers you authorization level for a few minutes before asking for the root password again, just prepending sudo to all commands you need to run as root is likely the easiest way to run commands as root on the server. Adding a NOPASSWD rule for your user in /etc/sudoers would make the process even smoother.

I hope this helps :-)