简体   繁体   English

以与bash脚本不同的用户身份运行命令

[英]Running commands as different user from bash script

I have 2 users: usr1 and usr2. 我有2个用户:usr1和usr2。 Neither is a root user. root用户也不是。

usr1 starts a bash script. usr1启动一个bash脚本。 And from the script, I want to run some commands as usr2. 从脚本中,我想将某些命令作为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. 这是2个具有不同特权的不同用户,因此,不能跳过usr2的密码。

This script can go interactive, and ask the user for the password. 该脚本可以进行交互,并询问用户密码。 Is there a way to do this in bash script ? bash脚本中有没有办法做到这一点?

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: 您可以尝试使用read read man page命令,请参见以下示例:

#!/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 / su -c与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 其中user = $ 1另外的bash参数,在本例中为usr2的用户ID,然后突出运行它

$sudo bash -x ./password.sh <target-user>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM