简体   繁体   中英

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?

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"

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM