允许python mac app运行sudo脚本

时间:2015-12-16 15:45:28

标签: python macos shell applescript py2app

我正在创建一个小应用程序,允许我通过状态栏切换到连接到VPN并运行一个小的路由shell脚本。为了构建这个应用程序,我使用了一个名为rumps和py2app的库来生成mac app。

我制作了以下python脚本来处理vpn + shell脚本的启动:

# -*- 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()

我的py2app设置文件如下:

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'],
)

问题是当我在shell中运行main.py时,应用程序可以运行shell脚本。但是当我创建捆绑的应用程序时,即使在向我询问管理员密码之后,应用程序似乎也无法运行shell脚本。

有人知道可能是什么问题吗?

1 个答案:

答案 0 :(得分:1)

所以问题是shell脚本没有与生成的应用捆绑在一起。我通过在导入之后插入来解决这个问题:

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

并在shell中运行生成的应用程序,如下所示:

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

解决方案是使用以下命令生成应用程序:

{{1}}

这种方式允许shell脚本与应用程序捆绑在一起。

相关问题