简体   繁体   中英

Running commands as different user from bash script

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.

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>

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