python - 允许 python mac 应用程序运行 sudo 脚本

标签 python macos shell applescript py2app

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

我制作了以下 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 脚本。

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

最佳答案

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

rumps.debug_mode(True)

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

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

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

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

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

关于python - 允许 python mac 应用程序运行 sudo 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34316259/

相关文章:

python - 更改 Mayavi 中的间距

python - 使用 cython 分配到任意数组位置。分配速度取决于值?

python - 将pybind11嵌入虚拟环境

css - 如何在 Mac Bluefish 文本编辑器中重新映射 CSS 快捷键

objective-c - 在 OSX 中,如何确定窗口的位置以及哪个窗口处于事件状态?

node.js - 无法访问 NPM 环境变量

python - 在 Linux 上的 python 中检测连接到 Raspberry Pi 的无线设备

python - 使用 Python 和 lxml 仅去除具有特定属性/值的标签

linux - sed 行删除是原子的吗?

bash - 在bash脚本中从ffmpeg捕获错误