简体   繁体   中英

Allowing python mac app to run sudo script

I'm making a small app that allows me through a status bar toggle to connect to a vpn and to run a small routing shell script. To build this app I used a library called rumps and py2app to generate the mac app.

I made the following python script that handles the launch of the vpn + the shell script :

# -*- coding: utf-8 -*-

import rumps
from subprocess import call

class MyVPNStatusBarApp(rumps.App):

    @rumps.clicked("MyVPN ON")
    def vpn_on(self, _):
        script_on = False
        try_number = 0
        call("scutil --nc start \"MyVPN\"", shell=True)
        while script_on == False:
            if call("scutil --nc show \"MyVPN\" | grep  -q \"Connected\"", shell=True) == 0:
                call("/usr/bin/osascript -e \'do shell script \"./web_routes.sh args 2>&1 etc\" with administrator privileges\'", shell=True)
                rumps.notification(
                    "VPN Status", "VPN + Internet Access", 'Granted')
                script_on = True
            elif try_number == 20:
                print 'TIME OUT'
                return     
            else:
                time.sleep(0.1)
                try_number += 1 

    @rumps.clicked("MyVPN OFF")
    def vpn_off(self, _):
        call("scutil --nc stop \"MyVPN\"", shell=True)
        rumps.notification(
            "VPN Status", "VPN OFF", 'Internet should work')


if __name__ == "__main__":
    MyVPNStatusBarApp("VPN").run()

My py2app setup file is as follow :

from setuptools import setup

APP = ['main.py']
DATA_FILES = []
OPTIONS = {
    'argv_emulation': True,
    'plist': {
        'LSUIElement': True,
    },
    'packages': ['rumps'],
}

setup(
    app=APP,
    name='MyVPN',
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

The problem is that when I run my main.py in the shell, the app is able to run the shell script. But when I make the bundled app, the app seems not able to run the shell script even after asking me for the admin password.

Do somebody know what might be the issue ?

So the issue was that the shell script wasn't bundled with the generated app. I figured out this by putting just after the imports:

rumps.debug_mode(True)

and running the generated app in the shell like this:

./dist/MyVPN.app/Contents/MacOS/MyVPN

The solution was to generate the app with this command:

> sudo python setup.py py2app --resources web_routes.sh

This way allows the shell script to be bundled with the app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM