Oserror error 13 must be run as administrator

Not running as sudo even added sudo when running under macOS(not sure for linux) #2742 Comments Env: macOS Sierra Python3.5.4 (using installer from the python.org) pip3 install keyboard pip3 install pyinstaller pip3 install pyobjc-framework-Quartz save this code as kb.py (short for keyboard). This may occur under macOS after running sudo python3 kb.py , if […]

Содержание

  1. Not running as sudo even added sudo when running under macOS(not sure for linux) #2742
  2. Comments
  3. Footer

Not running as sudo even added sudo when running under macOS(not sure for linux) #2742

Env:
macOS Sierra
Python3.5.4 (using installer from the python.org)

pip3 install keyboard

pip3 install pyinstaller

pip3 install pyobjc-framework-Quartz

save this code as kb.py (short for keyboard).

This may occur under macOS after running sudo python3 kb.py ,
if there’s no error like this, jump to next step:

Follow this instruction to install the quartz module.

Run pyinstaller kb.spec .

After building, there’s two files in the dist/ folder.

One is the executable file, the other one is the .app file.

Run the executable file with ./dist/kb and you can see the warning on the console.

Ok, then we run with sudo as sudo ./dist/kb . ( Run open ./dist/kb with or without sudo will always report this error.)

Now when we press alt+shift+c , we can see the hello print on the console.

But when we run .app from console, to see the debug output, nothing is output to the console.

If run the .app with sudo , program exit automatically with no any output.

So the problem is, the python program is not running with sudo even I added sudo on running.

The text was updated successfully, but these errors were encountered:

But when we run .app from console, to see the debug output, nothing is output to the console.

Which command is this? Is it sudo open kb.app or sudo kb.app/Contents/MacOS/kb ?

It’s sudo open kb.app only, no /Contents/MacOS/kb in behind.

Any progress?
Or any idea how to debug?

I recompiled the bootloader, added the code to check the uid and gid, they are not 0 even I run with sudo kb.app/Contents/MacOS/kb .
I’ll try to analyze the code to understand how this thing works, in order to gain root privilege.

PyInstaller does not change the uid or gid.

In that case, I don’t understand.
I ran the program with sudo , but the result of geteuid is not 0 . It can’t gain root access.

The problem was with open command. It will not pass the sudo when running.
It will run kb.app/Contents/MacOS/kb; exit; rather then sudo kb.app/Contents/MacOS/kb; exit; .
That’s could be the reason why it’s not running as root.

The problem was with open command

This means, this issue can be closed? If not: Which «open» you are talking about?

Yeah, I think this issue can be closed.
I’ll manage to get admin privilege with osascript .
Thanks

@skys215 I’m having exactly this issue (with both pyinstaller and keyboard); would you mind please explaining what you did to solve the issue, in a little more detail? I’m also going the osascript route right now, thanks to this SO answer, https://stackoverflow.com/a/6463738/1055658, but don’t understand things like exactly WHAT to give access to (the whole .app? A script within it?), when (AS it launches? after?), etc (a naive implementation isn’t working).

But it can’t find my file.

Is the problem that the script doesn’t actually exist anymore, since it’s part of the binary that’s been created? I’ve poked around inside of the .app that pyinstaller creates, and there appears to be mostly just a single compiled file. (I’ve also tried to read the How PyInstaller Works, but am getting bogged down.)

The closest idea I’ve had so far is to write in-line and factor just out the add_hotkey part (also for security reasons, https://stackoverflow.com/questions/25791196/forcing-a-gui-application-to-run-as-root), as in

The problem NOW is that I’m assuming there IS a ‘python’ on the user’s system, which maybe, but there’s MUCH less likely to be python3 which I need — is there a way to use the python that’s been included in the pyinstaller itself? (I haven’t been able to find it.)

Yeah, I’m facing the same problem.
I tried to print ls -al and pwd before calling the osascript , the script exists, but it still return with No such file or directory .
Maybe I should try run pwd inside the do shell script command?

Ps. I have Mac in office, not my home, so I cannot debug it frequently.
Plus, it’s my side project to study using PyQt, so I’m lack of motivation to debug it in the past few months/years.

Still failed to run as sudo.
I’ll open a new issue.

@amloewi @skys215 The way both of you create the command to run is extremely insecure! You are opening a door for shell-escape attacks! You should use the subprocess module to create secure code.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Im trying to make a script where every time I press x, it prints y.

When I run the code:

import keyboard

if keyboard.is_pressed('x'):
    print ("y")

The console outputs:

   raise OSError("Error 13 - Must be run as administrator")
OSError: Error 13 - Must be run as administrator

Thanks!

Error message seems straightforward. Try running it as administrator. Maybe the keyboard module needs that in OSX.
– nog642

Could you also show us the entire console output? I assume that line of code is only the end of the traceback, and you don’t actually have a raise OSError in your code.
– nog642

Yea, here is the entire error: Exception in thread Thread-1: Traceback (most recent call last): File «/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py», line 916, in _bootstrap_inner self.run() File «/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py», line 864, in run self._target(*self._args, **self._kwargs)
– J.Kobayashi

File «/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keyboard/__init__.py», line 292, in listen _os_keyboard.listen(self.direct_callback) File «/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keyboard/_darwinkeyboard.py», line 430, in listen raise OSError(«Error 13 — Must be run as administrator») OSError: Error 13 — Must be run as administrator
– J.Kobayashi

2 Answers

You can’t run this like you normally would in the mac terminal due to a security feature in macOS.

Let’s assume your file name is script.py.

If you type

python3 script.py

in the terminal, it will pop up with the OSError because macOS sees this as a security breach.


You need to run this file as administrator.

In order to do so, you need to type

sudo python3 script.py

It will then ask you for your password as verification. After that, your script should work as expected.

The keyboard module registers global key events (they trigger without application focus) and this requires administrator permissions under MacOS.

Я пытаюсь создать сценарий, в котором каждый раз, когда я нажимаю x, он печатает y.

Когда я запускаю код:

import keyboard

if keyboard.is_pressed('x'):
    print ("y")

Консоль выводит:

   raise OSError("Error 13 - Must be run as administrator")
OSError: Error 13 - Must be run as administrator

Спасибо!

Сообщение об ошибке кажется простым. Попробуйте запустить его от имени администратора. Возможно, это нужно модулю keyboard в OSX.


— nog642

23.10.2018 04:47

Не могли бы вы также показать нам весь вывод консоли? Я предполагаю, что эта строка кода — это только конец трассировки, и у вас фактически нет raise OSError в вашем коде.


— nog642

23.10.2018 04:49

Да, вот и вся ошибка: Исключение в потоке Thread-1: Traceback (последний вызов последний): File «/Library/Frameworks/Python.framework/Versions/3.6/lib/pytho‌ n3.6 / threading.py» , строка 916, в файле _bootstrap_inner self.run () «/Library/Frameworks/Python.framework/Versions/3.6/lib/pytho‌ n3.6 / threading.py», строка 864, при запуске self._target (* self ._args, ** self._kwargs)


— J.Kobayashi

23.10.2018 06:06

Файл «/Library/Frameworks/Python.framework/Versions/3.6/lib/pytho‌ n3.6 / site-packages / k‌ eyboard / __ init __. Py» ‌, строка 292, в listen _os_keyboard.listen (self.direct_callback ) Файл «/Library/Frameworks/Python.framework/Versions/3.6/lib/pytho‌ n3.6 / site-packages / k‌ eyboard / _darwinkeybo‌ ard.py», строка 430, при прослушивании вызывает OSError («Ошибка 13 — Необходимо запускать от имени администратора ») OSError: Ошибка 13 — Необходимо запускать от имени администратора.


— J.Kobayashi

23.10.2018 06:06

Я не уверен, как работать с правами администратора


— J.Kobayashi

23.10.2018 06:19

Можете ли вы отредактировать свой вопрос, чтобы включить полную трассировку? Я мало что знаю об OSX, поэтому ничем не могу помочь, но уверен, что так будет легче кому-то другому ответить на ваш вопрос.


— nog642

23.10.2018 06:52

Скраппинг поиска Apple App Store с помощью Python

Редкие достижения на Github ✨

Мутабельность и переработка объектов в Python

Другой маршрут в Flask Python

Другой маршрут в Flask Python

Flask — это фреймворк, который поддерживает веб-приложения. В этой статье я покажу, как мы можем использовать @app .route в flask, чтобы иметь другую…

14 Задание: Типы данных и структуры данных Python для DevOps

Python PyPDF2 - запись метаданных PDF


Ответы
2

Модуль клавиатуры регистрирует глобальные ключевые события (они запускаются без фокуса приложения), и для этого требуются права администратора в MacOS.

Вы не можете запустить это, как обычно, в терминале Mac из-за функции безопасности в macOS.

Предположим, ваше имя файла — script.py.

Если вы наберете

python3 script.py

В терминале появится сообщение об ошибке OSError, потому что macOS видит в этом нарушение безопасности.


Вам необходимо запустить этот файл от имени администратора.

Для этого вам нужно ввести

sudo python3 script.py

Затем он попросит вас ввести пароль в качестве подтверждения. После этого ваш скрипт должен работать должным образом.

Другие вопросы по теме

Like this post? Please share to your friends:
  • Ose error python
  • Origin как изменить дату рождения
  • Origin seems to be running no communication with orange is possible как исправить
  • Org xml sax saxparseexception related to above error the first definition appears here
  • Org postgresql driver error