5

I am new on Swift and I am trying to create a very simple application that executes a root shell command when you press a round button.

I have found the following link online, that explains how to execute a shell command with user permission on swift, but it doesn't tell how to do it with root privileges: http://practicalswift.com/2014/06/25/how-to-execute-shell-commands-from-swift/

How can I do it?

merch
  • 945
  • 8
  • 19
  • do you know about `sudo`? but it's possible that `swift` won't allow `sudo` commands. (I have no direct experience with Swift, so YRMV) Good luck. – shellter Nov 03 '14 at 04:43
  • 1
    nice question, and it's going to be a potentially complicated answer. If I had to answer it, my solution would either use [some form of NSTask](http://stackoverflow.com/questions/5697454/nstask-command-line-tools-and-root) or even better (and more modern), [a tool that makes use of SMJobBless](http://stackoverflow.com/questions/9134841/writing-a-privileged-helper-tool-with-smjobbless), [which *does* have a Swift interface](https://developer.apple.com/librarY/mac/documentation/ServiceManagement/Reference/ServiceManagement_header_reference/index.html#//apple_ref/c/func/SMJobBless) – Michael Dautermann Nov 03 '14 at 05:37
  • I am thinking about using pipe.fileHandleForWriting.writeData to send the password to sudo, but I have not found a lot of documentation in that direction. – merch Nov 04 '14 at 15:47

1 Answers1

6

Quick-and-dirty:

NSAppleScript(source: "do shell script \"sudo whatever\" with administrator " +
    "privileges")!.executeAndReturnError(nil)

Alternatively look into privileged helper tools but expect that to be much more complicated.

John
  • 964
  • 8
  • 21
  • 1
    nice suggestion, but this doesn't use `NSTask` and there might be a good reason why one would want to use `NSTask` ... or something similar at least – Chris May 07 '15 at 15:13