简体   繁体   中英

How to create an Applescript to execute terminal commands and password

I've searched around but couldn't quite find anything to fit my problem.

I want to create a script to replicate the following:

  1. Open Terminal

  2. Execute the following command:

     sudo kextunload /System/Library/Extensions/AppleHDA.kext 
  3. Then have it enter my OSX admin password for me.

  4. Then execute the following:

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

I'm completely new to applescript, so hoping someone can help me out.

Thanks!

The hint in a comment on the question is correct (in [Apple]Script Editor, select File > Open Dictionary... , select StandardAdditions.osax , then search for do shell script to see the complete syntax), but it's important to note that do shell script will NOT open a Terminal window; instead, it'll run the shell command hidden and return its result - which is generally preferable:

  • do shell script 's return value is the shell command's stdout output.
  • If the shell command returns a non-zero exit code, AppleScript will throw an error and the error message will contain the command's stderr output.

To run commands with administrative privileges, you have 2 options:

  • [ Recommended ] Let AppleScript display a password prompt :
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  
  • [ Not recommended for security reasons] Pass the password as an argument :
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 

As stated, if something goes wrong - whether it is because of an invalid password or a canceled password dialog or the shell commands returning a non-zero exit code - a runtime error is thrown. Here's an example of trapping it and reporting it via 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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