3

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?

1
  • 1. don't use in sudo su - or sudo or su, but not both together. 2. in ssh you forget to do cd, why not run script directly(without cd), i.e. "sudo su - user2 && /path/only/accessible/to/user2/someScript.sh" Commented Feb 8, 2018 at 17:55

2 Answers 2

2

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"

Sign up to request clarification or add additional context in comments.

3 Comments

why sudo su? don't you think its something wrong? its a bad practice.
Edited (used sudo su as in question from Anthony). Now answer without it
Would have worked but I don't have the rights to execute as user2 on that machine (which is weird, but eh), only to switch user. I'll still mark your answer as accepted for the learning experience. Thanks! The rest of my fight will be with the sysadmin
0

An update if anyone wonders about this.

What I finally did was to log in with an ssh key. My sysadmin had to get involved in order to set it up, but at least it is a viable option.

ssh -i /path/to/sshKey user2@$remoteHost "/path/only/accessible/to/user2/someScript.sh"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.