I am a beginner in Python and I require assistance in modifying a script. My objective is to create a Mac application that can change users' passwords and synchronize them with Azure AD tenants. Although the script runs without any error messages, I encounter a launch error when attempting to launch the application, as depicted in the attached image. Python script:
- Python script:
import subprocess
import requests
import json
import getpass
import os
import sys
from AppKit import NSAlert, NSApplication, NSCriticalAlertStyle, NSInformationalAlertStyle
CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
TENANT_ID = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyy'
CLIENT_SECRET = 'zzzzzzzzzzzzzzzzzzzzzzz'
def show_alert(title, message, style):
alert = NSAlert.alloc().init()
alert.setMessageText_(title)
alert.setInformativeText_(message)
alert.setAlertStyle_(style)
alert.addButtonWithTitle_('OK')
return alert.runModal()
def change_password(username):
# Prompt for new password
new_password = getpass.getpass('Enter your new password: ')
# Change local macOS password
subprocess.run(['dscl', '.', '-passwd', f'/Users/{username}', new_password])
# Synchronize password with Azure AD
endpoint = f'https://graph.microsoft.com/{TENANT_ID}/users/{username}/passwordProfile'
headers = {'Authorization': 'Bearer {}'.format(get_access_token())}
payload = {
'forceChangePasswordNextSignIn': False,
'password': new_password
}
response = requests.patch(endpoint, headers=headers, data=json.dumps(payload))
if response.status_code == 204:
show_alert('Success', 'Password changed successfully.', NSInformationalAlertStyle)
else:
show_alert('Error', 'Failed to change password.', NSCriticalAlertStyle)
def get_access_token():
url = f'https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token'
payload = {
'client_id': CLIENT_ID,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': CLIENT_SECRET,
'grant_type': 'client_credentials'
}
response = requests.post(url, data=payload)
access_token = response.json().get('access_token')
return access_token
def main():
username = getpass.getuser()
change_password(username)
if __name__ == '__main__':
app = NSApplication.sharedApplication()
main()
sys.exit(app.run())
#To convert the script into an app#:
- Install py2app:
pip install py2app
- Create a setup.py file with the following contents:
from setuptools import setup
setup(
app=['password_app.py'],
setup_requires=['py2app'],
)
- Run the command to build the app bundle:
python setup.py py2app

I have tried to tweak the script but no luck. I expect a working script