My requirement is to login as a different user which requires password authentication and execute some commands as that user inside a shell script which I run from my user account.

example: user1 is executing the script. Requirement is to login as user2 using password and execute set of commands using a single shell script.

  • Is password authentication required? Solutions I can think of would require the password to be stored more or less unencrypted in the script, which should not be done. If possible, I would prefer to use ssh otheruser@localhost with keypair for authentication. – Philippos Apr 26 '17 at 5:55

You can use several ways:

  1. Using su. Via su you can exec the command on this way:

su user -c "command"


su - user -c "command"

the difference is when you have dash you will get the environment of target user. With this command you will be asked for the password of target user

  1. Using sudo:

sudo -u user "command"

With this command you execute it with or without password (your password)

  1. Using ssh:

With ssh you can exec the command with password for user, password for the key (if any)

ssh user@localhost "command"

P.S. There are also other possible methods which are rarely possible like rsh

  • This helped me but, there must be someone else out there who thought the quotes were needed. Nope. From my trial-and-error at least with the sudo version: The quotes will not help you. – R.D. Alkire Sep 19 '19 at 1:59

Using the command su [username] allows you to run a command in the context of that user, from the current location. Using the following command su - [username] switches you to that users home directory. If you omit the username you are switching to root.

  • 1
    And the password? Do you want to source it plain from the script? You'd need to sudo the script to avoid be promted for the password. – Philippos Apr 26 '17 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.