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 user@172.1.1.101 "
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 :-)