gpt4 book ai didi

python - 从 32 位 python 运行 64 位 powershell

转载 作者:行者123 更新时间:2023-11-28 18:56:40 24 4
gpt4 key购买 nike

我在 Windows Server 2012 R2 standard 机器上运行 32 位 python。
我正在尝试为 64 位系统运行 powershell 脚本,检查注册表中是否存在 key :

$path = "Registry::HKLM\Software\<folder>"
if (!(Test-Path $path))
{
write "$path does not exist!"
}

当通过 powershell 运行时,脚本运行完美。
当我从 python 运行它时,它找不到 key :

from gevent.subprocess import call
call("powershell <script.ps1>, shell=True")

经过一番研究,我发现32位的python进程正在调用32位版本的powershell
我用这个简单的脚本验证了它,该脚本检查运行的进程是 32 位还是 64 位:

powershell [System.Environment]::Is64BitProcess

将为 64 位进程返回 True,为 32 位进程返回 False
手动检查此命令是否有效:

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe [System.Environment]::Is64BitProcess

返回 False,因为这是 32 位版本的 powershell(是的,由于 WOW64 文件夹而非常困惑)。

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe [System.Environment]::Is64BitProcess

返回 True。但是运行:

from gevent.subprocess import call
call("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe [System.Environment]::Is64BitProcess", shell=True)

返回False
我错过了什么?

最佳答案

您缺少的是 Windows 透明 redirects file system calls从 32 位进程到 C:\Windows\System32C:\Windows\SysWOW64 :)

有一个简单的解决方案 - 如果 32 位进程试图从 C:\Windows\sysnative 获取文件系统资源相反,Windows 不会重定向到 SysWOW64 .

从 PowerShell 相当容易 figure out您的进程是否会受到所有这些 SysWOW64 重定向的影响,基本上:

$IsSysWOW64Process = [Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess

然而,在 python 中,我还没有找到一个万无一失的方法,所以我怀疑你最好的选择是调用 kernel32!IsWow64Process2()通过ctypes :

from ctypes import windll,c_ushort,byref
import platform

def is_syswow64_process():
if platform.architecture()[0] != '64bit':
# 32-bit OS, no syswow64 handling
return False

# Ok, 64-bit OS, let's see if the process is 32-bit
# Obtain process handle to self
this_process = windll.kernel32.GetCurrentProcess()

# Declare ref arguments
proc_type, platform_type = c_ushort(), c_ushort()

# Query Windows for the information
wow64_call = windll.kernel32.IsWow64Process2(this_process, byref(proc_type), byref(platform_type))

if wow64_call == 0:
# you'd probably want to call kernel32!GetLastError here
raise Exception("Problem querying kernel32!IsWow64Process2")

return proc_type.value == 0

现在您可以在需要时有条件地替换路径:

powershell = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"

if is_syswow64_process():
powershell = re.sub("(?i)syswow64|system32", "sysnative", powershell)

call("%s .\path\to\script.ps1" % powershell)

关于python - 从 32 位 python 运行 64 位 powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com