October 13, 2014

Shell scripts with admin privileges in Keyboard Maestro

I try to automate a lot of things using Keyboard Maestro and some things are accomplished using shell scripts. For example I have a couple macros that, when I arrive at a client, get triggered by a connect to their wireless network and set up routing, start some apps etc.

Now you probably know that modifying the routing table requires root privileges and if you trigger a shell script that requires SUDO the normal way, you get one of these:

Nice innit?

There are some messy ways we can solve this, like for example adding the script file name to the sudoers-file as a command that does not require a password. If you are like my, you won't like this approach. I really don't want to do this for each and every script I plan on adding.

The Solution

More like a solution. There are multiple paths here. I can't think of a way to have a console script popup a dialog on a Mac to get the password. Perhaps we could abuse some kind of mac-compatible ssh-askpass thing to accomplish this, but then you have the password and you'd still have to get the script to re-execute as root.. 

So, AppleScript perhaps? 

Since AppleScript can be interactive and you can tell it to run applications with administrator privileges, it seems like a good idea to just have some kind of sudo'ing script that triggers our shell script. 

Turns out this is a lot easier to do than expected:

Just fire up your applescript editor and type in this little thingy:

on run argv
   set script to (item 1 of argv)  
   do shell script script with administrator privileges
end run 

Save the script as sudo.scpt (or whatever you prefer)

So this little gem will actually popup a regular password dialog and then execute whatever shell script you specified as its first argument with admin privileges. In your shell script you just use sudo in front of your commands and it will work.

And in Keyboard Maestro?

Adding this to Keyboard Maestro is not that hard either. You can just use the "Execute Shell Script" action (not AppleScript!) as we will type in a full command line with arguments here. An AppleScript is ran by using osascript so that's what we start with:

And that's it basically. 
You can press the Try button. You'll get a password prompt and then your shell script will be triggered. Obviously you should modify everything to your needs.

Steve out.




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.