How do I execute commands that require administrator privileges from Swift?

Asked 2 years ago, Updated 2 years ago, 37 views

I am currently running it as follows, but when the password is incorrect, the application gets stuck.

swift

let task=NSTask.launchedTaskWithLaunchPath("/bin/sh", arguments: ["-c", "/AAAA.sh", "sleep3")
 task.waitUntilExit()

AAAA.sh

 echo "password" | sudo-Sapachectl start

To avoid this,

  • How to check your password beforehand
  • How to Detect Sudo Failures

Could you tell me one of the following?

swift macos

2022-09-30 19:39

1 Answers

Check the terminationStatus to see if the shell script was successful.
However, this alone will not determine whether the password was incorrect or subsequent command execution failed.

let task=NSTask.launchedTaskWithLaunchPath("/bin/sh", arguments: ["-c", "/AAAA.sh")
task.waitUntilExit()

if task.terminationStatus!=0{
    // failure
}

If you want to determine if the password is wrong first, how about running only the dummy sudo to check the terminationStatus first?

 echo "password" | sudo-St true


2022-09-30 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.