Search code examples
linuxshellsshsudosu

Linux shell script - How to switch user and run a script?


I'm currently writing a .sh script to deploy different applications on 4 different machines. Right now I'm having trouble with running a script as another user. I need to log in with myUser with my credentials and then sudo su to user2 to run a specific script.

Normally, I would manually do the following:

ssh myUser@remotehost
[Type in password]
sudo su - user2
cd /path/only/accessible/to/user2
./someScript.sh

when I tried

ssh -t myUser@$remotehost "sudo su - user2 && /path/only/accessible/to/user2 && ./someScript.sh"

I was asked my password, then stayed logged as user2, without any feedback from the script, which would normally give me some informations.

What am I doing wrong?


Solution

  • Try
    ssh -t myUser@$remotehost "sudo -u user2 /path/only/accessible/to/user2/someScript.sh"

    If you need shell access after that you can use
    ssh -t myUser@$remotehost "sudo -u user2 /path/only/accessible/to/user2/someScript.sh && /bin/bash -l"