Linux – How to run a command as another user on Linux

bashcommand linelinuxshellssh

I have access to a linux server where I can sudo to 'foo' like this without a password:

sudo su - foo

Once I am the 'foo' user I am able to run a script like this:

/dir/foo_user_script.sh

The 'foo_user_script' is only executable by the foo user and not by my user. Thus I can run the script by first changing to the 'foo' user and then running the script.

However, I am trying to automate some processes using the Java SSH client ganymed. Ganymed's faq suggests that to run multiple commands I should use a contruct like:

Session.execCommand("echo Hello && echo again")

I tried something like this, but the second command (the foo_user_script) did not execute:

Session.execCommand("sudo su - foo && /dir/foo_user_script.sh")

I think this doesn't work because su launches a new shell.

Is there any way for me to run the /dir/foo_user_script.sh script in a single command?

Note:
"sudo -l" shows me this:

(root) NOPASSWD: /bin/su - foo

Thanks for the help!

Best Answer

sudo -u foo /dir/foo_user_script.sh