0

I have 2 users: usr1 and usr2. Neither is a root user.

usr1 starts a bash script. And from the script, I want to run some commands as usr2. I understand that the way to do it is:

su -l <usr2> -c "command"

The issue is with passing the password. These are 2 different users with different privileges, so, skipping the password for usr2 is not an option.

This script can go interactive, and ask the user for the password. Is there a way to do this in bash script ?

Note: I am not an expert with scripting. And I have done some research before asking this question, but I couldnt find a suitable answer.

10
  • Would adding the NOPASSWD option in the sudoers file be an option for you? Commented Sep 20, 2018 at 14:30
  • Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See What topics can I ask about here in the Help Center. Perhaps Super User or Unix & Linux Stack Exchange would be a better place to ask. Commented Sep 20, 2018 at 14:33
  • @Jason: Nope, security is of utmost importance, and skipping the password is a big NO Commented Sep 20, 2018 at 14:41
  • @jww thanks for pointing out. I will try other forums Commented Sep 20, 2018 at 14:41
  • Isn't the script already prompting for usr2's password when executed interactively? Can you include a MCVE and terminal transcript? Commented Sep 20, 2018 at 16:25

1 Answer 1

1

You can try using the read read man page command see example below:

#!/bin/bash

read -s -p "Enter your password: " pass
echo $pass

In that case you will need to use /bin/su -c along with sudo -S

#!/bin/bash 

user=$1
read -s -p "Enter pass: " pass
cmd=$(echo $pass|sudo -S <some-command>)
su -c '$cmd' - $user

Where user=$1 additional bash argument, in this case the user id for usr2, then jut run it

$sudo bash -x ./password.sh <target-user>
Sign up to request clarification or add additional context in comments.

2 Comments

The issue is how to use this password for running commands as su -l user
You can try to use /bin/su along with /usr/bin/sudo, I updated my answer to reflex this but, probably a better approach would be to give to use linux file ownership and permissions to control which user can execute it via groups.

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.