簡體   English   中英

如何創建一個Applescript執行終端命令和密碼

[英]How to create an Applescript to execute terminal commands and password

我到處搜尋,但找不到適合我的問題的任何東西。

我想創建一個腳本來復制以下內容:

  1. 開放終端

  2. 執行以下命令:

     sudo kextunload /System/Library/Extensions/AppleHDA.kext 
  3. 然后讓它輸入我的OSX管理員密碼。

  4. 然后執行以下操作:

     sudo kextload /System/Library/Extensions/AppleHDA.kext 

我是applescript的新手,所以希望有人可以幫助我。

謝謝!

關於問題的評論中的提示是正確的(在[Apple] Script Editor中,選擇File > Open Dictionary... ,選擇StandardAdditions.osax ,然后搜索do shell script以查看完整的語法),但請務必注意do shell script不會打開終端窗口; 相反,它將隱藏運行shell命令並返回其結果 -通常更可取:

  • do shell script的返回值是shell命令的stdout輸出。
  • 如果shell命令返回非零退出代碼,AppleScript將拋出錯誤,並且錯誤消息將包含命令的stderr輸出。

要運行具有管理特權的命令,您有2個選項:

  • [ 推薦 ]讓AppleScript 顯示密碼提示
set shCmds to "kextunload /System/Library/Extensions/AppleHDA.kext;
kextload /System/Library/Extensions/AppleHDA.kext"

# This will prompt for an admin password, then execute the commands
# as if they had been run with `sudo`.
do shell script shCmds with administrator privileges  
  • [出於安全考慮, 不建議使用]將密碼作為參數傳遞:
set shCmds to "kextunload /System/Library/Extensions/AppleHDA.kext;
kextload /System/Library/Extensions/AppleHDA.kext"

# Replace `{myPassword}` with your actual password.
# The commands will run as if they had been executed with `sudo`.
do shell script shCmds ¬
   user name short user name of (system info) password "{myPassword}" ¬
   with administrator privileges 

如前所述,如果出了什么問題(無論是由於無效的密碼還是取消了密碼對話框,還是由於shell命令返回了非零退出代碼),都會引發運行時錯誤。 這是一個捕獲它並通過display alert報告它的示例。

try
    do shell script shCmds with administrator privileges
on error errMsg number errNo
    display alert "Executing '" & shCmds & "' failed with error code " & ¬
        errNo & " and the following message: " & errMsg
    return
end try

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM