如何在 Windows 上以提升的权限运行脚本?

2024-01-03

我一直在试图弄清楚如何运行一堆都需要提升权限的应用程序。 DameWare、MSC.exe、PowerShell.exe 和 SCCM Manager Console 等应用程序都在我的日常工作中使用。

我现在运行的是Win7,计划最终迁移到Win10。我每天都运行这些程序,一一运行它们并为每个程序输入名称/密码非常耗时。我想我应该“自动化那些无聊的事情”并让 Python 来做。

关于这个问题(如何在 Windows 上以提升的权限运行 python 脚本 https://stackoverflow.com/questions/19672352/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())

看起来像types.TupleType and types.ListTypePython 3 中不存在。请尝试以下操作:

elif type(cmdLine) not in (tuple, list)

说“cmdLine 不是序列”后的值错误并不完全准确,因为字符串是序列,但确实应该引发ValueError。我可能会将其改写为“cmdLine 应该是非空元组或列表,或者 None”。您可以更新它以更广泛地检查是否cmdLine是一个非字符串可迭代对象,但这可能有点矫枉过正。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Windows 上以提升的权限运行脚本? 的相关文章

随机推荐

  • 将 ImageView ScaleType 设置为“center”并没有像我预期的那样工作

    我的布局如下ImageView
  • Entity Framework 6 - 如何在调用 SaveChanges 之前查看将为插入生成的 SQL

    在实体框架 6 中 是否可以查看将为某个对象执行的 SQLinsert before调用 SaveChanges using var db new StuffEntities db Things Add new Thing can I ge
  • [JsonProperty] 在 C# 中有何用途?

    例如 为什么下面的代码需要它 如何进一步使用它 public class FileAttachment JsonProperty fileName public string FileName get set Per 文档 https ww
  • Python 线程上 daemon 属性的含义

    我对将线程设置为守护进程意味着什么有点困惑 文档是这样说的 线程可以被标记为 守护进程 线 这面旗帜的意义 是整个Python程序 仅当守护线程存在时退出 左边 初始值被继承 来自创建线程 旗帜可以 通过 daemon 属性进行设置 我不确
  • 打印和放置有什么区别?

    例如我写的这行代码 print and puts产生不同的结果 1 upto 1000 each i print i if i 2 0 puts如果还没有一行 则在每个参数的末尾添加一个新行 print不添加新行 例如 puts 1 2 3
  • 使矩阵数字和名称顺序

    我有以下数据 yvar lt c 1 150 replication lt c rep c rep 1 10 rep 2 10 rep 3 10 5 genotypes lt c rep paste G 1 10 sep 15 enviro
  • 如何使用企业库日志记录仅编写消息来调试输出?

    我想使用 EntLib Logging 实现日志记录 并为类别 调试 连接两个 TraceListener 一个会将这些消息写入文件 另一个会将它们输出到系统跟踪输出 与 Debug Write 的方式相同 以便我可以使用 Sysinter
  • 更改现有数据库上的哈希函数

    我正在阅读一些有关密码哈希的内容 我见过 SHA 256 gt MD5 这让我思考应用程序如何处理从一种哈希函数到另一种哈希函数的变化 如果有人实现一个使用 MD5 对其密码进行哈希处理的应用程序 会发生什么情况 然后他们决定 SHA 25
  • 在scala中读取UTF-8格式的xml

    我正在尝试使用以下代码将文件读取为 xml import scala xml object HebrewToEnglishCityTranslator val data XML loadFile cities hebrew utf xml
  • 根据设备屏幕尺寸(hdpi/ldpi/mdpi)调用函数

    在 mdpi 设备上我想调用这个方法 final float scale getResources getDisplayMetrics density double height px 45 scale 0 5 但当应用程序在 hdpi 设
  • 《apyori模块的RelationRecord对象》apriori算法python

    请原谅我的英语不好 我试图识别一组数据中经常出现的属性 以使用 python 的 apyori 包推断出分类 我正在练习 20772 笔交易的数据框 最大的交易是 543 项 数据框 https i stack imgur com a2c9
  • 将分数转换为十六进制

    假设您有一个数字 28 5 您需要将其转换为十六进制 28 是 1C 29 是 1D 但是 28 5 会是什么呢 你甚至可以转换它吗 我问这个是因为我正在用 JavaScript jsyk 制作一个转换器 Use n toString 16
  • 将 php 脚本作为守护进程运行

    我需要运行一个 php 脚本作为守护进程 等待指令并执行操作 cron 作业不会为我做这件事 因为指令到达后需要立即采取行动 我知道由于内存管理问题 PHP 并不是守护进程的最佳选择 但由于各种原因 我在这种情况下必须使用 PHP 我遇到了
  • 在C中逐行读取文件

    Preface 这道题是关于逐行读取文件 并将每一行插入到一个链表中 我已经编写了链表的实现 并测试了insert 手动功能 这有效 我还编写了从文件中读取文本并将其写出的代码 同样 这也有效 好的 这是我的问题 我怎样才能合并这些概念 以
  • Dart:将十进制转换为十六进制

    我一直在寻找一种在 Dart 编程语言中将十进制数转换为十六进制格式的方法 The hex encode方法中的HexCodec例如 类无法转换十进制 1111 其十六进制值为 457 而是给出异常 FormatException 无效字节
  • 我应该在函数中抛出 IllegalArgumentException 吗?

    我正在构建一个包含大量计算的科学软件 当然参数可能有错误的长度等 所以我使用IllegalArgumentException类 因为它似乎是这个问题的正确名称 但我应该把throws IllegalArgumentException在函数定
  • 如何使用 python 中的循环创建多个目录?

    我想用循环创建 10 个目录 我尝试了以下代码 import os pathname 1 directory C Directory Path Name str pathname while pathname lt 11 if not os
  • 右移和有符号整数

    在我的编译器上 以下伪代码 值替换为二进制 sint32 word 10000000 00000000 00000000 00000000 word gt gt 16 产生一个word位字段如下所示 11111111 11111111 10
  • 在tomcat中共享文件夹

    如何使用 tomcat 6 浏览器访问文件夹 我想我需要向 web xml 添加上下文 我想 所以当我导航到http localhost 8080 myfiles http localhost 8080 myfiles我希望看到 c tem
  • 如何在 Windows 上以提升的权限运行脚本?

    我一直在试图弄清楚如何运行一堆都需要提升权限的应用程序 DameWare MSC exe PowerShell exe 和 SCCM Manager Console 等应用程序都在我的日常工作中使用 我现在运行的是Win7 计划最终迁移到W