如何使用 Python 在 windows 机器上远程获取已安装的证书?

How to get installed certificates on a windows machine remotely with Python?

我想远程查询一些 Windows 机器,并获取它们的证书存储详细信息(已安装的证书名称、到期时间和指纹)。 我正在使用 Python 2.7.

如何做到这一点?我对 pywin32wmi 包没有任何运气。

遗憾的是,最简单的解决方案是实际启动 powershell 进程并通过 Invoke-Command cmdlet 请求数据:

def run_powershell(scriptblock, cwd=os.getcwd()):
    log.debug("Running PowerShell Block:\r\n%s", scriptblock)
    log.debug("Current Directory: %s\r\n" % cwd)
    psProc = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                                '-ExecutionPolicy', 'Bypass',
                                '-noprofile',
                                '-c', '-',],
                                cwd=cwd,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
    stdoutdata, stderrdata = psProc.communicate(scriptblock)

    if stdoutdata:
        log.debug("Script Output:\r\n%s" % stdoutdata)
    elif not stderrdata:
        log.debug("Script completed succssfully (no stdout/stderr).")
    if stderrdata:
        log.error("Script Error:\r\n%s" % stderrdata)

    return stdoutdata, stderrdata


def get_certificates(server_list, location="LocalMachine", store="My"):
    cmd = '''
$sb = { ls Cert:\%s\%s | Select Subject,ThumbPrint }
$Servers = '%s' | ConvertFrom-Json

Invoke-Command -ComputerName $Servers -ScriptBlock $sb -Authentication Negotiate | ConvertTo-Json -Depth 999
    ''' % (location, store, json.dumps(server_list))
    stdoutdata, stderrdata = run_powershell(cmd)
    return json.loads(stdoutdata)