私は、すべて昇格されたアクセス許可を必要とする一連のアプリケーションを実行する方法をパズルで解こうとしてきました。DameWare、MSC.exe、PowerShell.exe、SCCM Manager Consoleなどのアプリケーションはすべて、私の日常業務で使用されています。
私は現在Win7を実行していますが、最終的にはWin10に移行する予定です。私は毎日これらのプログラムを実行していますが、それらを1つずつ実行し、それぞれの名前/パスワードを入力するのは時間がかかります。私は「退屈なものを自動化する」だけで、Pythonにそれをやらせると思った。
この質問(Windowsで昇格された特権でPythonスクリプトを実行する方法)については、答えがあり、「admin」という古いモジュールのコードが投稿されました。ただし、Python 2+で記述されており、Python3.5以降ではうまく機能しません。限られたPythonの知識で知っていることを実行しましたが、実行しようとするとエラーが発生し続けます
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
runAsAdmin('cmd.exe')
File "I:\Scripting\Python\admin.py", line 41, in runAsAdmin
elif type(cmdLine) not in (types.TupleType,types.ListType):
AttributeError: module 'types' has no attribute 'TupleType'
私はいくつかの調査を行いましたが、見つけることができるのはPython 2のドキュメントまたは例だけですが、Python3の変換/同等のものではありません。
これがadmin.pyソースです。Python3.5以降に移行するためにできることを実行しました。あなたが提供できるどんな助けもありがたいです!
#!/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 = input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
Python 3のように見えますがtypes.TupleType
、types.ListType
存在しません。代わりに次のことを試してください。
elif type(cmdLine) not in (tuple, list)
「cmdLineはシーケンスではありません」と言った後の値エラーは、文字列がシーケンスであるため正確ではありませんが、実際にはValueError
。を発生させる必要があります。「cmdLineは空でないタプルまたはリスト、またはNoneである必要があります」と言い換えることができます。cmdLine
文字列以外の反復可能かどうかをより広くチェックするように更新することもできますが、それはやり過ぎかもしれません。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加