Pythonスクリプト内でrootに昇格する方法は?

オタク男

root権限を要求するPythonスクリプトを作成しようとしています。elevate for pythonを使用してみましたが、実行すると「そのようなファイルまたはディレクトリはありません」というエラーが表示されました。

import os
from elevate import elevate

def is_root():
    return os.getuid() == 0

print("before ", is_root())
elevate()
print("after ", is_root())

なぜこれが起こるのですか?システムGUIを利用する実用的な代替手段はありますか?
編集:私はPython 3.6でLinuxを使用していますが、Windowsでも動作するようにしたいと思います。

Orsiris de Jong

これは、WindowsおよびLinuxで動作してUACまたはsudoをrootに昇格させ、コードがNuitkaで解釈、フリーズ、またはコンパイルされているかどうかに関係なく機能する完全なソリューションです。

コードは基本的に、すでに昇格されているかどうかをチェックし、昇格されている場合はmain()関数を実行し、昇格されていない場合は、main()関数を実行する昇格されたサブプロセスを生成します。

それが役に立てば幸い

import os
import sys
import subprocess
import logging

if os.name == 'nt':
    try:
        import ctypes
        # import ctypes  # In order to perform UAC check with ctypes.windll.shell32.ShellExecuteW()
        import win32event  # monitor process
        import win32process  # monitor process
        from win32com.shell.shell import ShellExecuteEx
        from win32com.shell import shellcon
    except ImportError:
        raise ImportError('Cannot import ctypes for checking admin privileges on Windows platform.')


logger = logging.getLogger(__name__)


def main():
    # Your code goes here
    # Keep in mind that elevating under windows will not redirect stdout/stderr to the main process
    print('Hello, elevated world !')


def is_admin():
    """
    Checks whether current program has administrative privileges in OS
    Works with Windows XP SP2+ and most Unixes

    :return: Boolean, True if admin privileges present
    """
    current_os_name = os.name

    # Works with XP SP2 +
    if current_os_name == 'nt':
        try:
            return ctypes.windll.shell32.IsUserAnAdmin() == 1
        except Exception:
            raise EnvironmentError('Cannot check admin privileges')
    elif current_os_name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise EnvironmentError('OS does not seem to be supported for admin check. OS: %s' % current_os_name)


# Improved answer I have done in https://stackoverflow.com/a/49759083/2635443
if __name__ == '__main__':
    if is_admin() is True:  # TODO # WIP
        main(sys.argv)
    else:
        # UAC elevation / sudo code working for CPython, Nuitka >= 0.6.2, PyInstaller, PyExe, CxFreeze

        # Regardless of the runner (CPython, Nuitka or frozen CPython), sys.argv[0] is the relative path to script,
        # sys.argv[1] are the arguments
        # The only exception being CPython on Windows where sys.argv[0] contains absolute path to script
        # Regarless of OS, sys.executable will contain full path to python binary for CPython and Nuitka,
        # and full path to frozen executable on frozen CPython

        # Recapitulative table create with
        # (CentOS 7x64 / Python 3.4 / Nuitka 0.6.1 / PyInstaller 3.4) and
        # (Windows 10 x64 / Python 3.7x32 / Nuitka 0.6.2.10 / PyInstaller 3.4)
        # --------------------------------------------------------------------------------------------------------------
        # | OS  | Variable       | CPython                       | Nuitka               | PyInstaller                  |
        # |------------------------------------------------------------------------------------------------------------|
        # | Lin | argv           | ['./script.py', '-h']         | ['./test', '-h']     | ['./test.py', -h']           |
        # | Lin | sys.executable | /usr/bin/python3.4            | /usr/bin/python3.4   | /absolute/path/to/test       |
        # | Win | argv           | ['C:\\Python\\test.py', '-h'] | ['test', '-h']       | ['test', '-h']               |
        # | Win | sys.executable | C:\Python\python.exe          | C:\Python\Python.exe | C:\absolute\path\to\test.exe |
        # --------------------------------------------------------------------------------------------------------------

        # Nuitka 0.6.2 and newer define builtin __nuitka_binary_dir
        # Nuitka does not set the frozen attribute on sys
        # Nuitka < 0.6.2 can be detected in sloppy ways, ie if not sys.argv[0].endswith('.py') or len(sys.path) < 3
        # Let's assume this will only be compiled with newer nuitka, and remove sloppy detections
        try:
            # Actual if statement not needed, but keeps code inspectors more happy
            if __nuitka_binary_dir is not None:
                is_nuitka_compiled = True
        except NameError:
            is_nuitka_compiled = False

        if is_nuitka_compiled:
            # On nuitka, sys.executable is the python binary, even if it does not exist in standalone,
            # so we need to fill runner with sys.argv[0] absolute path
            runner = os.path.abspath(sys.argv[0])
            arguments = sys.argv[1:]
            # current_dir = os.path.dirname(runner)

            logger.debug('Running elevator as Nuitka with runner [%s]' % runner)
            logger.debug('Arguments are %s' % arguments)

        # If a freezer is used (PyInstaller, cx_freeze, py2exe)
        elif getattr(sys, "frozen", False):
            runner = os.path.abspath(sys.executable)
            arguments = sys.argv[1:]
            # current_dir = os.path.dirname(runner)

            logger.debug('Running elevator as Frozen with runner [%s]' % runner)
            logger.debug('Arguments are %s' % arguments)

        # If standard interpreter CPython is used
        else:
            runner = os.path.abspath(sys.executable)
            arguments = [os.path.abspath(sys.argv[0])] + sys.argv[1:]
            # current_dir = os.path.abspath(sys.argv[0])

            logger.debug('Running elevator as CPython with runner [%s]' % runner)
            logger.debug('Arguments are %s' % arguments)

        if os.name == 'nt':
            # Re-run the program with admin rights
            # Join arguments and double quote each argument in order to prevent space separation
            arguments = ' '.join('"' + arg + '"' for arg in arguments)
            try:
                # Old method using ctypes which does not wait for executable to exit nor deos get exit code
                # See https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-shellexecutew
                # int 0 means SH_HIDE window, 1 is SW_SHOWNORMAL
                # needs the following imports
                # import ctypes

                # ctypes.windll.shell32.ShellExecuteW(None, 'runas', runner, arguments, None, 0)

                # Metthod with exit code that waits for executable to exit, needs the following imports
                # import ctypes  # In order to perform UAC check
                # import win32event  # monitor process
                # import win32process  # monitor process
                # from win32com.shell.shell import ShellExecuteEx
                # from win32com.shell import shellcon

                childProcess = ShellExecuteEx(nShow=0, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                                              lpVerb='runas', lpFile=runner, lpParameters=arguments)
                procHandle = childProcess['hProcess']
                obj = win32event.WaitForSingleObject(procHandle, -1)
                exit_code = win32process.GetExitCodeProcess(procHandle)
                logger.debug('Child exited with code: %s' % exit_code)
                sys.exit(exit_code)

            except Exception as e:
                logger.info(e)
                logger.debug('Trace', exc_info=True)
                sys.exit(255)
        # Linux runner and hopefully Unixes
        else:
            # Search for sudo executable in order to avoid using shell=True with subprocess
            sudo_path = None
            for path in os.environ.get('PATH', ''):
                if os.path.isfile(os.path.join(path, 'sudo')):
                    sudo_path = os.path.join(path, 'sudo')
            if sudo_path is None:
                logger.error('Cannot find sudo executable. Cannot elevate privileges. Trying to run wihtout.')
                main(sys.argv)
            else:
                command = 'sudo "%s"%s%s' % (
                    runner,
                    (' ' if len(arguments) > 0 else ''),
                    ' '.join('"%s"' % argument for argument in arguments)
                )
                try:
                    output = subprocess.check_output(command, stderr=subprocess.STDOUT,
                                                     shell=False, universal_newlines=False)
                    output = output.decode('unicode_escape', errors='ignore')

                    logger.info('Child output: %s' % output)
                    sys.exit(0)
                except subprocess.CalledProcessError as exc:
                    exit_code = exc.returncode
                    logger.error('Child exited with code: %s' % exit_code)
                    try:
                        output = exc.output.decode('unicode_escape', errors='ignore')
                        logger.error('Child outout: %s' % output)
                    except Exception as exc:
                        logger.debug(exc, exc_info=True)
                    sys.exit(exit_code)

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

昇格された特権でシェルスクリプトをリモートで実行する方法

分類Dev

ループ内のインデックスなしでリストにdf.columnを格納する方法は?

分類Dev

昇格されたAHKスクリプトから昇格されていないexeを起動する方法は?

分類Dev

Pythonスクリプト内からUAC昇格をリクエストしますか?

分類Dev

Windowsで昇格された特権でスクリプトを実行するにはどうすればよいですか?

分類Dev

ディレクトリ内のスクリプトに昇格されたアクセス許可を追加する

分類Dev

GoでUAC昇格をリクエストする

分類Dev

initramfsでswitch_rootの前にスクリプトを実行する方法は?

分類Dev

価格エントリに基づいて、配列またはクラスの最初の4つのアイテムを昇順で取得する方法

分類Dev

昇格されたアクセス許可を必要とするAzureWebJobでスクリプトを実行する

分類Dev

ウィジェットを異なる選択で異なるクラスに昇格させる方法は?

分類Dev

msg.payloadをui_templateノードred内のスクリプト変数に格納する方法は?

分類Dev

Dockerコンテナ内で実行されているPythonスクリプトに引数を渡す方法は?

分類Dev

JekyllとLiquidでリストの順序を昇順にする方法は?

分類Dev

Pythonスクリプト内でawscliを使用する方法

分類Dev

jspスクリプトレットでBean値を取得し、JavaScript変数に格納する方法は?

分類Dev

djangoプロジェクト内でPythonスクリプトを実行する方法は?

分類Dev

Pythonスクリプトをbashで「パイプ可能」にする方法は?

分類Dev

スクリプトを/ rootに保持するのは悪い考えですか?

分類Dev

root以外のユーザーにrootアクセスを必要とするコマンドでスクリプトを実行させる最良の方法は?

分類Dev

vue.jsアプリ内でjQueryスクリプトを使用する方法は?

分類Dev

.pyファイルでスクリプトを格納することなく、JavaからPythonスクリプトを実行するには?

分類Dev

他の2つのリストC#からの要素を昇順でリストに格納するにはどうすればよいですか?

分類Dev

スクリプトtest.py(Python)内の2つの異なる関数に個別に格納されている2つの辞書を比較する方法

分類Dev

Pythonの同じグラフにzipリストの上位5と下位5を昇順でプロットするにはどうすればよいですか?

分類Dev

Pythonスクリプトを永久にEC2で実行する方法は?

分類Dev

Pythonスクリプトのubuntuでchromedriverを有効にする方法は?

分類Dev

JavaスクリプトをリンクしてPythonスクリプト内で実行するにはどうすればよいですか?

分類Dev

Python スクリプト内の Python コードを表示するにはどうすればよいですか?

Related 関連記事

  1. 1

    昇格された特権でシェルスクリプトをリモートで実行する方法

  2. 2

    ループ内のインデックスなしでリストにdf.columnを格納する方法は?

  3. 3

    昇格されたAHKスクリプトから昇格されていないexeを起動する方法は?

  4. 4

    Pythonスクリプト内からUAC昇格をリクエストしますか?

  5. 5

    Windowsで昇格された特権でスクリプトを実行するにはどうすればよいですか?

  6. 6

    ディレクトリ内のスクリプトに昇格されたアクセス許可を追加する

  7. 7

    GoでUAC昇格をリクエストする

  8. 8

    initramfsでswitch_rootの前にスクリプトを実行する方法は?

  9. 9

    価格エントリに基づいて、配列またはクラスの最初の4つのアイテムを昇順で取得する方法

  10. 10

    昇格されたアクセス許可を必要とするAzureWebJobでスクリプトを実行する

  11. 11

    ウィジェットを異なる選択で異なるクラスに昇格させる方法は?

  12. 12

    msg.payloadをui_templateノードred内のスクリプト変数に格納する方法は?

  13. 13

    Dockerコンテナ内で実行されているPythonスクリプトに引数を渡す方法は?

  14. 14

    JekyllとLiquidでリストの順序を昇順にする方法は?

  15. 15

    Pythonスクリプト内でawscliを使用する方法

  16. 16

    jspスクリプトレットでBean値を取得し、JavaScript変数に格納する方法は?

  17. 17

    djangoプロジェクト内でPythonスクリプトを実行する方法は?

  18. 18

    Pythonスクリプトをbashで「パイプ可能」にする方法は?

  19. 19

    スクリプトを/ rootに保持するのは悪い考えですか?

  20. 20

    root以外のユーザーにrootアクセスを必要とするコマンドでスクリプトを実行させる最良の方法は?

  21. 21

    vue.jsアプリ内でjQueryスクリプトを使用する方法は?

  22. 22

    .pyファイルでスクリプトを格納することなく、JavaからPythonスクリプトを実行するには?

  23. 23

    他の2つのリストC#からの要素を昇順でリストに格納するにはどうすればよいですか?

  24. 24

    スクリプトtest.py(Python)内の2つの異なる関数に個別に格納されている2つの辞書を比較する方法

  25. 25

    Pythonの同じグラフにzipリストの上位5と下位5を昇順でプロットするにはどうすればよいですか?

  26. 26

    Pythonスクリプトを永久にEC2で実行する方法は?

  27. 27

    Pythonスクリプトのubuntuでchromedriverを有効にする方法は?

  28. 28

    JavaスクリプトをリンクしてPythonスクリプト内で実行するにはどうすればよいですか?

  29. 29

    Python スクリプト内の Python コードを表示するにはどうすればよいですか?

ホットタグ

アーカイブ