The weird part is, I can get it to successfully call the apple script dialog with this code when running on all my test machines:
#call applescript for user popup
osa = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
buttonReturn = osa.communicate(userPopup)
buttonReturn = str(buttonReturn[0]).strip()
print(buttonReturn)
However, when it's sent in a policy set to recurring check-in to our user base, that's when I'm getting the errors about osascript failing out due to it running as the root user.. why would it work on my test machines, when I'm allowing the recurring check in to hit just like it is on our production machines?
Not sure if this helps, but I was able to confirm the same thing. For some reason, running sudo -u
in Popen is not working.
I was able to use the subprocess.run
command instead and that worked in my test. However, that requires Python3.6+. While Apple supplies Python3.7.3, it requires an addition download the XCode Command Line tools. You would have to install it before you could run your script.
Here is my version of your code modified to use subprocess.run
#!/usr/bin/python3
import subprocess
userPopup = 'display dialog "Prompt" with title "Title" default answer "Default" default button "OK" cancel button "Cancel"'
#get the current logged in user
user = subprocess.run(["/usr/bin/stat", "-f", "'%Su'", "/dev/console"], capture_output=True, text=True)
output = user.stdout # Copy stdout from the last command to the variable
accountName = output.strip().strip("'") # Strip any line feed and the ' around the ouput
print(accountName)
osa = subprocess.run(['sudo', '-u', accountName, 'osascript', '-e', userPopup], capture_output=True, text=True)
result = osa.stdout
result = result.split(",")
try: # Try and split the output between Button and Text Result. If cancel was selected, no result is printed.
button = result[0].split(":")[1]
textResult = result[1].split(":")[1]
except IndexError: # Since "Cancel" was printed just assign the variables.
button = "Cancel"
textResult = ""
print(button, textResult)
Not sure if that is helpful to you or not.
I rarely write my Applescript codes in Python,
but in Bash I often use the launchctl with the User's ID:
#!/bin/sh
## Current User
CURRENT_USER=$(ls -l /dev/console | awk '{print $3}')
CURRENT_USER_UID=$(id -u $CURRENT_USER)
launchctl asuser $CURRENT_USER_UID osascript -e 'tell app "System Events" to log out'
*As I wrote this I saw Rich has a guide on using launchctl which includes python: Running processes in OS X as the logged-in user from outside the user’s account