![](/img/trans.png)
[英]How do I run a shell script with administrator privileges through AppleScript without prompting for a password?
[英]How to “do shell script with administrator privileges” as a regular user and not as root?
我正在運行一個通過Terminal運行ShellScript的應用程序。
我希望能夠使用“以管理員權限執行shell腳本”,但是終端以root身份而不是以普通用戶(這是Admin)身份運行我的腳本。
我不希望以root用戶身份運行的原因(除了顯而易見的原因)是因為我使用〜符號,以便任何用戶都可以登錄並在本地運行腳本(例如,我直接將日志文件寫入用戶的桌面)。
我不想以root用戶身份運行的另一個原因是因為我在shell腳本中使用了ViseX安裝程序,該安裝程序無法以root用戶身份運行。
這是我使用的applescript(感謝applescirpt的regulus6633):
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
不幸的是, with administrator privileges
意味着“以root身份”。 在Mac OS X中,就像在大多數其他Unix派生的操作系統中一樣,沒有辦法以非root用戶身份獲得管理員特權。 通過sudo
運行某些sudo
,它僅以root用戶身份運行命令。
但是,您無需以root用戶身份運行整個“終端”窗口。 只需以普通用戶身份啟動Terminal並告訴它(通過tell application "Terminal"
塊中的do script
)即可以root身份執行所需的命令。 我不知道do script
可以with administrator privileges
接受,但是如果不接受,您總是可以在前面貼一個sudo
。
我已經找到了使下一個成功的方法:
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
這是怎么回事:
. ~/.bash_profile
. ~/.bash_profile
環境變量(例如PATH)。 它有效(我現在在自動程序應用程序中使用它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.