【问题标题】:How to "do shell script with administrator privileges" as a regular user and not as root?如何以普通用户而不是 root 身份“以管理员权限执行 shell 脚本”?
【发布时间】:2011-01-25 08:44:57
【问题描述】:

我正在运行一个通过终端运行 shellscript 的 applscript。

我希望能够使用“以管理员权限执行 shell 脚本”,但终端以 root 身份运行我的脚本,而不是以普通用户(即管理员)身份运行。

我不想以 root 身份运行的原因(除了明显的原因)是我使用 ~ 符号,因此任何用户都可以登录并在本地运行脚本(例如,我将日志文件直接写入用户的桌面) .

我不想以 root 身份运行的另一个原因是我在我的 shell 脚本中使用的 ViseX 安装程序不能以 root 身份运行。

这是我使用的 applescript(感谢 regulus6633 提供的 applescript):

set theFile to "myscriptname.sh"

-- launch the application with admin privileges and get the pid of it
set thePID to (do shell script "/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal > /dev/null 2>&1 & echo $!" with administrator privileges) as integer

-- get the bundle identifier of that pid so we can do something with the application
delay 0.2
tell application "System Events"
 set theProcess to first process whose unix id is thePID
 set bi to bundle identifier of theProcess
end tell

-- runs the Terminal with the shellscript
set theFileAlias to (POSIX file theFile) as alias
tell application id bi
 activate
 open theFileAlias
end tell

【问题讨论】:

  • 为什么一定要在终端里面运行脚本???您可以使用 do shell script... 运行脚本本身
  • 我尝试在 applescript 中运行脚本,但没有成功。它只是冻结了。脚本本身需要一些用户输入,它还会向屏幕输出大量数据。

标签: macos shell applescript


【解决方案1】:

我已经找到了通过下一个获得成功的方法:

do shell script "sudo -H -u virtustilus /bin/bash -c \"/bin/bash -c '. ~/.bash_profile; /Users/vis/my_big_script.sh > /Users/vis/someLog.log 2>&1'\"" with administrator privileges

这里发生了什么:

  • 以“root”用户(管理员权限)启动 shell 脚本。
  • 将用户更改为“virtustilus”(我的主要用户)并更改主目录(标志 -H)。
  • 加载 . ~/.bash_profile 环境变量(如 PATH)。
  • 启动脚本 my_big_script.sh 并将所有输出重定向到文件 someLog.log。

它可以工作(我现在在自动机应用程序中使用它)。

【讨论】:

    【解决方案2】:

    不幸的是,with administrator privileges 的意思是“作为根”。在 Mac OS X 中,与大多数其他源自 Unix 的操作系统一样,没有办法以非 root 用户的身份获得管理员权限。当你通过sudo 运行某些东西时,它只是以 root 身份运行命令。

    不过,您不需要以 root 身份运行整个终端窗口。只需以普通用户身份启动终端并告诉它(通过tell application "Terminal" 块内的do script)以root 身份执行所需的命令。我不知道do script 是否接受with administrator privileges,但如果没有,您可以随时在前面贴上sudo

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 2015-07-10
      • 1970-01-01
      • 2022-01-08
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2018-05-11
      相关资源
      最近更新 更多