Jeremyy44
Jeremyy44

Reputation: 7

Run a command as su - through ssh through a bash script

Hi so basicly what I am trying to do is run a script that is located on the remote server as root by running su - before running the script.

I need to run the script after running the command su - otherwise it wont run. And at the state that the server will be sudo isnt installed yet.

Right now I have ssh -t $USERNAME@$IP "su - && /home/$USERNAME/firstboot/firstboot.sh" but it connects me as su - on the remote server but dosnt execute the script.

Any idea would be greatly apreciated thank you.

Upvotes: 0

Views: 2125

Answers (1)

larsks
larsks

Reputation: 311328

Right now I have ssh -t $USERNAME@$IP "su - && /home/$USERNAME/firstboot/firstboot.sh" but it connects me as su - on the remote server but dosnt execute the script.

Fundamentally, you can't use su like that. Forget ssh for a moment; if you run su - && date, the date command will only execute after the su shell has exited (because command1 && command2 means "run command1 first, and if it exits successfully, run command2).

You need to use the -c option to su if you want to run a command in the su environment:

su - -c date

In your script, that means you want to run:

su - -c /home/$USERNAME/firstboot/firstboot.sh

So your ssh command should look like:

ssh -t $USERNAME@$IP su - -c /home/$USERNAME/firstboot/firstboot.sh

Upvotes: 1

Related Questions