Windows에서 높은 권한으로 Python 스크립트를 어떻게 실행할 수 있나요?
Windows에서 높은 권한으로 스크립트 실행
애플리케이션 개발의 많은 작업, 특히 시스템 리소스와 상호작용하거나 관리 작업을 실행할 때 높은 권한이 필요합니다. 이 문서에서는 관리 액세스가 필요한 Python에서 스크립트를 실행할 때 발생하는 특정 문제를 다룹니다.
도전
제공된 코드 샘플은 높은 권한으로 스크립트를 시작하려고 시도합니다. 그러나 스크립트는 권한 프롬프트를 지나 진행되지 않습니다. 해당 문제는 스크립트 실행에 대한 일반적인 오해에 있는 것으로 보입니다.
해결책
제공된 코드는 관리자 권한으로 다시 시작하면 자체 상승이 가능하다는 가정을 기반으로 합니다. . 그러나 Windows의 권한 있는 작업 특성으로 인해 이 접근 방식은 실현 가능하지 않습니다. 대신 외부 메커니즘을 활용하여 권한 상승을 요청해야 합니다.
매우 효과적인 솔루션 중 하나는 Preston Landers가 2010년에 만든 포괄적인 스크립트입니다. 이 스크립트를 사용하면 사용자는 현재 사용자에게 관리 권한이 있는지, 그렇지 않은 경우 쉽게 확인할 수 있습니다. , UAC 권한 상승을 요청하세요. 스크립트는 별도의 창에서 시스템 작업을 나타내는 시각적 피드백을 제공합니다.
Preston Landers 스크립트 사용
다음 스니펫을 사용하여 스크립트를 기본 애플리케이션에 통합할 수 있습니다.
import admin if not admin.isUserAdmin(): admin.runAsAdmin()
전체 스크립트 코드를 확인하실 수 있습니다 아래:
#!/usr/bin/env python # -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4 # (C) COPYRIGHT © Preston Landers 2010 # Released under the same license as Python 2.6.5 import sys, os, traceback, types def isUserAdmin(): if os.name == 'nt': import ctypes # WARNING: requires Windows XP SP2 or higher! try: return ctypes.windll.shell32.IsUserAnAdmin() except: traceback.print_exc() print "Admin check failed, assuming not an admin." return False elif os.name == 'posix': # Check for root on Posix return os.getuid() == 0 else: raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,) def runAsAdmin(cmdLine=None, wait=True): if os.name != 'nt': raise RuntimeError, "This function is only implemented on Windows." import win32api, win32con, win32event, win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon python_exe = sys.executable if cmdLine is None: cmdLine = [python_exe] + sys.argv elif type(cmdLine) not in (types.TupleType,types.ListType): raise ValueError, "cmdLine is not a sequence." cmd = '"%s"' % (cmdLine[0],) # XXX TODO: isn't there a function or something we can call to massage command line params? params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]]) cmdDir = '' showCmd = win32con.SW_SHOWNORMAL #showCmd = win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt. # print "Running", cmd, params # ShellExecute() doesn't seem to allow us to fetch the PID or handle # of the process, so we can't get anything useful from it. Therefore # the more complex ShellExecuteEx() must be used. # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd) procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) #print "Process handle %s returned code %s" % (procHandle, rc) else: rc = None return rc def test(): rc = 0 if not isUserAdmin(): print "You're not an admin.", os.getpid(), "params: ", sys.argv #rc = runAsAdmin(["c:\Windows\notepad.exe"]) rc = runAsAdmin() else: print "You are an admin!", os.getpid(), "params: ", sys.argv rc = 0 x = raw_input('Press Enter to exit.') return rc if __name__ == "__main__": sys.exit(test())
또는 이제 이 스크립트를 PyPi의 Python 패키지로 설치하여 사용할 수 있습니다. 다음 단계를 따르세요.
- pip install pyuac 및 pip install pypiwin32를 사용하여 패키지를 설치합니다.
- 다음과 같이 패키지를 사용합니다.
import pyuac def main(): print("Do stuff here that requires being run as an admin.") # The window will disappear as soon as the program exits! input("Press enter to close the window. >") if __name__ == "__main__": if not pyuac.isUserAdmin(): print("Re-launching as admin!") pyuac.runAsAdmin() else: main() # Already an admin here.
또는 , 데코레이터를 사용하세요:
from pyuac import main_requires_admin @main_requires_admin def main(): print("Do stuff here that requires being run as an admin.") # The window will disappear as soon as the program exits! input("Press enter to close the window. >") if __name__ == "__main__": main()
위 내용은 Windows에서 높은 권한으로 Python 스크립트를 어떻게 실행할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

Linux 터미널에서 Python 사용 ...

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.
