python-如何在Windows上以提升的特权运行脚本?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何在Windows上以提升的特权运行脚本?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3750字,纯文字阅读大概需要6分钟。
内容图文
![python-如何在Windows上以提升的特权运行脚本?](/upload/InfoBanner/zyjiaocheng/947/e82fcb99148a4cbc848da1a725bb0c99.jpg)
我一直在试图弄清楚如何运行一堆都需要提升权限的应用程序.诸如DameWare,MSC.exe,PowerShell.exe和SCCM Manager控制台之类的应用程序都用于我的日常工作中.
我现在正在运行Win7,并计划最终迁移到Win10.每天我运行这些程序,一个一个地运行它们并为每个键入名称/密码是很费时间的.我想我只是“自动化无聊的东西”,然后让Python来做.
在此问题(How to run python script with elevated privilege on windows)上,答案就在那里,并且发布了名为“ admin”的旧模块的代码.但是,它是用Python 2编写的,在Python 3.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文档或示例,而不是Python 3转换/等效文件.
这是admin.py的源代码,我已经尽力将其升级到Python 3.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())
解决方法:
它看起来像type.TupleType和types.ListType在Python 3中不存在.请尝试以下操作:
elif type(cmdLine)不在(元组,列表)
说“ cmdLine不是序列”之后的值错误并不完全准确,因为字符串是序列,但实际上应该引发ValueError.我可能将其改写为“ cmdLine应该是一个非空的元组或列表,或者是None”.您可以对其进行更新,以更广泛地检查cmdLine是否为不可迭代的非字符串,但这可能会显得过大.
内容总结
以上是互联网集市为您收集整理的python-如何在Windows上以提升的特权运行脚本?全部内容,希望文章能够帮你解决python-如何在Windows上以提升的特权运行脚本?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。