且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何编写一个 shell 脚本,以超级用户身份运行某些命令,而不必以超级用户身份运行某些命令,而不必照看它?

更新时间:2023-10-22 20:53:40

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

运行它:`./sutest'给我

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

但使用 sudo:sudo ./sutest 给出

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

因此,当您以 sudo 身份运行时,您会在 $USERNAME 中保留原始用户名.这导致了类似于其他人发布的解决方案:

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

只需 sudo 首先调用您的脚本,它会提示输入一次密码.

Just sudo to invoke your script in the first place, it will prompt for the password once.

我最初在 Linux 上写了这个答案,这与 OS X 确实有一些差异

I originally wrote this answer on Linux, which does have some differences with OS X

OS X(我在 Mountain Lion 10.8.3 上对此进行测试)有一个环境变量 SUDO_USER 当您运行 sudo 时,可以就地使用上面的 USERNAME ,或者为了更跨平台,脚本可以检查是否设置了 SUDO_USER 并在设置时使用它,如果设置了则使用 USERNAME.

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

更改 OS X 的原始脚本,变成...

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

使其跨平台的第一个尝试可能是......

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.