Bash – How to login as different user inside shell script and execute a set of commands

bashshell-script

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.

Best Answer

You can use several ways:

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

su user -c "command"

or

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

Related Question