How do I run a shell script with administrator privileges through AppleScript without prompting for a password?

StackOverflow https://stackoverflow.com/questions/22161394

  •  19-10-2022
  •  | 
  •  

Question

I want to have my AppleScript application run a Python script with sudo, but I don't want the application to prompt the user for a password (our users do not have sudo privileges).

The Python script has been added to the /etc/sudoers file appropriately (ALL ALL=NOPASSWD: /path/to/script.py). In the terminal, I can do (as a regular, non-privileged user):

$ sudo ./script.py

and it runs perfectly well. But in AppleScript when you try to do:

do shell script "sudo ./script.py"

You of course get the "sudo: no tty present and no askpass program specified" error. But if you change it to:

do shell script "./script.py" with administrator privileges

AppleScript insists on presenting a popup window to ask for the password. I have also tried passing a null password to sudo with a pipe:

do shell script "echo '' | sudo -S ./script.py"

but that also does not work. (I think it tries to run sudo individually first and then pass the command through, which won't work because the user doesn't have sudo privileges!)

I need a solution where AppleScript will run the Python script with sudo. I would prefer the script stays unreadable and un-executable by average users for security reasons, and is only executed through the AppleScript. (I know that, hypothetically, the users could call sudo script.py and it would run, but that's assuming they even know about sudoers; I'm trying to keep it as secure as possible while still usable).

I'm still pretty new to AppleScript, so any help would be greatly appreciated! Thanks!

Was it helpful?

Solution

When I added ALL ALL=NOPASSWD: /Users/myusername/a to sudoers and ran echo $'#!/bin/bash\nsay $(ls ~root|head -n1)'>~/a;chmod +x ~/a, do shell script "sudo ~/a" ran the script as root without requiring a password.

I'm guessing the problem is that you specified the path like do shell script "sudo ./script.py". Try to use do shell script "sudo ~/script.py" instead. The default working directory is for do shell script is / and not ~/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top